context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public class BufferedStream_StreamAsync : StreamAsync
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ConcurrentOperationsAreSerialized(bool apm)
{
byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)i).ToArray();
var mcaos = new ManuallyReleaseAsyncOperationsStream();
var stream = new BufferedStream(mcaos, 1);
var tasks = new Task[4];
for (int i = 0; i < 4; i++)
{
tasks[i] = apm ?
Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, data, 250 * i, 250, null) :
stream.WriteAsync(data, 250 * i, 250);
}
Assert.False(tasks.All(t => t.IsCompleted));
mcaos.Release();
await Task.WhenAll(tasks);
stream.Position = 0;
for (int i = 0; i < tasks.Length; i++)
{
Assert.Equal(i, stream.ReadByte());
}
}
[Fact]
public void UnderlyingStreamThrowsExceptions()
{
var stream = new BufferedStream(new ThrowsExceptionFromAsyncOperationsStream());
Assert.Equal(TaskStatus.Faulted, stream.ReadAsync(new byte[1], 0, 1).Status);
Assert.Equal(TaskStatus.Faulted, stream.WriteAsync(new byte[10000], 0, 10000).Status);
Assert.Equal(TaskStatus.Faulted, Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, new byte[10000], 0, 10000, null).Status);
stream.WriteByte(1);
Assert.Equal(TaskStatus.Faulted, stream.FlushAsync().Status);
}
}
public class BufferedStream_StreamMethods : StreamMethods
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
protected override Stream CreateStream(int bufferSize)
{
return new BufferedStream(new MemoryStream(), bufferSize);
}
}
public class BufferedStream_TestLeaveOpen : TestLeaveOpen
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamWriterWithBufferedStream_CloseTests : CloseTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamWriterWithBufferedStream_FlushTests : FlushTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
[Fact]
public void WriteAfterRead_NonSeekableStream_Throws()
{
var wrapped = new WrappedMemoryStream(canRead: true, canWrite: true, canSeek: false, data: new byte[] { 1, 2, 3, 4, 5 });
var s = new BufferedStream(wrapped);
s.Read(new byte[3], 0, 3);
Assert.Throws<NotSupportedException>(() => s.Write(new byte[10], 0, 10));
}
}
public class StreamWriterWithBufferedStream_WriteTests : WriteTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamReaderWithBufferedStream_Tests : StreamReaderTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
protected override Stream GetSmallStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
return new BufferedStream(new MemoryStream(testData));
}
protected override Stream GetLargeStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
List<byte> data = new List<byte>();
for (int i = 0; i < 1000; i++)
{
data.AddRange(testData);
}
return new BufferedStream(new MemoryStream(data.ToArray()));
}
}
public class BinaryWriterWithBufferedStream_Tests : BinaryWriterTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
[Fact]
public override void BinaryWriter_FlushTests()
{
// [] Check that flush updates the underlying stream
using (Stream memstr2 = CreateStream())
using (BinaryWriter bw2 = new BinaryWriter(memstr2))
{
string str = "HelloWorld";
int expectedLength = str.Length + 1; // 1 for 7-bit encoded length
bw2.Write(str);
Assert.Equal(expectedLength, memstr2.Length);
bw2.Flush();
Assert.Equal(expectedLength, memstr2.Length);
}
// [] Flushing a closed writer may throw an exception depending on the underlying stream
using (Stream memstr2 = CreateStream())
{
BinaryWriter bw2 = new BinaryWriter(memstr2);
bw2.Dispose();
Assert.Throws<ObjectDisposedException>(() => bw2.Flush());
}
}
}
public class BinaryWriterWithBufferedStream_WriteByteCharTests : BinaryWriter_WriteByteCharTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class BinaryWriterWithBufferedStream_WriteTests : BinaryWriter_WriteTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
internal sealed class ManuallyReleaseAsyncOperationsStream : MemoryStream
{
private readonly TaskCompletionSource<bool> _tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
public void Release() { _tcs.SetResult(true); }
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _tcs.Task;
return await base.ReadAsync(buffer, offset, count, cancellationToken);
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _tcs.Task;
await base.WriteAsync(buffer, offset, count, cancellationToken);
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
await _tcs.Task;
await base.FlushAsync(cancellationToken);
}
}
internal sealed class ThrowsExceptionFromAsyncOperationsStream : MemoryStream
{
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new InvalidOperationException("Exception from ReadAsync");
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new InvalidOperationException("Exception from BeginRead");
}
public override int EndRead(IAsyncResult asyncResult)
{
throw new InvalidOperationException("Exception from EndRead");
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new InvalidOperationException("Exception from WriteAsync");
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new InvalidOperationException("Exception from BeginWrite");
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new InvalidOperationException("Exception from EndWrite");
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
throw new InvalidOperationException("Exception from FlushAsync");
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.IdentityManagement
{
/// <summary>
/// Constants used for properties of type AssignmentStatusType.
/// </summary>
public class AssignmentStatusType : ConstantClass
{
/// <summary>
/// Constant Any for AssignmentStatusType
/// </summary>
public static readonly AssignmentStatusType Any = new AssignmentStatusType("Any");
/// <summary>
/// Constant Assigned for AssignmentStatusType
/// </summary>
public static readonly AssignmentStatusType Assigned = new AssignmentStatusType("Assigned");
/// <summary>
/// Constant Unassigned for AssignmentStatusType
/// </summary>
public static readonly AssignmentStatusType Unassigned = new AssignmentStatusType("Unassigned");
/// <summary>
/// Default Constructor
/// </summary>
public AssignmentStatusType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static AssignmentStatusType FindValue(string value)
{
return FindValue<AssignmentStatusType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator AssignmentStatusType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ContextKeyTypeEnum.
/// </summary>
public class ContextKeyTypeEnum : ConstantClass
{
/// <summary>
/// Constant Binary for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum Binary = new ContextKeyTypeEnum("binary");
/// <summary>
/// Constant BinaryList for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum BinaryList = new ContextKeyTypeEnum("binaryList");
/// <summary>
/// Constant Boolean for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum Boolean = new ContextKeyTypeEnum("boolean");
/// <summary>
/// Constant BooleanList for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum BooleanList = new ContextKeyTypeEnum("booleanList");
/// <summary>
/// Constant Date for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum Date = new ContextKeyTypeEnum("date");
/// <summary>
/// Constant DateList for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum DateList = new ContextKeyTypeEnum("dateList");
/// <summary>
/// Constant Ip for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum Ip = new ContextKeyTypeEnum("ip");
/// <summary>
/// Constant IpList for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum IpList = new ContextKeyTypeEnum("ipList");
/// <summary>
/// Constant Numeric for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum Numeric = new ContextKeyTypeEnum("numeric");
/// <summary>
/// Constant NumericList for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum NumericList = new ContextKeyTypeEnum("numericList");
/// <summary>
/// Constant String for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum String = new ContextKeyTypeEnum("string");
/// <summary>
/// Constant StringList for ContextKeyTypeEnum
/// </summary>
public static readonly ContextKeyTypeEnum StringList = new ContextKeyTypeEnum("stringList");
/// <summary>
/// Default Constructor
/// </summary>
public ContextKeyTypeEnum(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ContextKeyTypeEnum FindValue(string value)
{
return FindValue<ContextKeyTypeEnum>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ContextKeyTypeEnum(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type EncodingType.
/// </summary>
public class EncodingType : ConstantClass
{
/// <summary>
/// Constant PEM for EncodingType
/// </summary>
public static readonly EncodingType PEM = new EncodingType("PEM");
/// <summary>
/// Constant SSH for EncodingType
/// </summary>
public static readonly EncodingType SSH = new EncodingType("SSH");
/// <summary>
/// Default Constructor
/// </summary>
public EncodingType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static EncodingType FindValue(string value)
{
return FindValue<EncodingType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator EncodingType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type EntityType.
/// </summary>
public class EntityType : ConstantClass
{
/// <summary>
/// Constant AWSManagedPolicy for EntityType
/// </summary>
public static readonly EntityType AWSManagedPolicy = new EntityType("AWSManagedPolicy");
/// <summary>
/// Constant Group for EntityType
/// </summary>
public static readonly EntityType Group = new EntityType("Group");
/// <summary>
/// Constant LocalManagedPolicy for EntityType
/// </summary>
public static readonly EntityType LocalManagedPolicy = new EntityType("LocalManagedPolicy");
/// <summary>
/// Constant Role for EntityType
/// </summary>
public static readonly EntityType Role = new EntityType("Role");
/// <summary>
/// Constant User for EntityType
/// </summary>
public static readonly EntityType User = new EntityType("User");
/// <summary>
/// Default Constructor
/// </summary>
public EntityType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static EntityType FindValue(string value)
{
return FindValue<EntityType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator EntityType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type PolicyEvaluationDecisionType.
/// </summary>
public class PolicyEvaluationDecisionType : ConstantClass
{
/// <summary>
/// Constant Allowed for PolicyEvaluationDecisionType
/// </summary>
public static readonly PolicyEvaluationDecisionType Allowed = new PolicyEvaluationDecisionType("allowed");
/// <summary>
/// Constant ExplicitDeny for PolicyEvaluationDecisionType
/// </summary>
public static readonly PolicyEvaluationDecisionType ExplicitDeny = new PolicyEvaluationDecisionType("explicitDeny");
/// <summary>
/// Constant ImplicitDeny for PolicyEvaluationDecisionType
/// </summary>
public static readonly PolicyEvaluationDecisionType ImplicitDeny = new PolicyEvaluationDecisionType("implicitDeny");
/// <summary>
/// Default Constructor
/// </summary>
public PolicyEvaluationDecisionType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static PolicyEvaluationDecisionType FindValue(string value)
{
return FindValue<PolicyEvaluationDecisionType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator PolicyEvaluationDecisionType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type PolicyScopeType.
/// </summary>
public class PolicyScopeType : ConstantClass
{
/// <summary>
/// Constant All for PolicyScopeType
/// </summary>
public static readonly PolicyScopeType All = new PolicyScopeType("All");
/// <summary>
/// Constant AWS for PolicyScopeType
/// </summary>
public static readonly PolicyScopeType AWS = new PolicyScopeType("AWS");
/// <summary>
/// Constant Local for PolicyScopeType
/// </summary>
public static readonly PolicyScopeType Local = new PolicyScopeType("Local");
/// <summary>
/// Default Constructor
/// </summary>
public PolicyScopeType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static PolicyScopeType FindValue(string value)
{
return FindValue<PolicyScopeType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator PolicyScopeType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type PolicySourceType.
/// </summary>
public class PolicySourceType : ConstantClass
{
/// <summary>
/// Constant AwsManaged for PolicySourceType
/// </summary>
public static readonly PolicySourceType AwsManaged = new PolicySourceType("aws-managed");
/// <summary>
/// Constant Group for PolicySourceType
/// </summary>
public static readonly PolicySourceType Group = new PolicySourceType("group");
/// <summary>
/// Constant None for PolicySourceType
/// </summary>
public static readonly PolicySourceType None = new PolicySourceType("none");
/// <summary>
/// Constant Role for PolicySourceType
/// </summary>
public static readonly PolicySourceType Role = new PolicySourceType("role");
/// <summary>
/// Constant User for PolicySourceType
/// </summary>
public static readonly PolicySourceType User = new PolicySourceType("user");
/// <summary>
/// Constant UserManaged for PolicySourceType
/// </summary>
public static readonly PolicySourceType UserManaged = new PolicySourceType("user-managed");
/// <summary>
/// Default Constructor
/// </summary>
public PolicySourceType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static PolicySourceType FindValue(string value)
{
return FindValue<PolicySourceType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator PolicySourceType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ReportFormatType.
/// </summary>
public class ReportFormatType : ConstantClass
{
/// <summary>
/// Constant TextCsv for ReportFormatType
/// </summary>
public static readonly ReportFormatType TextCsv = new ReportFormatType("text/csv");
/// <summary>
/// Default Constructor
/// </summary>
public ReportFormatType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ReportFormatType FindValue(string value)
{
return FindValue<ReportFormatType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ReportFormatType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ReportStateType.
/// </summary>
public class ReportStateType : ConstantClass
{
/// <summary>
/// Constant COMPLETE for ReportStateType
/// </summary>
public static readonly ReportStateType COMPLETE = new ReportStateType("COMPLETE");
/// <summary>
/// Constant INPROGRESS for ReportStateType
/// </summary>
public static readonly ReportStateType INPROGRESS = new ReportStateType("INPROGRESS");
/// <summary>
/// Constant STARTED for ReportStateType
/// </summary>
public static readonly ReportStateType STARTED = new ReportStateType("STARTED");
/// <summary>
/// Default Constructor
/// </summary>
public ReportStateType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ReportStateType FindValue(string value)
{
return FindValue<ReportStateType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ReportStateType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type StatusType.
/// </summary>
public class StatusType : ConstantClass
{
/// <summary>
/// Constant Active for StatusType
/// </summary>
public static readonly StatusType Active = new StatusType("Active");
/// <summary>
/// Constant Inactive for StatusType
/// </summary>
public static readonly StatusType Inactive = new StatusType("Inactive");
/// <summary>
/// Default Constructor
/// </summary>
public StatusType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static StatusType FindValue(string value)
{
return FindValue<StatusType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator StatusType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SummaryKeyType.
/// </summary>
public class SummaryKeyType : ConstantClass
{
/// <summary>
/// Constant AccessKeysPerUserQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType AccessKeysPerUserQuota = new SummaryKeyType("AccessKeysPerUserQuota");
/// <summary>
/// Constant AccountAccessKeysPresent for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType AccountAccessKeysPresent = new SummaryKeyType("AccountAccessKeysPresent");
/// <summary>
/// Constant AccountMFAEnabled for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType AccountMFAEnabled = new SummaryKeyType("AccountMFAEnabled");
/// <summary>
/// Constant AccountSigningCertificatesPresent for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType AccountSigningCertificatesPresent = new SummaryKeyType("AccountSigningCertificatesPresent");
/// <summary>
/// Constant AttachedPoliciesPerGroupQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType AttachedPoliciesPerGroupQuota = new SummaryKeyType("AttachedPoliciesPerGroupQuota");
/// <summary>
/// Constant AttachedPoliciesPerRoleQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType AttachedPoliciesPerRoleQuota = new SummaryKeyType("AttachedPoliciesPerRoleQuota");
/// <summary>
/// Constant AttachedPoliciesPerUserQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType AttachedPoliciesPerUserQuota = new SummaryKeyType("AttachedPoliciesPerUserQuota");
/// <summary>
/// Constant GroupPolicySizeQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType GroupPolicySizeQuota = new SummaryKeyType("GroupPolicySizeQuota");
/// <summary>
/// Constant Groups for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType Groups = new SummaryKeyType("Groups");
/// <summary>
/// Constant GroupsPerUserQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType GroupsPerUserQuota = new SummaryKeyType("GroupsPerUserQuota");
/// <summary>
/// Constant GroupsQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType GroupsQuota = new SummaryKeyType("GroupsQuota");
/// <summary>
/// Constant MFADevices for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType MFADevices = new SummaryKeyType("MFADevices");
/// <summary>
/// Constant MFADevicesInUse for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType MFADevicesInUse = new SummaryKeyType("MFADevicesInUse");
/// <summary>
/// Constant Policies for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType Policies = new SummaryKeyType("Policies");
/// <summary>
/// Constant PoliciesQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType PoliciesQuota = new SummaryKeyType("PoliciesQuota");
/// <summary>
/// Constant PolicySizeQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType PolicySizeQuota = new SummaryKeyType("PolicySizeQuota");
/// <summary>
/// Constant PolicyVersionsInUse for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType PolicyVersionsInUse = new SummaryKeyType("PolicyVersionsInUse");
/// <summary>
/// Constant PolicyVersionsInUseQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType PolicyVersionsInUseQuota = new SummaryKeyType("PolicyVersionsInUseQuota");
/// <summary>
/// Constant ServerCertificates for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType ServerCertificates = new SummaryKeyType("ServerCertificates");
/// <summary>
/// Constant ServerCertificatesQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType ServerCertificatesQuota = new SummaryKeyType("ServerCertificatesQuota");
/// <summary>
/// Constant SigningCertificatesPerUserQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType SigningCertificatesPerUserQuota = new SummaryKeyType("SigningCertificatesPerUserQuota");
/// <summary>
/// Constant UserPolicySizeQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType UserPolicySizeQuota = new SummaryKeyType("UserPolicySizeQuota");
/// <summary>
/// Constant Users for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType Users = new SummaryKeyType("Users");
/// <summary>
/// Constant UsersQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType UsersQuota = new SummaryKeyType("UsersQuota");
/// <summary>
/// Constant VersionsPerPolicyQuota for SummaryKeyType
/// </summary>
public static readonly SummaryKeyType VersionsPerPolicyQuota = new SummaryKeyType("VersionsPerPolicyQuota");
/// <summary>
/// Default Constructor
/// </summary>
public SummaryKeyType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SummaryKeyType FindValue(string value)
{
return FindValue<SummaryKeyType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SummaryKeyType(string value)
{
return FindValue(value);
}
}
}
| |
// 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.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
namespace System.Management
{
/// <summary>
/// <para>Represents the method that will handle the <see cref='E:System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
/// </summary>
public delegate void EventArrivedEventHandler(object sender, EventArrivedEventArgs e);
/// <summary>
/// <para>Represents the method that will handle the <see cref='E:System.Management.ManagementEventWatcher.Stopped'/> event.</para>
/// </summary>
public delegate void StoppedEventHandler (object sender, StoppedEventArgs e);
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Subscribes to temporary event notifications
/// based on a specified event query.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example demonstrates how to subscribe to an event using the ManagementEventWatcher object.
/// class Sample_ManagementEventWatcher
/// {
/// public static int Main(string[] args) {
///
/// //For the example, we'll put a class into the repository, and watch
/// //for class deletion events when the class is deleted.
/// ManagementClass newClass = new ManagementClass();
/// newClass["__CLASS"] = "TestDeletionClass";
/// newClass.Put();
///
/// //Set up an event watcher and a handler for the event
/// ManagementEventWatcher watcher = new ManagementEventWatcher(
/// new WqlEventQuery("__ClassDeletionEvent"));
/// MyHandler handler = new MyHandler();
/// watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
///
/// //Start watching for events
/// watcher.Start();
///
/// // For the purpose of this sample, we delete the class to trigger the event
/// // and wait for two seconds before terminating the consumer
/// newClass.Delete();
///
/// System.Threading.Thread.Sleep(2000);
///
/// //Stop watching
/// watcher.Stop();
///
/// return 0;
/// }
///
/// public class MyHandler {
/// public void Arrived(object sender, EventArrivedEventArgs e) {
/// Console.WriteLine("Class Deleted = " +
/// ((ManagementBaseObject)e.NewEvent["TargetClass"])["__CLASS"]);
/// }
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This example demonstrates how to subscribe an event using the ManagementEventWatcher object.
/// Class Sample_ManagementEventWatcher
/// Public Shared Sub Main()
///
/// ' For the example, we'll put a class into the repository, and watch
/// ' for class deletion events when the class is deleted.
/// Dim newClass As New ManagementClass()
/// newClass("__CLASS") = "TestDeletionClass"
/// newClass.Put()
///
/// ' Set up an event watcher and a handler for the event
/// Dim watcher As _
/// New ManagementEventWatcher(New WqlEventQuery("__ClassDeletionEvent"))
/// Dim handler As New MyHandler()
/// AddHandler watcher.EventArrived, AddressOf handler.Arrived
///
/// ' Start watching for events
/// watcher.Start()
///
/// ' For the purpose of this sample, we delete the class to trigger the event
/// ' and wait for two seconds before terminating the consumer
/// newClass.Delete()
///
/// System.Threading.Thread.Sleep(2000)
///
/// ' Stop watching
/// watcher.Stop()
///
/// End Sub
///
/// Public Class MyHandler
/// Public Sub Arrived(sender As Object, e As EventArrivedEventArgs)
/// Console.WriteLine("Class Deleted = " & _
/// CType(e.NewEvent("TargetClass"), ManagementBaseObject)("__CLASS"))
/// End Sub
/// End Class
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
[ToolboxItem(false)]
public class ManagementEventWatcher : Component
{
//fields
private ManagementScope scope;
private EventQuery query;
private EventWatcherOptions options;
private IEnumWbemClassObject enumWbem;
private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in cache
private uint cachedCount; //says how many objects are in the cache (when using BlockSize option)
private uint cacheIndex; //used to walk the cache
private SinkForEventQuery sink; // the sink implementation for event queries
private WmiDelegateInvoker delegateInvoker;
//Called when IdentifierChanged() event fires
private void HandleIdentifierChange(object sender,
IdentifierChangedEventArgs e)
{
// Invalidate any sync or async call in progress
Stop();
}
//default constructor
/// <overload>
/// Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class.
/// </overload>
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class. For further
/// initialization, set the properties on the object. This is the default constructor.</para>
/// </summary>
public ManagementEventWatcher() : this((ManagementScope)null, null, null) {}
//parameterized constructors
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query.</para>
/// </summary>
/// <param name='query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
/// <remarks>
/// <para>The namespace in which the watcher will be listening for
/// events is the default namespace that is currently set.</para>
/// </remarks>
public ManagementEventWatcher (
EventQuery query) : this(null, query, null) {}
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query in the
/// form of a string.</para>
/// </summary>
/// <param name='query'> A WMI event query, which defines the events for which the watcher will listen.</param>
/// <remarks>
/// <para>The namespace in which the watcher will be listening for
/// events is the default namespace that is currently set.</para>
/// </remarks>
public ManagementEventWatcher (
string query) : this(null, new EventQuery(query), null) {}
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/>
/// class that listens for events conforming to the given WMI event query.</para>
/// </summary>
/// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
public ManagementEventWatcher(
ManagementScope scope,
EventQuery query) : this(scope, query, null) {}
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/>
/// class that listens for events conforming to the given WMI event query. For this
/// variant, the query and the scope are specified as strings.</para>
/// </summary>
/// <param name='scope'> The management scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'> The query that defines the events for which the watcher will listen.</param>
public ManagementEventWatcher(
string scope,
string query) : this(new ManagementScope(scope), new EventQuery(query), null) {}
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class that listens for
/// events conforming to the given WMI event query, according to the specified options. For
/// this variant, the query and the scope are specified as strings. The options
/// object can specify options such as a timeout and context information.</para>
/// </summary>
/// <param name='scope'>The management scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>The query that defines the events for which the watcher will listen.</param>
/// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param>
public ManagementEventWatcher(
string scope,
string query,
EventWatcherOptions options) : this(new ManagementScope(scope), new EventQuery(query), options) {}
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class
/// that listens for events conforming to the given WMI event query, according to the specified
/// options. For this variant, the query and the scope are specified objects. The
/// options object can specify options such as timeout and context information.</para>
/// </summary>
/// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
/// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param>
public ManagementEventWatcher(
ManagementScope scope,
EventQuery query,
EventWatcherOptions options)
{
if (null != scope)
this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(HandleIdentifierChange));
else
this.scope = ManagementScope._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange));
if (null != query)
this.query = (EventQuery)query.Clone();
else
this.query = new EventQuery();
this.query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != options)
this.options = (EventWatcherOptions)options.Clone();
else
this.options = new EventWatcherOptions();
this.options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
enumWbem = null;
cachedCount = 0;
cacheIndex = 0;
sink = null;
delegateInvoker = new WmiDelegateInvoker (this);
}
/// <summary>
/// <para>Ensures that outstanding calls are cleared. This is the destructor for the object.</para>
/// </summary>
~ManagementEventWatcher ()
{
// Ensure any outstanding calls are cleared
Stop ();
if (null != scope)
scope.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange);
if (null != options)
options.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange);
if (null != query)
query.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange);
}
//
// Events
//
/// <summary>
/// <para> Occurs when a new event arrives.</para>
/// </summary>
public event EventArrivedEventHandler EventArrived;
/// <summary>
/// <para> Occurs when a subscription is canceled.</para>
/// </summary>
public event StoppedEventHandler Stopped;
//
//Public Properties
//
/// <summary>
/// <para>Gets or sets the scope in which to watch for events (namespace or scope).</para>
/// </summary>
/// <value>
/// <para> The scope in which to watch for events (namespace or scope).</para>
/// </value>
public ManagementScope Scope
{
get
{
return scope;
}
set
{
if (null != value)
{
ManagementScope oldScope = scope;
scope = (ManagementScope)value.Clone ();
// Unregister ourselves from the previous scope object
if (null != oldScope)
oldScope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
//register for change events in this object
scope.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the scope property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Gets or sets the criteria to apply to events.</para>
/// </summary>
/// <value>
/// <para> The criteria to apply to the events, which is equal to the event query.</para>
/// </value>
public EventQuery Query
{
get
{
return query;
}
set
{
if (null != value)
{
ManagementQuery oldQuery = query;
query = (EventQuery)value.Clone ();
// Unregister ourselves from the previous query object
if (null != oldQuery)
oldQuery.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
//register for change events in this object
query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the query property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Gets or sets the options used to watch for events.</para>
/// </summary>
/// <value>
/// <para>The options used to watch for events.</para>
/// </value>
public EventWatcherOptions Options
{
get
{
return options;
}
set
{
if (null != value)
{
EventWatcherOptions oldOptions = options;
options = (EventWatcherOptions)value.Clone ();
// Unregister ourselves from the previous scope object
if (null != oldOptions)
oldOptions.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
//register for change events in this object
options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the options property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Waits for the next event that matches the specified query to arrive, and
/// then returns it.</para>
/// </summary>
/// <returns>
/// <para>A <see cref='System.Management.ManagementBaseObject'/> representing the
/// newly arrived event.</para>
/// </returns>
/// <remarks>
/// <para>If the event watcher object contains options with
/// a specified timeout, the API will wait for the next event only for the specified
/// amount of time; otherwise, the API will be blocked until the next event occurs.</para>
/// </remarks>
public ManagementBaseObject WaitForNextEvent()
{
ManagementBaseObject obj = null;
Initialize ();
#pragma warning disable CA2002
lock(this)
#pragma warning restore CA2002
{
SecurityHandler securityHandler = Scope.GetSecurityHandler();
int status = (int)ManagementStatus.NoError;
try
{
if (null == enumWbem) //don't have an enumerator yet - get it
{
//Execute the query
status = scope.GetSecuredIWbemServicesHandler( Scope.GetIWbemServices() ).ExecNotificationQuery_(
query.QueryLanguage,
query.QueryString,
options.Flags,
options.GetContext (),
ref enumWbem);
}
if (status >= 0)
{
if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects
{
//Because Interop doesn't support custom marshalling for arrays, we have to use
//the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded"
//counterparts afterwards.
IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[options.BlockSize];
int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout)
? (int) tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE :
(int) options.Timeout.TotalMilliseconds;
status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)options.BlockSize, tempArray, ref cachedCount);
cacheIndex = 0;
if (status >= 0)
{
//Convert results and put them in cache. Note that we may have timed out
//in which case we might not have all the objects. If no object can be returned
//we throw a timeout exception.
if (cachedCount == 0)
ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout);
for (int i = 0; i < cachedCount; i++)
cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(tempArray[i]));
}
}
if (status >= 0)
{
obj = new ManagementBaseObject(cachedObjects[cacheIndex]);
cacheIndex++;
}
}
}
finally
{
securityHandler.Reset();
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return obj;
}
//********************************************
//Start
//********************************************
/// <summary>
/// <para>Subscribes to events with the given query and delivers
/// them, asynchronously, through the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
/// </summary>
public void Start()
{
Initialize ();
// Cancel any current event query
Stop ();
// Submit a new query
SecurityHandler securityHandler = Scope.GetSecurityHandler();
IWbemServices wbemServices = scope.GetIWbemServices();
try
{
sink = new SinkForEventQuery(this, options.Context, wbemServices);
if (sink.Status < 0)
{
Marshal.ThrowExceptionForHR(sink.Status, WmiNetUtilsHelper.GetErrorInfo_f());
}
// For async event queries we should ensure 0 flags as this is
// the only legal value
int status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecNotificationQueryAsync_(
query.QueryLanguage,
query.QueryString,
0,
options.GetContext(),
sink.Stub);
if (status < 0)
{
if (sink != null)
{
sink.ReleaseStub();
sink = null;
}
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
finally
{
securityHandler.Reset();
}
}
//********************************************
//Stop
//********************************************
/// <summary>
/// <para>Cancels the subscription whether it is synchronous or asynchronous.</para>
/// </summary>
public void Stop()
{
//For semi-synchronous, release the WMI enumerator to cancel the subscription
if (null != enumWbem)
{
Marshal.ReleaseComObject(enumWbem);
enumWbem = null;
FireStopped (new StoppedEventArgs (options.Context, (int)ManagementStatus.OperationCanceled));
}
// In async mode cancel the call to the sink - this will
// unwind the operation and cause a Stopped message
if (null != sink)
{
sink.Cancel ();
sink = null;
}
}
private void Initialize ()
{
//If the query is not set yet we can't do it
if (null == query)
throw new InvalidOperationException();
if (null == options)
Options = new EventWatcherOptions ();
//If we're not connected yet, this is the time to do it...
#pragma warning disable CA2002
lock (this)
#pragma warning restore CA2002
{
if (null == scope)
Scope = new ManagementScope ();
if (null == cachedObjects)
cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
}
lock (scope)
{
scope.Initialize ();
}
}
internal void FireStopped (StoppedEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates (Stopped, args);
}
catch
{
}
}
internal void FireEventArrived (EventArrivedEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates (EventArrived, args);
}
catch
{
}
}
}
internal class SinkForEventQuery : IWmiEventSource
{
private ManagementEventWatcher eventWatcher;
private object context;
private IWbemServices services;
private IWbemObjectSink stub; // The secured IWbemObjectSink
private int status;
private bool isLocal;
public int Status {get {return status;} set {status=value;}}
public SinkForEventQuery (ManagementEventWatcher eventWatcher,
object context,
IWbemServices services)
{
this.services = services;
this.context = context;
this.eventWatcher = eventWatcher;
this.status = 0;
this.isLocal = false;
// determine if the server is local, and if so don't create a real stub using unsecap
if((0==string.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
(0==string.Compare(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
{
this.isLocal = true;
}
if(MTAHelper.IsNoContextMTA())
HackToCreateStubInMTA(this);
else
{
//
// Ensure we are able to trap exceptions from worker thread.
//
ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethodWithParam ( HackToCreateStubInMTA ) ) ;
disp.Parameter = this ;
disp.Start ( ) ;
}
}
void HackToCreateStubInMTA(object param)
{
SinkForEventQuery obj = (SinkForEventQuery) param ;
object dmuxStub = null;
obj.Status = WmiNetUtilsHelper.GetDemultiplexedStub_f (obj, obj.isLocal, out dmuxStub);
obj.stub = (IWbemObjectSink) dmuxStub;
}
internal IWbemObjectSink Stub
{
get { return stub; }
}
public void Indicate(IntPtr pWbemClassObject)
{
Marshal.AddRef(pWbemClassObject);
IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pWbemClassObject);
try
{
EventArrivedEventArgs args = new EventArrivedEventArgs(context, new ManagementBaseObject(obj));
eventWatcher.FireEventArrived(args);
}
catch
{
}
}
public void SetStatus (
int flags,
int hResult,
string message,
IntPtr pErrObj)
{
try
{
// Fire Stopped event
eventWatcher.FireStopped(new StoppedEventArgs(context, hResult));
//This handles cases in which WMI calls SetStatus to indicate a problem, for example
//a queue overflow due to slow client processing.
//Currently we just cancel the subscription in this case.
if (hResult != (int)tag_WBEMSTATUS.WBEM_E_CALL_CANCELLED
&& hResult != (int)tag_WBEMSTATUS.WBEM_S_OPERATION_CANCELLED)
ThreadPool.QueueUserWorkItem(new WaitCallback(Cancel2));
}
catch
{
}
}
// On Win2k, we get a deadlock if we do a Cancel within a SetStatus
// Instead of calling it from SetStatus, we use ThreadPool.QueueUserWorkItem
void Cancel2(object o)
{
//
// Try catch the call to cancel. In this case the cancel is being done without the client
// knowing about it so catching all exceptions is not a bad thing to do. If a client calls
// Stop (which calls Cancel), they will still recieve any exceptions that may have occured.
//
try
{
Cancel();
}
catch
{
}
}
internal void Cancel ()
{
if (null != stub)
{
#pragma warning disable CA2002
lock(this)
#pragma warning restore CA2002
{
if (null != stub)
{
int status = services.CancelAsyncCall_(stub);
// Release prior to throwing an exception.
ReleaseStub();
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}
}
}
internal void ReleaseStub ()
{
if (null != stub)
{
#pragma warning disable CA2002
lock(this)
#pragma warning restore CA2002
{
/*
* We force a release of the stub here so as to allow
* unsecapp.exe to die as soon as possible.
* however if it is local, unsecap won't be started
*/
if (null != stub)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(stub);
stub = null;
}
catch
{
}
}
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcdcv = Google.Cloud.Dialogflow.Cx.V3;
using sys = System;
namespace Google.Cloud.Dialogflow.Cx.V3
{
/// <summary>Resource name for the <c>SessionEntityType</c> resource.</summary>
public sealed partial class SessionEntityTypeName : gax::IResourceName, sys::IEquatable<SessionEntityTypeName>
{
/// <summary>The possible contents of <see cref="SessionEntityTypeName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>
/// .
/// </summary>
ProjectLocationAgentSessionEntityType = 1,
/// <summary>
/// A resource name with pattern
/// <c>
/// projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}</c>
/// .
/// </summary>
ProjectLocationAgentEnvironmentSessionEntityType = 2,
}
private static gax::PathTemplate s_projectLocationAgentSessionEntityType = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}");
private static gax::PathTemplate s_projectLocationAgentEnvironmentSessionEntityType = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}");
/// <summary>Creates a <see cref="SessionEntityTypeName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SessionEntityTypeName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SessionEntityTypeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SessionEntityTypeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SessionEntityTypeName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionEntityTypeName"/> constructed from the provided ids.</returns>
public static SessionEntityTypeName FromProjectLocationAgentSessionEntityType(string projectId, string locationId, string agentId, string sessionId, string entityTypeId) =>
new SessionEntityTypeName(ResourceNameType.ProjectLocationAgentSessionEntityType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), entityTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId)));
/// <summary>
/// Creates a <see cref="SessionEntityTypeName"/> with the pattern
/// <c>
/// projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionEntityTypeName"/> constructed from the provided ids.</returns>
public static SessionEntityTypeName FromProjectLocationAgentEnvironmentSessionEntityType(string projectId, string locationId, string agentId, string environmentId, string sessionId, string entityTypeId) =>
new SessionEntityTypeName(ResourceNameType.ProjectLocationAgentEnvironmentSessionEntityType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), entityTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionEntityTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionEntityTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string agentId, string sessionId, string entityTypeId) =>
FormatProjectLocationAgentSessionEntityType(projectId, locationId, agentId, sessionId, entityTypeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionEntityTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionEntityTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>.
/// </returns>
public static string FormatProjectLocationAgentSessionEntityType(string projectId, string locationId, string agentId, string sessionId, string entityTypeId) =>
s_projectLocationAgentSessionEntityType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionEntityTypeName"/> with pattern
/// <c>
/// projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionEntityTypeName"/> with pattern
/// <c>
/// projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}</c>
/// .
/// </returns>
public static string FormatProjectLocationAgentEnvironmentSessionEntityType(string projectId, string locationId, string agentId, string environmentId, string sessionId, string entityTypeId) =>
s_projectLocationAgentEnvironmentSessionEntityType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="SessionEntityTypeName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>
/// projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="sessionEntityTypeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SessionEntityTypeName"/> if successful.</returns>
public static SessionEntityTypeName Parse(string sessionEntityTypeName) => Parse(sessionEntityTypeName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SessionEntityTypeName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>
/// projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sessionEntityTypeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SessionEntityTypeName"/> if successful.</returns>
public static SessionEntityTypeName Parse(string sessionEntityTypeName, bool allowUnparsed) =>
TryParse(sessionEntityTypeName, allowUnparsed, out SessionEntityTypeName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SessionEntityTypeName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>
/// projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="sessionEntityTypeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SessionEntityTypeName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sessionEntityTypeName, out SessionEntityTypeName result) =>
TryParse(sessionEntityTypeName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SessionEntityTypeName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>
/// projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}/entityTypes/{entity_type}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sessionEntityTypeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SessionEntityTypeName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sessionEntityTypeName, bool allowUnparsed, out SessionEntityTypeName result)
{
gax::GaxPreconditions.CheckNotNull(sessionEntityTypeName, nameof(sessionEntityTypeName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationAgentSessionEntityType.TryParseName(sessionEntityTypeName, out resourceName))
{
result = FromProjectLocationAgentSessionEntityType(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
return true;
}
if (s_projectLocationAgentEnvironmentSessionEntityType.TryParseName(sessionEntityTypeName, out resourceName))
{
result = FromProjectLocationAgentEnvironmentSessionEntityType(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4], resourceName[5]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(sessionEntityTypeName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SessionEntityTypeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string entityTypeId = null, string environmentId = null, string locationId = null, string projectId = null, string sessionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AgentId = agentId;
EntityTypeId = entityTypeId;
EnvironmentId = environmentId;
LocationId = locationId;
ProjectId = projectId;
SessionId = sessionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SessionEntityTypeName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param>
public SessionEntityTypeName(string projectId, string locationId, string agentId, string sessionId, string entityTypeId) : this(ResourceNameType.ProjectLocationAgentSessionEntityType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), entityTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Agent</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string AgentId { get; }
/// <summary>
/// The <c>EntityType</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string EntityTypeId { get; }
/// <summary>
/// The <c>Environment</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string EnvironmentId { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Session</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string SessionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationAgentSessionEntityType: return s_projectLocationAgentSessionEntityType.Expand(ProjectId, LocationId, AgentId, SessionId, EntityTypeId);
case ResourceNameType.ProjectLocationAgentEnvironmentSessionEntityType: return s_projectLocationAgentEnvironmentSessionEntityType.Expand(ProjectId, LocationId, AgentId, EnvironmentId, SessionId, EntityTypeId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SessionEntityTypeName);
/// <inheritdoc/>
public bool Equals(SessionEntityTypeName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SessionEntityTypeName a, SessionEntityTypeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SessionEntityTypeName a, SessionEntityTypeName b) => !(a == b);
}
public partial class SessionEntityType
{
/// <summary>
/// <see cref="gcdcv::SessionEntityTypeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::SessionEntityTypeName SessionEntityTypeName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::SessionEntityTypeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListSessionEntityTypesRequest
{
/// <summary>
/// <see cref="SessionName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public SessionName ParentAsSessionName
{
get => string.IsNullOrEmpty(Parent) ? null : SessionName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetSessionEntityTypeRequest
{
/// <summary>
/// <see cref="gcdcv::SessionEntityTypeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::SessionEntityTypeName SessionEntityTypeName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::SessionEntityTypeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateSessionEntityTypeRequest
{
/// <summary>
/// <see cref="SessionName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public SessionName ParentAsSessionName
{
get => string.IsNullOrEmpty(Parent) ? null : SessionName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteSessionEntityTypeRequest
{
/// <summary>
/// <see cref="gcdcv::SessionEntityTypeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::SessionEntityTypeName SessionEntityTypeName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::SessionEntityTypeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: 591573 $
* $Date: 2007-11-03 11:17:59 +0100 (sam., 03 nov. 2007) $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2005 - Gilles Bayon
*
*
* 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.
*
********************************************************************************/
#endregion
using System;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Text;
using IBatisNet.Common.Logging;
using IBatisNet.Common.Utilities.Objects;
using IBatisNet.DataMapper.Configuration.ParameterMapping;
using IBatisNet.DataMapper.Configuration.Statements;
using IBatisNet.DataMapper.Exceptions;
using IBatisNet.DataMapper.Scope;
namespace IBatisNet.DataMapper.Commands
{
/// <summary>
/// DefaultPreparedCommand.
/// </summary>
internal class DefaultPreparedCommand : IPreparedCommand
{
private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region IPreparedCommand Members
/// <summary>
/// Create an IDbCommand for the SqlMapSession and the current SQL Statement
/// and fill IDbCommand IDataParameter's with the parameterObject.
/// </summary>
/// <param name="request"></param>
/// <param name="session">The SqlMapSession</param>
/// <param name="statement">The IStatement</param>
/// <param name="parameterObject">
/// The parameter object that will fill the sql parameter
/// </param>
/// <returns>An IDbCommand with all the IDataParameter filled.</returns>
public void Create(RequestScope request, ISqlMapSession session, IStatement statement, object parameterObject)
{
// the IDbConnection & the IDbTransaction are assign in the CreateCommand
request.IDbCommand = new DbCommandDecorator(session.CreateCommand(statement.CommandType), request);
request.IDbCommand.CommandText = request.PreparedStatement.PreparedSql;
if (_logger.IsDebugEnabled)
{
_logger.Debug("Statement Id: [" + statement.Id + "] PreparedStatement : [" + request.IDbCommand.CommandText + "]");
}
ApplyParameterMap(session, request.IDbCommand, request, statement, parameterObject);
}
/// <summary>
/// Applies the parameter map.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="command">The command.</param>
/// <param name="request">The request.</param>
/// <param name="statement">The statement.</param>
/// <param name="parameterObject">The parameter object.</param>
protected virtual void ApplyParameterMap
(ISqlMapSession session, IDbCommand command,
RequestScope request, IStatement statement, object parameterObject)
{
StringCollection properties = request.PreparedStatement.DbParametersName;
IDbDataParameter[] parameters = request.PreparedStatement.DbParameters;
StringBuilder paramLogList = new StringBuilder(); // Log info
StringBuilder typeLogList = new StringBuilder(); // Log info
int count = properties.Count;
for (int i = 0; i < count; ++i)
{
IDbDataParameter sqlParameter = parameters[i];
IDbDataParameter parameterCopy = command.CreateParameter();
ParameterProperty property = request.ParameterMap.GetProperty(i);
#region Logging
if (_logger.IsDebugEnabled)
{
paramLogList.Append(sqlParameter.ParameterName);
paramLogList.Append("=[");
typeLogList.Append(sqlParameter.ParameterName);
typeLogList.Append("=[");
}
#endregion
if (command.CommandType == CommandType.StoredProcedure)
{
#region store procedure command
// A store procedure must always use a ParameterMap
// to indicate the mapping order of the properties to the columns
if (request.ParameterMap == null) // Inline Parameters
{
throw new DataMapperException("A procedure statement tag must alway have a parameterMap attribute, which is not the case for the procedure '" + statement.Id + "'.");
}
else // Parameters via ParameterMap
{
if (property.DirectionAttribute.Length == 0)
{
property.Direction = sqlParameter.Direction;
}
sqlParameter.Direction = property.Direction;
}
#endregion
}
#region Logging
if (_logger.IsDebugEnabled)
{
paramLogList.Append(property.PropertyName);
paramLogList.Append(",");
}
#endregion
request.ParameterMap.SetParameter(property, parameterCopy, parameterObject);
parameterCopy.Direction = sqlParameter.Direction;
// With a ParameterMap, we could specify the ParameterDbTypeProperty
if (request.ParameterMap != null)
{
if (property.DbType != null && property.DbType.Length > 0)
{
string dbTypePropertyName = session.DataSource.DbProvider.ParameterDbTypeProperty;
object propertyValue = ObjectProbe.GetMemberValue(sqlParameter, dbTypePropertyName, request.DataExchangeFactory.AccessorFactory);
ObjectProbe.SetMemberValue(parameterCopy, dbTypePropertyName, propertyValue,
request.DataExchangeFactory.ObjectFactory, request.DataExchangeFactory.AccessorFactory);
}
else
{
//parameterCopy.DbType = sqlParameter.DbType;
}
}
else
{
//parameterCopy.DbType = sqlParameter.DbType;
}
#region Logging
if (_logger.IsDebugEnabled)
{
if (parameterCopy.Value == DBNull.Value)
{
paramLogList.Append("null");
paramLogList.Append("], ");
typeLogList.Append("System.DBNull, null");
typeLogList.Append("], ");
}
else
{
paramLogList.Append(parameterCopy.Value.ToString());
paramLogList.Append("], ");
// sqlParameter.DbType could be null (as with Npgsql)
// if PreparedStatementFactory did not find a dbType for the parameter in:
// line 225: "if (property.DbType.Length >0)"
// Use parameterCopy.DbType
//typeLogList.Append( sqlParameter.DbType.ToString() );
typeLogList.Append(parameterCopy.DbType.ToString());
typeLogList.Append(", ");
typeLogList.Append(parameterCopy.Value.GetType().ToString());
typeLogList.Append("], ");
}
}
#endregion
// JIRA-49 Fixes (size, precision, and scale)
if (session.DataSource.DbProvider.SetDbParameterSize)
{
if (sqlParameter.Size > 0)
{
parameterCopy.Size = sqlParameter.Size;
}
}
if (session.DataSource.DbProvider.SetDbParameterPrecision)
{
parameterCopy.Precision = sqlParameter.Precision;
}
if (session.DataSource.DbProvider.SetDbParameterScale)
{
parameterCopy.Scale = sqlParameter.Scale;
}
parameterCopy.ParameterName = sqlParameter.ParameterName;
command.Parameters.Add(parameterCopy);
}
#region Logging
if (_logger.IsDebugEnabled && properties.Count > 0)
{
_logger.Debug("Statement Id: [" + statement.Id + "] Parameters: [" + paramLogList.ToString(0, paramLogList.Length - 2) + "]");
_logger.Debug("Statement Id: [" + statement.Id + "] Types: [" + typeLogList.ToString(0, typeLogList.Length - 2) + "]");
}
#endregion
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Validation
{
// Integration tests for the default configuration of ModelMetadata and Validation providers
public class DefaultModelValidatorProviderTest
{
[Fact]
public void CreateValidators_ForIValidatableObject()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var validatorProvider = TestModelValidatorProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForType(typeof(ValidatableObject));
var context = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
validatorProvider.CreateValidators(context);
// Assert
var validatorItems = context.Results;
var validatorItem = Assert.Single(validatorItems);
Assert.IsType<ValidatableObjectAdapter>(validatorItem.Validator);
}
[Fact]
public void CreateValidators_ModelValidatorAttributeOnClass()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var validatorProvider = TestModelValidatorProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForType(typeof(ModelValidatorAttributeOnClass));
var context = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
validatorProvider.CreateValidators(context);
// Assert
var validatorItems = context.Results;
var validator = Assert.IsType<CustomModelValidatorAttribute>(Assert.Single(validatorItems).Validator);
Assert.Equal("Class", validator.Tag);
}
[Fact]
public void CreateValidators_ModelValidatorAttributeOnProperty()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var validatorProvider = TestModelValidatorProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(
typeof(ModelValidatorAttributeOnProperty),
nameof(ModelValidatorAttributeOnProperty.Property));
var context = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
validatorProvider.CreateValidators(context);
// Assert
var validatorItems = context.Results;
var validator = Assert.IsType<CustomModelValidatorAttribute>(Assert.Single(validatorItems).Validator);
Assert.Equal("Property", validator.Tag);
}
[Fact]
public void CreateValidators_ModelValidatorAttributeOnPropertyAndClass()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var validatorProvider = TestModelValidatorProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(
typeof(ModelValidatorAttributeOnPropertyAndClass),
nameof(ModelValidatorAttributeOnPropertyAndClass.Property));
var context = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
validatorProvider.CreateValidators(context);
// Assert
var validatorItems = context.Results;
Assert.Equal(2, validatorItems.Count);
Assert.Single(validatorItems, v => Assert.IsType<CustomModelValidatorAttribute>(v.Validator).Tag == "Class");
Assert.Single(validatorItems, v => Assert.IsType<CustomModelValidatorAttribute>(v.Validator).Tag == "Property");
}
[Fact]
public void CreateValidators_FromModelMetadataType_SingleValidator()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var validatorProvider = TestModelValidatorProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(
typeof(ProductViewModel),
nameof(ProductViewModel.Id));
var context = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
validatorProvider.CreateValidators(context);
// Assert
var validatorItems = context.Results;
var adapter = Assert.IsType<DataAnnotationsModelValidator>(Assert.Single(validatorItems).Validator);
Assert.IsType<RangeAttribute>(adapter.Attribute);
}
[Fact]
public void CreateValidators_FromModelMetadataType_MergedValidators()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var validatorProvider = TestModelValidatorProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(
typeof(ProductViewModel),
nameof(ProductViewModel.Name));
var context = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
validatorProvider.CreateValidators(context);
// Assert
var validatorItems = context.Results;
Assert.Equal(2, validatorItems.Count);
Assert.Single(validatorItems, v => ((DataAnnotationsModelValidator)v.Validator).Attribute is RegularExpressionAttribute);
Assert.Single(validatorItems, v => ((DataAnnotationsModelValidator)v.Validator).Attribute is StringLengthAttribute);
}
[Fact]
public void HasValidators_ReturnsTrue_IfMetadataIsIModelValidator()
{
// Arrange
var validatorProvider = new DefaultModelValidatorProvider();
var attributes = new object[] { new RequiredAttribute(), new CustomModelValidatorAttribute(), new BindRequiredAttribute(), };
// Act
var result = validatorProvider.HasValidators(typeof(object), attributes);
// Assert
Assert.True(result);
}
[Fact]
public void HasValidators_ReturnsFalse_IfNoMetadataIsIModelValidator()
{
// Arrange
var validatorProvider = new DefaultModelValidatorProvider();
var attributes = new object[] { new RequiredAttribute(), new BindRequiredAttribute(), };
// Act
var result = validatorProvider.HasValidators(typeof(object), attributes);
// Assert
Assert.False(result);
}
private static IList<ValidatorItem> GetValidatorItems(ModelMetadata metadata)
{
return metadata.ValidatorMetadata.Select(v => new ValidatorItem(v)).ToList();
}
private class ValidatableObject : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return null;
}
}
[CustomModelValidator(Tag = "Class")]
private class ModelValidatorAttributeOnClass
{
}
private class ModelValidatorAttributeOnProperty
{
[CustomModelValidator(Tag = "Property")]
public string Property { get; set; }
}
private class ModelValidatorAttributeOnPropertyAndClass
{
[CustomModelValidator(Tag = "Property")]
public ModelValidatorAttributeOnClass Property { get; set; }
}
private class CustomModelValidatorAttribute : Attribute, IModelValidator
{
public string Tag { get; set; }
public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
{
throw new NotImplementedException();
}
}
private class RangeAttributeOnProperty
{
[Range(0, 10)]
public int Property { get; set; }
}
private class CustomValidationAttribute : ValidationAttribute
{
}
private class CustomValidationAttributeOnProperty
{
[CustomValidation]
public int Property { get; set; }
}
private class ProductEntity
{
[Range(0, 10)]
public int Id { get; set; }
[RegularExpression(".*")]
public string Name { get; set; }
}
[ModelMetadataType(typeof(ProductEntity))]
private class ProductViewModel
{
public int Id { get; set; }
[StringLength(4)]
public string Name { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using Microsoft.Win32;
using System.Data;
namespace ExportExtensionCommon
{
public partial class Capture : Form
{
public SIEEDefaultValues DefaultFieldValues { get; set; }
public string DefaultDocument { get; set; }
private Dictionary<string, Control> tb_dict = new Dictionary<string, Control>();
private SIEESettings settings;
private SIEEFieldlist schema;
private SIEEBatch batch = new SIEEBatch();
private string document;
private Dictionary<DataGridView, DataTable> gridToTableMap = new Dictionary<DataGridView, DataTable>();
public Capture(SIEESettings settings, SIEEFieldlist schema)
{
InitializeComponent();
this.settings = settings;
this.schema = schema;
addFields(schema);
}
public DialogResult MyShowDialog()
{
btn_data.Enabled = DefaultFieldValues.ExtensionExists(settings.GetType().Name);
document = DefaultDocument;
lbl_docName.Text = Path.GetFileName(document);
return ShowDialog();
}
public string GetDocument()
{
return document;
}
public SIEEBatch GetData() { return batch; }
private SIEEFieldlist GetFieldlistFromUI()
{
TextBox tb;
DataGridView dgv;
SIEEFieldlist fl = new SIEEFieldlist(schema);
SIEETableFieldRow tfr;
foreach (SIEEField f in fl)
{
Control c = tb_dict[f.Name];
if (c is TextBox)
{
tb = (TextBox)c;
f.Value = tb.Text;
continue;
}
// else c is DataGridView
dgv = (DataGridView)c;
SIEETableField tf = (SIEETableField)f;
DataTable table = gridToTableMap[dgv];
foreach (DataRow row in table.Rows)
{
tfr = new SIEETableFieldRow();
foreach (DataColumn col in table.Columns)
{
tfr[col.ColumnName] = row[col] is DBNull ? "" : (string)row[col];
}
tf.AddRow(tfr);
}
}
return fl;
}
private void addFields (SIEEFieldlist fl)
{
Label l;
TextBox tb;
DataGridView dgv;
DataTable table;
int ypos = 0;
const int labelwidth = 300;
int labelheight;
int entryheight;
int gridheight;
int cnt = 0;
tb_dict.Clear();
foreach (SIEEField f in fl)
{
l = new Label();
l.Location = new System.Drawing.Point(0, ypos);
l.Name = "label_" + f.Name;
labelheight = l.Size.Height;
l.Size = new System.Drawing.Size(labelwidth, labelheight);
l.TabIndex = cnt;
l.Text = f.Name;
this.panel.Controls.Add(l);
if (! (f is SIEETableField))
{
tb = new TextBox();
tb.Location = new System.Drawing.Point(labelwidth + 30, ypos);
tb.Name = f.Name;
entryheight = tb.Size.Height > labelheight ? tb.Size.Height : labelheight;
tb.Size = new System.Drawing.Size(panel.Size.Width - (labelwidth + 30), entryheight);
tb.TabIndex = cnt;
this.panel.Controls.Add(tb);
tb_dict.Add(f.Name, tb);
tb.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left;
ypos += entryheight;
}
else
{
SIEETableField tf = (SIEETableField)f;
dgv = new DataGridView();
dgv.Location = new System.Drawing.Point(labelwidth + 30, ypos);
dgv.Name = tf.Name;
gridheight = dgv.Size.Height;
dgv.Size = new System.Drawing.Size(panel.Size.Width - (labelwidth + 30), gridheight);
dgv.TabIndex = cnt;
dgv.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
table = new DataTable();
gridToTableMap[dgv] = table;
dgv.DataSource = table;
foreach (SIEEField col in tf.Columns) { table.Columns.Add(col.Name); }
this.panel.Controls.Add(dgv);
tb_dict.Add(f.Name, dgv);
dgv.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left;
//dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill);
ypos += 10 + gridheight;
}
cnt++;
}
}
private void btn_ok_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
private void btn_document_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Filter = "Document (*.pdf)|*.pdf";
ofd.Title = "Select document";
if (ofd.ShowDialog() == DialogResult.OK)
{
document = ofd.FileName;
lbl_docName.Text = Path.GetFileName(document);
}
}
private void btn_data_Click(object sender, EventArgs e)
{
string type = settings.GetType().Name;
DataRow row;
foreach (Control c in this.panel.Controls)
{
if (!DefaultFieldValues.Exists(type, c.Name)) continue;
if (c.GetType().Name == "TextBox")
{
((TextBox)c).Text = DefaultFieldValues.Get(type, c.Name);
continue;
}
// if c.GetType().Name = "DataGridView
DataTable table = gridToTableMap[(DataGridView)c];
table.Clear();
foreach (string line in DefaultFieldValues.Get(type, c.Name).Split('\n'))
{
int i = 0;
row = table.NewRow();
foreach (string v in line.Split(';')) { row[i++] = v.Trim(); }
table.Rows.Add(row);
}
}
}
private void btn_addDocument_Click(object sender, EventArgs e)
{
// rather complex loops to make document name unique within batch
string doc = Path.GetFileNameWithoutExtension(document);
bool done = false;
while (!done)
{
done = true; int cnt = 0;
foreach (SIEEDocument d in batch)
{
if (Path.GetFileNameWithoutExtension(d.InputFileName) == doc)
{
doc = doc + String.Format("_{0:D4}", cnt++);
done = false;
}
}
}
doc = Path.GetFileNameWithoutExtension(doc);
batch.Add(new SIEEDocument {
InputFileName = doc,
PDFFileName = document,
BatchId = "4711",
DocumentId = batch.Count.ToString(),
Fieldlist = GetFieldlistFromUI()
});
lbl_numberOfDocs.Text = batch.Count + " Documents loaded";
btn_ok.Enabled = true;
}
}
}
| |
namespace Incoding.MSpecContrib
{
#region << Using >>
using System;
using System.Collections.Generic;
using System.Linq;
using Incoding.Block.IoC;
using Incoding.CQRS;
using Incoding.Data;
using Incoding.Extensions;
using Machine.Specifications;
using Moq;
#endregion
public static class MockMessage
{
#region Factory constructors
public static void Execute(this IMessage message)
{
message.OnExecute(IoCFactory.Instance.TryResolve<IDispatcher>(), new Lazy<IUnitOfWork>(() => IoCFactory.Instance.TryResolve<IUnitOfWork>()));
}
#endregion
}
public abstract class MockMessage<TMessage, TResult> where TMessage : IMessage
{
#region Constructors
protected MockMessage(TMessage instanceMessage)
{
Original = instanceMessage;
Original.Setting = new MessageExecuteSetting();
repository = Pleasure.Mock<IRepository>();
var unitOfWork = Pleasure.MockStrictAsObject<IUnitOfWork>(mock => mock.Setup(x => x.GetRepository()).Returns(repository.Object));
IoCFactory.Instance.StubTryResolve(unitOfWork);
dispatcher = Pleasure.MockStrict<IDispatcher>();
dispatcher.Setup(r => r.Push(Pleasure.MockIt.Is<CommandComposite>(composite => composite.Parts.Any(message => this.predcatesStubs.Any(func => func(message))).ShouldBeTrue())));
IoCFactory.Instance.StubTryResolve(dispatcher.Object);
}
#endregion
#region Properties
[Obsolete("Use mock.Execute() instead of mock.Original.Execute()", false)]
public TMessage Original { get; set; }
#endregion
#region Fields
protected readonly Mock<IDispatcher> dispatcher;
readonly Dictionary<Type, List<CommandBase>> stubs = new Dictionary<Type, List<CommandBase>>();
readonly Dictionary<Type, int> stubsOfSuccess = new Dictionary<Type, int>();
readonly Mock<IRepository> repository;
private readonly List<Func<IMessage, bool>> predcatesStubs = new List<Func<IMessage, bool>>();
private bool isNew;
#endregion
#region Api Methods
public void Execute()
{
Original.Execute();
ShouldBePushed();
repository.VerifyAll();
}
public MockMessage<TMessage, TResult> StubPushAsThrow<TCommand>(TCommand command, Exception ex, MessageExecuteSetting setting = null) where TCommand : CommandBase
{
dispatcher.StubPushAsThrow(command, ex, setting);
return this;
}
public void ShouldBePushed()
{
foreach (var stub in stubs)
{
if (stubsOfSuccess.GetOrDefault(stub.Key) != stub.Value.Count)
throw new SpecificationException("Not Stub for {0}".F(stub.Key.Name));
}
}
public MockMessage<TMessage, TResult> StubPush<TCommand>(TCommand command, Action<ICompareFactoryDsl<TCommand, TCommand>> dsl = null, MessageExecuteSetting setting = null, object result = null) where TCommand : CommandBase
{
command.Setting = command.Setting ?? (setting ?? new MessageExecuteSetting());
var type = typeof(TCommand);
var value = stubs.GetOrDefault(type, new List<CommandBase>());
value.Add(command);
if (!stubs.ContainsKey(type))
stubs.Add(type, value);
predcatesStubs.Add(s =>
{
bool isAny = false;
foreach (var pair in this.stubs[type])
{
try
{
var sAsT = s as TCommand;
sAsT.ShouldEqualWeak(pair as TCommand, factoryDsl =>
{
factoryDsl.ForwardToAction(r => r.Setting, a =>
{
if (a.Setting != null)
a.Setting.ShouldEqualWeak(sAsT.Setting);
});
if (dsl != null)
dsl(factoryDsl);
});
isAny = true;
s.SetValue("Result", result);
if (this.stubsOfSuccess.ContainsKey(type))
this.stubsOfSuccess[type]++;
else
this.stubsOfSuccess.Add(type, 1);
break;
}
catch (InternalSpecificationException ex)
{
Console.WriteLine(ex);
}
}
return isAny;
});
return this;
}
public MockMessage<TMessage, TResult> StubPush<TCommand>(Action<IInventFactoryDsl<TCommand>> configure, Action<ICompareFactoryDsl<TCommand, TCommand>> dsl = null) where TCommand : CommandBase
{
return StubPush(Pleasure.Generator.Invent(configure), dsl);
}
public void ShouldBeDeleteByIds<TEntity>(IEnumerable<object> ids) where TEntity : class, IEntity, new()
{
repository.Verify(r => r.DeleteByIds<TEntity>(Pleasure.MockIt.IsStrong(ids)));
}
public void ShouldBeDeleteAll<TEntity>() where TEntity : class, IEntity, new()
{
repository.Verify(r => r.DeleteAll<TEntity>());
}
public void ShouldBeDelete<TEntity>(object id, int callCount = 1) where TEntity : class, IEntity, new()
{
repository.Verify(r => r.Delete<TEntity>(id), Times.Exactly(callCount));
}
public void ShouldBeDelete<TEntity>(TEntity entity, int callCount = 1) where TEntity : class, IEntity, new()
{
repository.Verify(r => r.Delete(Pleasure.MockIt.IsStrong(entity)), Times.Exactly(callCount));
}
public void ShouldBeSave<TEntity>(Action<TEntity> verify, int callCount = 1) where TEntity : class, IEntity, new()
{
Func<TEntity, bool> match = s =>
{
verify(s);
return true;
};
repository.Verify(r => r.Save(Pleasure.MockIt.Is<TEntity>(entity => match(entity))), Times.Exactly(callCount));
}
public void ShouldBeSaves<TEntity>(Action<IEnumerable<TEntity>> verify, int callCount = 1) where TEntity : class, IEntity, new()
{
Func<IEnumerable<TEntity>, bool> match = s =>
{
verify(s);
return true;
};
repository.Verify(r => r.Saves(Pleasure.MockIt.Is<IEnumerable<TEntity>>(entities => match(entities))), Times.Exactly(callCount));
}
public void ShouldBeFlush(int callCount = 1)
{
repository.Verify(r => r.Flush(), Times.Exactly(callCount));
}
public void ShouldBeSave<TEntity>(TEntity entity, int callCount = 1) where TEntity : class, IEntity, new()
{
ShouldBeSave<TEntity>(r => r.ShouldEqualWeak(entity), callCount);
}
public void ShouldNotBeSave<TEntity>() where TEntity : class, IEntity, new()
{
ShouldBeSave<TEntity>(r => r.ShouldBeAssignableTo<TEntity>(), 0);
}
public void ShouldNotBeSaveOrUpdate<TEntity>() where TEntity : class, IEntity, new()
{
ShouldBeSaveOrUpdate<TEntity>(r => r.ShouldBeAssignableTo<TEntity>(), 0);
}
public void ShouldBeSaveOrUpdate<TEntity>(Action<TEntity> verify, int callCount = 1) where TEntity : class, IEntity, new()
{
Func<TEntity, bool> match = s =>
{
verify(s);
return true;
};
repository.Verify(r => r.SaveOrUpdate(Pleasure.MockIt.Is<TEntity>(entity => match(entity))), Times.Exactly(callCount));
}
public void ShouldBeSaveOrUpdate<TEntity>(TEntity entity, int callCount = 1) where TEntity : class, IEntity, new()
{
ShouldBeSaveOrUpdate<TEntity>(r => r.ShouldEqualWeak(entity), callCount);
}
public MockMessage<TMessage, TResult> StubQuery<TQuery, TNextResult>(TQuery query, TNextResult result) where TQuery : QueryBase<TNextResult>
{
dispatcher.StubQuery(query, result, new MessageExecuteSetting());
dispatcher.StubQuery(query, result, null);
return this;
}
public MockMessage<TMessage, TResult> StubQuery<TQuery, TNextResult>(TQuery query, Action<ICompareFactoryDsl<TQuery, TQuery>> dsl, TNextResult result, MessageExecuteSetting executeSetting = null) where TQuery : QueryBase<TNextResult>
{
dispatcher.StubQuery(query, dsl, result, executeSetting);
return this;
}
public MockMessage<TMessage, TResult> StubQuery<TQuery, TNextResult>(TNextResult result) where TQuery : QueryBase<TNextResult>
{
return StubQuery(Pleasure.Generator.Invent<TQuery>(), result);
}
public MockMessage<TMessage, TResult> StubQueryAsNull<TQuery, TNextResult>() where TQuery : QueryBase<TNextResult>
{
return StubQuery<TQuery, TNextResult>(default(TNextResult));
}
public MockMessage<TMessage, TResult> StubQuery<TQuery, TNextResult>(Action<IInventFactoryDsl<TQuery>> configure, TNextResult result) where TQuery : QueryBase<TNextResult>
{
return StubQuery(Pleasure.Generator.Invent(configure), result);
}
#endregion
#region Data
public void ShouldBeIsResult(TResult expected)
{
Original.Result.ShouldEqualWeak(expected);
}
public void ShouldBeIsResult(Action<TResult> verifyResult)
{
verifyResult((TResult)Original.Result);
}
#endregion
#region Stubs
#region Api Methods
public MockMessage<TMessage, TResult> StubQuery<TEntity>(OrderSpecification<TEntity> orderSpecification = null, Specification<TEntity> whereSpecification = null, FetchSpecification<TEntity> fetchSpecification = null, PaginatedSpecification paginatedSpecification = null, params TEntity[] entities) where TEntity : class, IEntity, new()
{
return Stub(message => message.repository.StubQuery(orderSpecification, whereSpecification, fetchSpecification, paginatedSpecification, entities));
}
public MockMessage<TMessage, TResult> StubEmptyQuery<TEntity>(OrderSpecification<TEntity> orderSpecification = null, Specification<TEntity> whereSpecification = null, FetchSpecification<TEntity> fetchSpecification = null, PaginatedSpecification paginatedSpecification = null) where TEntity : class, IEntity, new()
{
return Stub(message => message.repository.StubQuery(orderSpecification, whereSpecification, fetchSpecification, paginatedSpecification, Pleasure.ToArray<TEntity>()));
}
public MockMessage<TMessage, TResult> StubPaginated<TEntity>(PaginatedSpecification paginatedSpecification, OrderSpecification<TEntity> orderSpecification = null, Specification<TEntity> whereSpecification = null, FetchSpecification<TEntity> fetchSpecification = null, IncPaginatedResult<TEntity> result = null) where TEntity : class, IEntity, new()
{
return Stub(message => message.repository.StubPaginated(paginatedSpecification, orderSpecification, whereSpecification, fetchSpecification, result));
}
public MockMessage<TMessage, TResult> StubNotEmptyQuery<TEntity>(OrderSpecification<TEntity> orderSpecification = null, Specification<TEntity> whereSpecification = null, FetchSpecification<TEntity> fetchSpecification = null, PaginatedSpecification paginatedSpecification = null, int countEntity = 1) where TEntity : class, IEntity, new()
{
var entities = Pleasure.ToList<TEntity>();
for (int i = 0; i < countEntity; i++)
entities.Add(Pleasure.Generator.Invent<TEntity>());
return StubQuery(orderSpecification, whereSpecification, fetchSpecification, paginatedSpecification, entities.ToArray());
}
public MockMessage<TMessage, TResult> StubGetById<TEntity>(object id, TEntity res) where TEntity : class, IEntity, new()
{
return Stub(message => message.repository.StubGetById(id, res));
}
public MockMessage<TMessage, TResult> StubSave<TEntity>(TEntity res, object id) where TEntity : class, IEntity, new()
{
Action<TEntity> verify = entity =>
{
entity.ShouldEqualWeak(res, null);
entity.SetValue("Id", id);
};
return Stub(message => message.repository.Setup(r => r.Save(Pleasure.MockIt.Is<TEntity>(verify))));
}
public MockMessage<TMessage, TResult> StubSave<TEntity>(Action<TEntity> action, object id) where TEntity : class, IEntity, new()
{
Func<TEntity, bool> match = s =>
{
action(s);
return true;
};
Action<TEntity> verify = entity =>
{
match(entity);
entity.SetValue("Id", id);
};
return Stub(message => message.repository.Setup(r => r.Save(Pleasure.MockIt.Is<TEntity>(verify))));
}
public MockMessage<TMessage, TResult> StubLoadById<TEntity>(object id, TEntity res) where TEntity : class, IEntity, new()
{
return Stub(message => message.repository.StubLoadById(id, res));
}
#endregion
MockMessage<TMessage, TResult> Stub(Action<MockMessage<TMessage, TResult>> configureMock)
{
configureMock(this);
return this;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function EWCreatorWindow::init( %this )
{
// Just so we can recall this method for testing changes
// without restarting.
if ( isObject( %this.array ) )
%this.array.delete();
%this.array = new ArrayObject();
%this.array.caseSensitive = true;
%this.setListView( true );
%this.beginGroup( "Environment" );
// Removed Prefab as there doesn't really seem to be a point in creating a blank one
//%this.registerMissionObject( "Prefab", "Prefab" );
%this.registerMissionObject( "SkyBox", "Sky Box" );
%this.registerMissionObject( "CloudLayer", "Cloud Layer" );
%this.registerMissionObject( "BasicClouds", "Basic Clouds" );
%this.registerMissionObject( "ScatterSky", "Scatter Sky" );
%this.registerMissionObject( "Sun", "Basic Sun" );
%this.registerMissionObject( "Lightning" );
%this.registerMissionObject( "WaterBlock", "Water Block" );
%this.registerMissionObject( "SFXEmitter", "Sound Emitter" );
%this.registerMissionObject( "Precipitation" );
%this.registerMissionObject( "ParticleEmitterNode", "Particle Emitter" );
%this.registerMissionObject( "VolumetricFog", "Volumetric Fog" );
%this.registerMissionObject( "RibbonNode", "Ribbon" );
// Legacy features. Users should use Ground Cover and the Forest Editor.
//%this.registerMissionObject( "fxShapeReplicator", "Shape Replicator" );
//%this.registerMissionObject( "fxFoliageReplicator", "Foliage Replicator" );
%this.registerMissionObject( "PointLight", "Point Light" );
%this.registerMissionObject( "SpotLight", "Spot Light" );
%this.registerMissionObject( "GroundCover", "Ground Cover" );
%this.registerMissionObject( "TerrainBlock", "Terrain Block" );
%this.registerMissionObject( "GroundPlane", "Ground Plane" );
%this.registerMissionObject( "WaterPlane", "Water Plane" );
%this.registerMissionObject( "PxCloth", "Cloth" );
%this.registerMissionObject( "ForestWindEmitter", "Wind Emitter" );
%this.registerMissionObject( "DustEmitter", "Dust Emitter" );
%this.registerMissionObject( "DustSimulation", "Dust Simulation" );
%this.registerMissionObject( "DustEffecter", "Dust Effecter" );
%this.endGroup();
%this.beginGroup( "Level" );
%this.registerMissionObject( "MissionArea", "Mission Area" );
%this.registerMissionObject( "Path" );
%this.registerMissionObject( "Marker", "Path Node" );
%this.registerMissionObject( "Trigger" );
%this.registerMissionObject( "PhysicalZone", "Physical Zone" );
%this.registerMissionObject( "Camera" );
%this.registerMissionObject( "LevelInfo", "Level Info" );
%this.registerMissionObject( "TimeOfDay", "Time of Day" );
%this.registerMissionObject( "Zone", "Zone" );
%this.registerMissionObject( "Portal", "Zone Portal" );
%this.registerMissionObject( "SpawnSphere", "Player Spawn Sphere", "PlayerDropPoint" );
%this.registerMissionObject( "SpawnSphere", "Observer Spawn Sphere", "ObserverDropPoint" );
%this.registerMissionObject( "SFXSpace", "Sound Space" );
%this.registerMissionObject( "OcclusionVolume", "Occlusion Volume" );
%this.registerMissionObject( "AccumulationVolume", "Accumulation Volume" );
%this.registerMissionObject( "Entity", "Entity" );
%this.endGroup();
%this.beginGroup( "System" );
%this.registerMissionObject( "SimGroup" );
%this.endGroup();
%this.beginGroup( "ExampleObjects" );
%this.registerMissionObject( "RenderObjectExample" );
%this.registerMissionObject( "RenderMeshExample" );
%this.registerMissionObject( "RenderShapeExample" );
%this.endGroup();
}
function EWCreatorWindow::onWake( %this )
{
CreatorTabBook.selectPage( 0 );
CreatorTabBook.onTabSelected( "Scripted" );
}
function EWCreatorWindow::beginGroup( %this, %group )
{
%this.currentGroup = %group;
}
function EWCreatorWindow::endGroup( %this, %group )
{
%this.currentGroup = "";
}
function EWCreatorWindow::getCreateObjectPosition()
{
%focusPoint = LocalClientConnection.getControlObject().getLookAtPoint();
if( %focusPoint $= "" )
return "0 0 0";
else
return getWord( %focusPoint, 1 ) SPC getWord( %focusPoint, 2 ) SPC getWord( %focusPoint, 3 );
}
function EWCreatorWindow::registerMissionObject( %this, %class, %name, %buildfunc, %group )
{
if( !isClass(%class) )
return;
if ( %name $= "" )
%name = %class;
if ( %this.currentGroup !$= "" && %group $= "" )
%group = %this.currentGroup;
if ( %class $= "" || %group $= "" )
{
warn( "EWCreatorWindow::registerMissionObject, invalid parameters!" );
return;
}
%args = new ScriptObject();
%args.val[0] = %class;
%args.val[1] = %name;
%args.val[2] = %buildfunc;
%this.array.push_back( %group, %args );
}
function EWCreatorWindow::getNewObjectGroup( %this )
{
return %this.objectGroup;
}
function EWCreatorWindow::setNewObjectGroup( %this, %group )
{
if( %this.objectGroup )
{
%oldItemId = EditorTree.findItemByObjectId( %this.objectGroup );
if( %oldItemId > 0 )
EditorTree.markItem( %oldItemId, false );
}
%group = %group.getID();
%this.objectGroup = %group;
%itemId = EditorTree.findItemByObjectId( %group );
EditorTree.markItem( %itemId );
}
function EWCreatorWindow::createStatic( %this, %file )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( getScene(0) );
%objId = new TSStatic()
{
shapeName = %file;
position = %this.getCreateObjectPosition();
parentGroup = %this.objectGroup;
};
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::createPrefab( %this, %file )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( getScene(0) );
%objId = new Prefab()
{
filename = %file;
position = %this.getCreateObjectPosition();
parentGroup = %this.objectGroup;
};
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::createObject( %this, %cmd )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( getScene(0) );
pushInstantGroup();
%objId = eval(%cmd);
popInstantGroup();
if( isObject( %objId ) )
%this.onFinishCreateObject( %objId );
return %objId;
}
function EWCreatorWindow::onFinishCreateObject( %this, %objId )
{
%this.objectGroup.add( %objId );
if( %objId.isMemberOfClass( "SceneObject" ) )
{
%objId.position = %this.getCreateObjectPosition();
//flush new position
%objId.setTransform( %objId.getTransform() );
}
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::onObjectCreated( %this, %objId )
{
// Can we submit an undo action?
if ( isObject( %objId ) )
MECreateUndoAction::submit( %objId );
EditorTree.clearSelection();
EWorldEditor.clearSelection();
EWorldEditor.selectObject( %objId );
// When we drop the selection don't store undo
// state for it... the creation deals with it.
EWorldEditor.dropSelection( true );
}
function CreatorTabBook::onTabSelected( %this, %text, %idx )
{
if ( %this.isAwake() )
{
EWCreatorWindow.tab = %text;
EWCreatorWindow.navigate( "" );
}
}
function EWCreatorWindow::navigate( %this, %address )
{
CreatorIconArray.frozen = true;
CreatorIconArray.clear();
CreatorPopupMenu.clear();
if ( %this.tab $= "Scripted" )
{
%category = getWord( %address, 1 );
%dataGroup = "DataBlockGroup";
for ( %i = 0; %i < %dataGroup.getCount(); %i++ )
{
%obj = %dataGroup.getObject(%i);
// echo ("Obj: " @ %obj.getName() @ " - " @ %obj.category );
if ( %obj.category $= "" && %obj.category == 0 )
continue;
// Add category to popup menu if not there already
if ( CreatorPopupMenu.findText( %obj.category ) == -1 )
CreatorPopupMenu.add( %obj.category );
if ( %address $= "" )
{
%ctrl = %this.findIconCtrl( %obj.category );
if ( %ctrl == -1 )
{
%this.addFolderIcon( %obj.category );
}
}
else if ( %address $= %obj.category )
{
%ctrl = %this.findIconCtrl( %obj.getName() );
if ( %ctrl == -1 )
%this.addShapeIcon( %obj );
}
}
}
if ( %this.tab $= "Meshes" )
{
%fullPath = findFirstFileMultiExpr( getFormatExtensions() );
while ( %fullPath !$= "" )
{
if (strstr(%fullPath, "cached.dts") != -1)
{
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
continue;
}
%fullPath = makeRelativePath( %fullPath, getMainDotCSDir() );
%splitPath = strreplace( %fullPath, " ", "_" );
%splitPath = strreplace( %splitPath, "/", " " );
if( getWord(%splitPath, 0) $= "tools" )
{
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
continue;
}
%dirCount = getWordCount( %splitPath ) - 1;
%pathFolders = getWords( %splitPath, 0, %dirCount - 1 );
// Add this file's path (parent folders) to the
// popup menu if it isn't there yet.
%temp = strreplace( %pathFolders, " ", "/" );
%temp = strreplace( %temp, "_", " " );
%r = CreatorPopupMenu.findText( %temp );
if ( %r == -1 )
{
CreatorPopupMenu.add( %temp );
}
// Is this file in the current folder?
if ( stricmp( %pathFolders, %address ) == 0 )
{
%this.addStaticIcon( %fullPath );
}
// Then is this file in a subfolder we need to add
// a folder icon for?
else
{
%wordIdx = 0;
%add = false;
if ( %address $= "" )
{
%add = true;
%wordIdx = 0;
}
else
{
for ( ; %wordIdx < %dirCount; %wordIdx++ )
{
%temp = getWords( %splitPath, 0, %wordIdx );
if ( stricmp( %temp, %address ) == 0 )
{
%add = true;
%wordIdx++;
break;
}
}
}
if ( %add == true )
{
%folder = getWord( %splitPath, %wordIdx );
%ctrl = %this.findIconCtrl( %folder );
if ( %ctrl == -1 )
%this.addFolderIcon( %folder );
}
}
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
}
}
if ( %this.tab $= "Level" )
{
// Add groups to popup menu
%array = %this.array;
%array.sortk();
%count = %array.count();
if ( %count > 0 )
{
%lastGroup = "";
for ( %i = 0; %i < %count; %i++ )
{
%group = %array.getKey( %i );
if ( %group !$= %lastGroup )
{
CreatorPopupMenu.add( %group );
if ( %address $= "" )
%this.addFolderIcon( %group );
}
if ( %address $= %group )
{
%args = %array.getValue( %i );
%class = %args.val[0];
%name = %args.val[1];
%func = %args.val[2];
%this.addMissionObjectIcon( %class, %name, %func );
}
%lastGroup = %group;
}
}
}
if ( %this.tab $= "Prefabs" )
{
%expr = "*.prefab";
%fullPath = findFirstFile( %expr );
while ( %fullPath !$= "" )
{
%fullPath = makeRelativePath( %fullPath, getMainDotCSDir() );
%splitPath = strreplace( %fullPath, " ", "_" );
%splitPath = strreplace( %splitPath, "/", " " );
if( getWord(%splitPath, 0) $= "tools" )
{
%fullPath = findNextFile( %expr );
continue;
}
%dirCount = getWordCount( %splitPath ) - 1;
%pathFolders = getWords( %splitPath, 0, %dirCount - 1 );
// Add this file's path (parent folders) to the
// popup menu if it isn't there yet.
%temp = strreplace( %pathFolders, " ", "/" );
%temp = strreplace( %temp, "_", " " );
%r = CreatorPopupMenu.findText( %temp );
if ( %r == -1 )
{
CreatorPopupMenu.add( %temp );
}
// Is this file in the current folder?
if ( (%dirCount == 0 && %address $= "") || stricmp( %pathFolders, %address ) == 0 )
{
%this.addPrefabIcon( %fullPath );
}
// Then is this file in a subfolder we need to add
// a folder icon for?
else
{
%wordIdx = 0;
%add = false;
if ( %address $= "" )
{
%add = true;
%wordIdx = 0;
}
else
{
for ( ; %wordIdx < %dirCount; %wordIdx++ )
{
%temp = getWords( %splitPath, 0, %wordIdx );
if ( stricmp( %temp, %address ) == 0 )
{
%add = true;
%wordIdx++;
break;
}
}
}
if ( %add == true )
{
%folder = getWord( %splitPath, %wordIdx );
%ctrl = %this.findIconCtrl( %folder );
if ( %ctrl == -1 )
%this.addFolderIcon( %folder );
}
}
%fullPath = findNextFile( %expr );
}
}
CreatorIconArray.sort( "alphaIconCompare" );
for ( %i = 0; %i < CreatorIconArray.getCount(); %i++ )
{
CreatorIconArray.getObject(%i).autoSize = false;
}
CreatorIconArray.frozen = false;
CreatorIconArray.refresh();
// Recalculate the array for the parent guiScrollCtrl
CreatorIconArray.getParent().computeSizes();
%this.address = %address;
CreatorPopupMenu.sort();
%str = strreplace( %address, " ", "/" );
%r = CreatorPopupMenu.findText( %str );
if ( %r != -1 )
CreatorPopupMenu.setSelected( %r, false );
else
CreatorPopupMenu.setText( %str );
CreatorPopupMenu.tooltip = %str;
}
function EWCreatorWindow::navigateDown( %this, %folder )
{
if ( %this.address $= "" )
%address = %folder;
else
%address = %this.address SPC %folder;
// Because this is called from an IconButton::onClick command
// we have to wait a tick before actually calling navigate, else
// we would delete the button out from under itself.
%this.schedule( 1, "navigate", %address );
}
function EWCreatorWindow::navigateUp( %this )
{
%count = getWordCount( %this.address );
if ( %count == 0 )
return;
if ( %count == 1 )
%address = "";
else
%address = getWords( %this.address, 0, %count - 2 );
%this.navigate( %address );
}
function EWCreatorWindow::setListView( %this, %noupdate )
{
//CreatorIconArray.clear();
//CreatorIconArray.setVisible( false );
CreatorIconArray.setVisible( true );
%this.contentCtrl = CreatorIconArray;
%this.isList = true;
if ( %noupdate == true )
%this.navigate( %this.address );
}
//function EWCreatorWindow::setIconView( %this )
//{
//echo( "setIconView" );
//
//CreatorIconStack.clear();
//CreatorIconStack.setVisible( false );
//
//CreatorIconArray.setVisible( true );
//%this.contentCtrl = CreatorIconArray;
//%this.isList = false;
//
//%this.navigate( %this.address );
//}
function EWCreatorWindow::findIconCtrl( %this, %name )
{
for ( %i = 0; %i < %this.contentCtrl.getCount(); %i++ )
{
%ctrl = %this.contentCtrl.getObject( %i );
if ( %ctrl.text $= %name )
return %ctrl;
}
return -1;
}
function EWCreatorWindow::createIcon( %this )
{
%ctrl = new GuiIconButtonCtrl()
{
profile = "GuiCreatorIconButtonProfile";
buttonType = "radioButton";
groupNum = "-1";
};
if ( %this.isList )
{
%ctrl.iconLocation = "Left";
%ctrl.textLocation = "Right";
%ctrl.extent = "348 19";
%ctrl.textMargin = 8;
%ctrl.buttonMargin = "2 2";
%ctrl.autoSize = true;
}
else
{
%ctrl.iconLocation = "Center";
%ctrl.textLocation = "Bottom";
%ctrl.extent = "40 40";
}
return %ctrl;
}
function EWCreatorWindow::addFolderIcon( %this, %text )
{
%ctrl = %this.createIcon();
%ctrl.altCommand = "EWCreatorWindow.navigateDown(\"" @ %text @ "\");";
%ctrl.iconBitmap = "tools/gui/images/folder.png";
%ctrl.text = %text;
%ctrl.tooltip = %text;
%ctrl.class = "CreatorFolderIconBtn";
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addMissionObjectIcon( %this, %class, %name, %buildfunc )
{
%ctrl = %this.createIcon();
// If we don't find a specific function for building an
// object then fall back to the stock one
%method = "build" @ %buildfunc;
if( !ObjectBuilderGui.isMethod( %method ) )
%method = "build" @ %class;
if( !ObjectBuilderGui.isMethod( %method ) )
%cmd = "return new " @ %class @ "();";
else
%cmd = "ObjectBuilderGui." @ %method @ "();";
%ctrl.altCommand = "ObjectBuilderGui.newObjectCallback = \"EWCreatorWindow.onFinishCreateObject\"; EWCreatorWindow.createObject( \"" @ %cmd @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class );
%ctrl.text = %name;
%ctrl.class = "CreatorMissionObjectIconBtn";
%ctrl.tooltip = %class;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addShapeIcon( %this, %datablock )
{
%ctrl = %this.createIcon();
%name = %datablock.getName();
%class = %datablock.getClassName();
%cmd = %class @ "::create(" @ %name @ ");";
%shapePath = ( %datablock.shapeFile !$= "" ) ? %datablock.shapeFile : %datablock.shapeName;
%createCmd = "EWCreatorWindow.createObject( \\\"" @ %cmd @ "\\\" );";
%ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %shapePath @ "\", \"" @ %createCmd @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class );
%ctrl.text = %name;
%ctrl.class = "CreatorShapeIconBtn";
%ctrl.tooltip = %name;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addStaticIcon( %this, %fullPath )
{
%ctrl = %this.createIcon();
%ext = fileExt( %fullPath );
%file = fileBase( %fullPath );
%fileLong = %file @ %ext;
%tip = %fileLong NL
"Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL
"Date Created: " @ fileCreatedTime( %fullPath ) NL
"Last Modified: " @ fileModifiedTime( %fullPath );
%createCmd = "EWCreatorWindow.createStatic( \\\"" @ %fullPath @ "\\\" );";
%ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %fullPath @ "\", \"" @ %createCmd @ "\" );";
%ctrl.iconBitmap = ( ( %ext $= ".dts" ) ? EditorIconRegistry::findIconByClassName( "TSStatic" ) : "tools/gui/images/iconCollada" );
%ctrl.text = %file;
%ctrl.class = "CreatorStaticIconBtn";
%ctrl.tooltip = %tip;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addPrefabIcon( %this, %fullPath )
{
%ctrl = %this.createIcon();
%ext = fileExt( %fullPath );
%file = fileBase( %fullPath );
%fileLong = %file @ %ext;
%tip = %fileLong NL
"Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL
"Date Created: " @ fileCreatedTime( %fullPath ) NL
"Last Modified: " @ fileModifiedTime( %fullPath );
%ctrl.altCommand = "EWCreatorWindow.createPrefab( \"" @ %fullPath @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( "Prefab" );
%ctrl.text = %file;
%ctrl.class = "CreatorPrefabIconBtn";
%ctrl.tooltip = %tip;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function CreatorPopupMenu::onSelect( %this, %id, %text )
{
%split = strreplace( %text, "/", " " );
EWCreatorWindow.navigate( %split );
}
function alphaIconCompare( %a, %b )
{
if ( %a.class $= "CreatorFolderIconBtn" )
if ( %b.class !$= "CreatorFolderIconBtn" )
return -1;
if ( %b.class $= "CreatorFolderIconBtn" )
if ( %a.class !$= "CreatorFolderIconBtn" )
return 1;
%result = stricmp( %a.text, %b.text );
return %result;
}
// Generic create object helper for use from the console.
function genericCreateObject( %class )
{
if ( !isClass( %class ) )
{
warn( "createObject( " @ %class @ " ) - Was not a valid class." );
return;
}
%cmd = "return new " @ %class @ "();";
%obj = EWCreatorWindow.createObject( %cmd );
// In case the caller wants it.
return %obj;
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class CtorTests
{
[Fact]
public static void TestDefaultConstructor()
{
using (X509Certificate2 c = new X509Certificate2())
{
VerifyDefaultConstructor(c);
}
}
private static void VerifyDefaultConstructor(X509Certificate2 c)
{
IntPtr h = c.Handle;
object ignored;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber());
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Issuer);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Subject);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.RawData);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Thumbprint);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.SignatureAlgorithm);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.HasPrivateKey);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Version);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Archived);
Assert.ThrowsAny<CryptographicException>(() => c.Archived = false);
Assert.ThrowsAny<CryptographicException>(() => c.FriendlyName = "Hi");
Assert.ThrowsAny<CryptographicException>(() => ignored = c.SubjectName);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.IssuerName);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString());
Assert.ThrowsAny<CryptographicException>(() => c.GetEffectiveDateString());
Assert.ThrowsAny<CryptographicException>(() => c.GetExpirationDateString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKeyString());
Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertData());
Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertDataString());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumberString());
#pragma warning disable 0618
Assert.ThrowsAny<CryptographicException>(() => c.GetIssuerName());
Assert.ThrowsAny<CryptographicException>(() => c.GetName());
#pragma warning restore 0618
}
[Fact]
public static void TestConstructor_DER()
{
byte[] expectedThumbPrint = new byte[]
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (c) =>
{
IntPtr h = c.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
Assert.Equal(expectedThumbPrint, actualThumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
public static void TestConstructor_PEM()
{
byte[] expectedThumbPrint =
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (cert) =>
{
IntPtr h = cert.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = cert.GetCertHash();
Assert.Equal(expectedThumbPrint, actualThumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificatePemBytes))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
public static void TestCopyConstructor_NoPal()
{
using (var c1 = new X509Certificate2())
using (var c2 = new X509Certificate2(c1))
{
VerifyDefaultConstructor(c1);
VerifyDefaultConstructor(c2);
}
}
[Fact]
public static void TestCopyConstructor_Pal()
{
using (var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var c2 = new X509Certificate2(c1))
{
Assert.Equal(c1.GetCertHash(), c2.GetCertHash());
Assert.Equal(c1.GetKeyAlgorithm(), c2.GetKeyAlgorithm());
Assert.Equal(c1.GetKeyAlgorithmParameters(), c2.GetKeyAlgorithmParameters());
Assert.Equal(c1.GetKeyAlgorithmParametersString(), c2.GetKeyAlgorithmParametersString());
Assert.Equal(c1.GetPublicKey(), c2.GetPublicKey());
Assert.Equal(c1.GetSerialNumber(), c2.GetSerialNumber());
Assert.Equal(c1.Issuer, c2.Issuer);
Assert.Equal(c1.Subject, c2.Subject);
Assert.Equal(c1.RawData, c2.RawData);
Assert.Equal(c1.Thumbprint, c2.Thumbprint);
Assert.Equal(c1.SignatureAlgorithm.Value, c2.SignatureAlgorithm.Value);
Assert.Equal(c1.HasPrivateKey, c2.HasPrivateKey);
Assert.Equal(c1.Version, c2.Version);
Assert.Equal(c1.Archived, c2.Archived);
Assert.Equal(c1.SubjectName.Name, c2.SubjectName.Name);
Assert.Equal(c1.IssuerName.Name, c2.IssuerName.Name);
Assert.Equal(c1.GetCertHashString(), c2.GetCertHashString());
Assert.Equal(c1.GetEffectiveDateString(), c2.GetEffectiveDateString());
Assert.Equal(c1.GetExpirationDateString(), c2.GetExpirationDateString());
Assert.Equal(c1.GetPublicKeyString(), c2.GetPublicKeyString());
Assert.Equal(c1.GetRawCertData(), c2.GetRawCertData());
Assert.Equal(c1.GetRawCertDataString(), c2.GetRawCertDataString());
Assert.Equal(c1.GetSerialNumberString(), c2.GetSerialNumberString());
#pragma warning disable 0618
Assert.Equal(c1.GetIssuerName(), c2.GetIssuerName());
Assert.Equal(c1.GetName(), c2.GetName());
#pragma warning restore 0618
}
}
[Fact]
public static void TestCopyConstructor_Lifetime_Independent()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
using (var c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
{
RSA rsa = c2.GetRSAPrivateKey();
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
c1.Dispose();
rsa.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
// Verify other cert and previous key do not affect cert
using (rsa = c2.GetRSAPrivateKey())
{
hash = new byte[20];
sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
}
}
[Fact]
public static void TestCopyConstructor_Lifetime_Cloned()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
var c2 = new X509Certificate2(c1);
TestPrivateKey(c1, true);
TestPrivateKey(c2, true);
c1.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, false);
TestPrivateKey(c2, true);
c2.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c2, false);
}
[Fact]
public static void TestCopyConstructor_Lifetime_Cloned_Reversed()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
var c2 = new X509Certificate2(c1);
TestPrivateKey(c1, true);
TestPrivateKey(c2, true);
c2.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, true);
TestPrivateKey(c2, false);
c1.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, false);
}
private static void TestPrivateKey(X509Certificate2 c, bool expectSuccess)
{
if (expectSuccess)
{
using (RSA rsa = c.GetRSAPrivateKey())
{
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
}
else
{
Assert.ThrowsAny<CryptographicException>(() => c.GetRSAPrivateKey());
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedCerData not supported on Unix
public static void TestConstructor_SerializedCert_Windows()
{
const string ExpectedThumbPrint = "71CB4E2B02738AD44F8B382C93BD17BA665F9914";
Action<X509Certificate2> assert = (cert) =>
{
IntPtr h = cert.Handle;
Assert.NotEqual(IntPtr.Zero, h);
Assert.Equal(ExpectedThumbPrint, cert.Thumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.StoreSavedAsSerializedCerData))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedCerData not supported on Unix
public static void TestByteArrayConstructor_SerializedCert_Unix()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.StoreSavedAsSerializedCerData));
}
[Fact]
public static void TestNullConstructorArguments()
{
Assert.Throws<ArgumentNullException>(() => new X509Certificate2((string)null));
AssertExtensions.Throws<ArgumentException>("handle", () => new X509Certificate2(IntPtr.Zero));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2((byte[])null, (string)null));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2(Array.Empty<byte>(), (string)null));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2((byte[])null, (string)null, X509KeyStorageFlags.DefaultKeySet));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2(Array.Empty<byte>(), (string)null, X509KeyStorageFlags.DefaultKeySet));
// A null string password does not throw
using (new X509Certificate2(TestData.MsCertificate, (string)null)) { }
using (new X509Certificate2(TestData.MsCertificate, (string)null, X509KeyStorageFlags.DefaultKeySet)) { }
Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromCertFile(null));
Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromSignedFile(null));
AssertExtensions.Throws<ArgumentNullException>("cert", () => new X509Certificate2((X509Certificate2)null));
AssertExtensions.Throws<ArgumentException>("handle", () => new X509Certificate2(IntPtr.Zero));
// A null SecureString password does not throw
using (new X509Certificate2(TestData.MsCertificate, (SecureString)null)) { }
using (new X509Certificate2(TestData.MsCertificate, (SecureString)null, X509KeyStorageFlags.DefaultKeySet)) { }
// For compat reasons, the (byte[]) constructor (and only that constructor) treats a null or 0-length array as the same
// as calling the default constructor.
{
using (X509Certificate2 c = new X509Certificate2((byte[])null))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
}
}
{
using (X509Certificate2 c = new X509Certificate2(Array.Empty<byte>()))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
}
}
}
[Fact]
public static void InvalidCertificateBlob()
{
CryptographicException ex = Assert.ThrowsAny<CryptographicException>(
() => new X509Certificate2(new byte[] { 0x01, 0x02, 0x03 }));
CryptographicException defaultException = new CryptographicException();
Assert.NotEqual(defaultException.Message, ex.Message);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(unchecked((int)0x80092009), ex.HResult);
// TODO (3233): Test that Message is also set correctly
//Assert.Equal("Cannot find the requested object.", ex.Message);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Assert.Equal(-25257, ex.HResult);
}
else // Any Unix
{
Assert.Equal(0x0D07803A, ex.HResult);
Assert.Equal("error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error", ex.Message);
}
}
[Fact]
public static void InvalidStorageFlags()
{
byte[] nonEmptyBytes = new byte[1];
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
// No test is performed here for the ephemeral flag failing downlevel, because the live
// binary is always used by default, meaning it doesn't know EphemeralKeySet doesn't exist.
}
#if netcoreapp
[Fact]
public static void InvalidStorageFlags_PersistedEphemeral()
{
const X509KeyStorageFlags PersistedEphemeral =
X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet;
byte[] nonEmptyBytes = new byte[1];
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(nonEmptyBytes, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(string.Empty, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(nonEmptyBytes, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, PersistedEphemeral));
}
#endif
}
}
| |
//! \file OggStream.cs
//! \date Sat Apr 08 01:43:58 2017
//! \brief libogg partial implementation.
//
// Copyright (C) 2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using GameRes.Utility;
namespace GameRes.Formats.Vorbis
{
internal sealed class OggBitStream : IDisposable
{
LsbBitStream m_input;
public OggBitStream (OggPacket input)
{
// certainly an overhead to create a new stream for every packet, but it's so convenient
var buf = new MemoryStream (input.Packet);
m_input = new LsbBitStream (buf);
}
/// <summary>Read <paramref name="count"/> bits from a stream.</summary>
/// <returns>-1 if there was not enough bits in a stream</returns>
public int ReadBits (int count)
{
if (count <= 24)
return m_input.GetBits (count);
else if (count > 32)
throw new ArgumentOutOfRangeException ("count", "Attempted to read more than 32 bits from OggBitStream.");
int lo = m_input.GetBits (24);
return m_input.GetBits (count - 24) << 24 | lo;
}
/// <summary>Read 8-bit integer from bitstream.</summary>
/// <returns>-1 if there was not enough bits in a stream</returns>
public int ReadByte ()
{
return ReadBits (8);
}
/// <summary>Read 8-bit integer from bitstream.</summary>
/// <exception cref="EndOfStreamException">Thrown if there's not enough bits in a stream.</exception>
public byte ReadUInt8 ()
{
int b = ReadBits (8);
if (-1 == b)
throw new EndOfStreamException();
return (byte)b;
}
/// <summary>Read 32-bit integer from bitstream.</summary>
/// <exception cref="EndOfStreamException">Thrown if there's not enough bits in a stream.</exception>
public int ReadInt32 ()
{
int lo = ReadBits (16);
int hi = ReadBits (16);
if (-1 == lo || -1 == hi)
throw new EndOfStreamException();
return hi << 16 | lo;
}
/// <summary>Attempt to read <paramref name="count"/> bytes from stream.</summary>
/// <exception cref="EndOfStreamException">Thrown if there's not enough bytes in a bitstream.</exception>
public byte[] ReadBytes (int count)
{
var buf = new byte[count];
for (int i = 0; i < count; ++i)
buf[i] = ReadUInt8();
return buf;
}
bool m_disposed = false;
public void Dispose ()
{
if (!m_disposed)
{
m_input.Dispose();
m_disposed = true;
}
}
}
// struct ogg_packet
// https://xiph.org/ogg/doc/libogg/ogg_packet.html
internal class OggPacket
{
public byte[] Packet;
public bool BoS;
public bool EoS;
public long GranulePos;
public long PacketNo;
public void SetPacket (long packet_no, byte[] packet)
{
PacketNo = packet_no;
Packet = packet;
}
}
// struct ogg_stream_state
// https://xiph.org/ogg/doc/libogg/ogg_stream_state.html
internal class OggStreamState
{
byte[] BodyData; // bytes from packet bodies
int BodyStorage; // storage elements allocated
int BodyFill; // elements stored; fill mark
int BodyReturned; // elements of fill returned
int[] LacingVals; // The values that will go to the segment table granulepos values for headers.
long[] GranuleVals; // Not compact this way, but it is simple coupled to the lacing fifo.
int LacingStorage;
int LacingFill;
byte[] Header; // working space for header encode
int HeaderFill;
bool EoS; // set when we have buffered the last packet in the logical bitstream
bool BoS; // set after we've written the initial page of a logical bitstream
int SerialNo;
int PageNo;
long PacketNo; // sequence number for decode; the framing knows where there's a hole in the data,
// but we need coupling so that the codec (which is in a seperate abstraction
// layer) also knows about the gap
long GranulePos;
// https://xiph.org/ogg/doc/libogg/ogg_stream_init.html
public OggStreamState (int serial_no)
{
BodyStorage = 0x4000;
LacingStorage = 0x400;
BodyData = new byte[BodyStorage];
LacingVals = new int[LacingStorage];
GranuleVals = new long[LacingStorage];
Header = new byte[282];
SerialNo = serial_no;
}
public void Clear ()
{
BodyStorage = 0;
BodyFill = 0;
BodyReturned = 0;
LacingStorage = 0;
LacingFill = 0;
HeaderFill = 0;
EoS = false;
BoS = false;
SerialNo = 0;
PageNo = 0;
PacketNo = 0;
GranulePos = 0;
}
public bool PacketIn (OggPacket op)
{
int bytes = op.Packet.Length;
int lacing_vals = bytes / 255 + 1;
if (BodyReturned > 0)
{
// advance packet data according to the body_returned pointer.
// We had to keep it around to return a pointer into the buffer last call.
BodyFill -= BodyReturned;
if (BodyFill > 0)
Buffer.BlockCopy (BodyData, BodyReturned, BodyData, 0, BodyFill);
BodyReturned = 0;
}
// make sure we have the buffer storage
if(!BodyExpand (bytes) || !LacingExpand (lacing_vals))
return false;
// Copy in the submitted packet.
Buffer.BlockCopy (op.Packet, 0, BodyData, BodyFill, op.Packet.Length);
BodyFill += op.Packet.Length;
// Store lacing vals for this packet
int i;
for (i = 0; i < lacing_vals-1; ++i)
{
LacingVals[LacingFill + i] = 0xFF;
GranuleVals[LacingFill + i] = GranulePos;
}
LacingVals[LacingFill + i] = bytes % 0xFF;
GranulePos = GranuleVals[LacingFill+i] = GranulePos;
// flag the first segment as the beginning of the packet
LacingVals[LacingFill] |= 0x100;
LacingFill += lacing_vals;
PacketNo++;
EoS = op.EoS;
return true;
}
public void Write (Stream output)
{
var page = new OggPage();
while (PageOut (page))
{
output.Write (page.Header, 0, page.HeaderLength);
output.Write (page.Body, page.BodyStart, page.BodyLength);
}
}
public void Flush (Stream output)
{
var page = new OggPage();
while (Flush (page, true, 0x1000))
{
output.Write (page.Header, 0, page.HeaderLength);
output.Write (page.Body, page.BodyStart, page.BodyLength);
}
}
public bool PageOut (OggPage page)
{
bool force = EoS && (LacingFill > 0) || (LacingFill > 0 && !BoS);
return Flush (page, force, 0x1000);
}
bool BodyExpand (int needed)
{
if (BodyStorage - needed <= BodyFill)
{
if (BodyStorage > int.MaxValue - needed)
{
Clear();
return false;
}
int body_storage = BodyStorage + needed;
if (body_storage < int.MaxValue - 1024)
body_storage += 1024;
Array.Resize (ref BodyData, body_storage);
BodyStorage = body_storage;
}
return true;
}
bool LacingExpand (int needed)
{
if (LacingStorage - needed <= LacingFill)
{
if (LacingStorage > int.MaxValue - needed)
{
Clear();
return false;
}
int lacing_storage = LacingStorage + needed;
if (lacing_storage < int.MaxValue - 32)
lacing_storage += 32;
Array.Resize (ref LacingVals, lacing_storage);
Array.Resize (ref GranuleVals, lacing_storage);
LacingStorage = lacing_storage;
}
return true;
}
bool Flush (OggPage og, bool force, int fill)
{
int maxvals = Math.Min (LacingFill, 0xFF);
if (0 == maxvals)
return false;
// construct a page
// decide how many segments to include
int vals = 0;
int acc = 0;
long granule_pos = -1;
// If this is the initial header case, the first page must only include
// the initial header packet
if (!BoS) // 'initial header page' case
{
granule_pos = 0;
for (vals = 0; vals < maxvals; vals++)
{
if ((LacingVals[vals] & 0xFF) < 0xFF)
{
vals++;
break;
}
}
}
else
{
int packets_done = 0;
int packet_just_done = 0;
for (vals = 0; vals < maxvals; vals++)
{
if (acc > fill && packet_just_done >= 4)
{
force = true;
break;
}
acc += LacingVals[vals] & 0xFF;
if ((LacingVals[vals] & 0xFF) < 0xFF)
{
granule_pos = GranuleVals[vals];
packet_just_done = ++packets_done;
}
else
packet_just_done = 0;
}
if (0xFF == vals)
force = true;
}
if (!force)
return false;
// construct the header in temp storage
Encoding.ASCII.GetBytes ("OggS", 0, 4, Header, 0);
// stream structure version
Header[4] = 0;
// continued packet flag?
Header[5] = 0;
if ((LacingVals[0] & 0x100) == 0)
Header[5] |= 1;
// first page flag?
if (!BoS)
Header[5] |= 2;
// last page flag?
if (EoS && LacingFill == vals)
Header[5] |= 4;
BoS = true;
// 64 bits of PCM position
LittleEndian.Pack (granule_pos, Header, 6);
// 32 bits of stream serial number
LittleEndian.Pack (SerialNo, Header, 14);
// 32 bits of page counter (we have both counter and page header because this
// val can roll over)
if (-1 == PageNo)
PageNo = 0;
LittleEndian.Pack (PageNo, Header, 18);
++PageNo;
int bytes = 0;
// segment table
Header[26] = (byte)vals;
for (int i = 0; i < vals; ++i)
bytes += Header[i+27] = (byte)LacingVals[i];
// set pointers in the ogg_page struct
og.Header = Header;
og.HeaderLength = HeaderFill = vals + 27;
og.Body = BodyData;
og.BodyStart = BodyReturned;
og.BodyLength = bytes;
// advance the lacing data and set the body_returned pointer
LacingFill -= vals;
Array.Copy (LacingVals, vals, LacingVals, 0, LacingFill);
Array.Copy (GranuleVals, vals, GranuleVals, 0, LacingFill);
BodyReturned += bytes;
// calculate the checksum
og.SetChecksum();
return true;
}
}
// struct ogg_page
// https://xiph.org/ogg/doc/libogg/ogg_page.html
internal class OggPage
{
public byte[] Header;
public int HeaderLength;
public byte[] Body;
public int BodyStart;
public int BodyLength;
public void SetChecksum ()
{
Header[22] = Header[23] = Header[24] = Header[25] = 0;
uint crc = Crc32Normal.UpdateCrc (0, Header, 0, HeaderLength);
crc = Crc32Normal.UpdateCrc (crc, Body, BodyStart, BodyLength);
LittleEndian.Pack (crc, Header, 22);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
// ReSharper disable InconsistentNaming
namespace IdmNet.Models
{
/// <summary>
/// SynchronizationRule - This resource defines synchronization behavior between FIM resources and resources in external systems.
/// </summary>
public class SynchronizationRule : IdmResource
{
/// <summary>
/// Parameterless CTOR
/// </summary>
public SynchronizationRule()
{
ObjectType = ForcedObjType = "SynchronizationRule";
}
/// <summary>
/// Build a SynchronizationRule object from a IdmResource object
/// </summary>
/// <param name="resource">base class</param>
public SynchronizationRule(IdmResource resource)
{
Attributes = resource.Attributes;
ObjectType = ForcedObjType = "SynchronizationRule";
if (resource.Creator == null)
return;
Creator = resource.Creator;
}
readonly string ForcedObjType;
/// <summary>
/// Object Type (can only be SynchronizationRule)
/// </summary>
[Required]
public override sealed string ObjectType
{
get { return GetAttrValue("ObjectType"); }
set
{
if (value != ForcedObjType)
throw new InvalidOperationException("Object Type of SynchronizationRule can only be 'SynchronizationRule'");
SetAttrValue("ObjectType", value);
}
}
/// <summary>
/// Create External System Resource - Indicates if an external system resource is created if the relationship criteria is not met.
/// </summary>
[Required]
public bool CreateConnectedSystemObject
{
get { return AttrToBool("CreateConnectedSystemObject"); }
set {
SetAttrValue("CreateConnectedSystemObject", value.ToString());
}
}
/// <summary>
/// Create FIM Resource - Indicates if a resource should be created in FIM if the relationship criteria is not met.
/// </summary>
[Required]
public bool CreateILMObject
{
get { return AttrToBool("CreateILMObject"); }
set {
SetAttrValue("CreateILMObject", value.ToString());
}
}
/// <summary>
/// Data Flow Direction - A Synchronization Rule can be defined as inbound (0), outbound (1) or bi-directional (2).
/// </summary>
[Required]
public int FlowType
{
get { return AttrToInteger("FlowType"); }
set {
SetAttrValue("FlowType", value.ToString());
}
}
/// <summary>
/// Dependency - A Synchronization Rule that must be applied to a resource before this Synchronization Rule can be applied.
/// </summary>
public SynchronizationRule Dependency
{
get { return GetAttr("Dependency", _theDependency); }
set
{
_theDependency = value;
SetAttrValue("Dependency", ObjectIdOrNull(value));
}
}
private SynchronizationRule _theDependency;
/// <summary>
/// Disconnect External System Resource - This option applies when this Synchronization Rule is removed from a resource in FIM.
/// </summary>
[Required]
public bool DisconnectConnectedSystemObject
{
get { return AttrToBool("DisconnectConnectedSystemObject"); }
set {
SetAttrValue("DisconnectConnectedSystemObject", value.ToString());
}
}
/// <summary>
/// Existence Test - Outbound attribute flows within a transformation marked as an existence tests for the Synchronization Rule.
/// </summary>
public List<string> ExistenceTest
{
get { return GetAttrValues("ExistenceTest"); }
set {
SetAttrValues("ExistenceTest", value);
}
}
/// <summary>
/// External System - The Management Agent identifying the external system this Synchronization Rule will operate on.
/// </summary>
[Required]
public string ConnectedSystem
{
get { return GetAttrValue("ConnectedSystem"); }
set {
SetAttrValue("ConnectedSystem", value);
}
}
/// <summary>
/// External System Resource Type - The resource type in the external system that this Synchronization Rule applies to.
/// </summary>
[Required]
public string ConnectedObjectType
{
get { return GetAttrValue("ConnectedObjectType"); }
set {
SetAttrValue("ConnectedObjectType", value);
}
}
/// <summary>
/// External System Scoping Filter - A filter representing the resources on the external system that the rule applies to.
/// </summary>
public string ConnectedSystemScope
{
get { return GetAttrValue("ConnectedSystemScope"); }
set {
SetAttrValue("ConnectedSystemScope", value);
}
}
/// <summary>
/// FIM Resource Type - The resource type in the FIM Metaverse that this Synchronization Rule applies to.
/// </summary>
[Required]
public string ILMObjectType
{
get { return GetAttrValue("ILMObjectType"); }
set {
SetAttrValue("ILMObjectType", value);
}
}
/// <summary>
/// Initial Flow - A series of outbound flows between FIM and external systems. These flows are only executed upon creation of a new resource.
/// </summary>
public List<string> InitialFlow
{
get { return GetAttrValues("InitialFlow"); }
set {
SetAttrValues("InitialFlow", value);
}
}
/// <summary>
/// Management Agent ID - Description: The Management Agent identifying the external system this Synchronization Rule will operate on.
/// </summary>
public ma_data ManagementAgentID
{
get { return GetAttr("ManagementAgentID", _theManagementAgentID); }
set
{
_theManagementAgentID = value;
SetAttrValue("ManagementAgentID", ObjectIdOrNull(value));
}
}
private ma_data _theManagementAgentID;
/// <summary>
/// Outbound Scope Filter Based - Determines how the synchronization rule is applied to existing resources.
/// </summary>
public bool? msidmOutboundIsFilterBased
{
get { return AttrToNullableBool("msidmOutboundIsFilterBased"); }
set {
SetAttrValue("msidmOutboundIsFilterBased", value.ToString());
}
}
/// <summary>
/// Outbound Scoping Filters - A filter representing the resources on the FIM metaverse that the rule applies to.
/// </summary>
public string msidmOutboundScopingFilters
{
get { return GetAttrValue("msidmOutboundScopingFilters"); }
set {
SetAttrValue("msidmOutboundScopingFilters", value);
}
}
/// <summary>
/// Persistent Flow - A series of attribute flow definitions.
/// </summary>
public List<string> PersistentFlow
{
get { return GetAttrValues("PersistentFlow"); }
set {
SetAttrValues("PersistentFlow", value);
}
}
/// <summary>
/// Precedence - A number indicating the Synchronization Rule's precedence relative to all other Synchronization Rules that apply to the same external system. A smaller number represents a higher precedence.
/// </summary>
public int? Precedence
{
get { return AttrToNullableInteger("Precedence"); }
set {
SetAttrValue("Precedence", value.ToString());
}
}
/// <summary>
/// Relationship Criteria - Defines how a relationship between a resource in FIM and a resource in an external system is detected.
/// </summary>
[Required]
public string RelationshipCriteria
{
get { return GetAttrValue("RelationshipCriteria"); }
set {
SetAttrValue("RelationshipCriteria", value);
}
}
/// <summary>
/// Synchronization Rule Parameters - These are parameters which require values to be provided from the workflow that adds the Synchronization Rule to a resource.
/// </summary>
public List<string> SynchronizationRuleParameters
{
get { return GetAttrValues("SynchronizationRuleParameters"); }
set {
SetAttrValues("SynchronizationRuleParameters", value);
}
}
}
}
| |
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(Animator))]
public class ThirdPersonCharacter : MonoBehaviour
{
[SerializeField] float m_MovingTurnSpeed = 360;
[SerializeField] float m_StationaryTurnSpeed = 180;
[SerializeField] float m_JumpPower = 12f;
[Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
[SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others
[SerializeField] float m_MoveSpeedMultiplier = 1f;
[SerializeField] float m_AnimSpeedMultiplier = 1f;
[SerializeField] float m_GroundCheckDistance = 0.1f;
Rigidbody m_Rigidbody;
Animator m_Animator;
bool m_IsGrounded;
float m_OrigGroundCheckDistance;
const float k_Half = 0.5f;
float m_TurnAmount;
float m_ForwardAmount;
Vector3 m_GroundNormal;
float m_CapsuleHeight;
Vector3 m_CapsuleCenter;
CapsuleCollider m_Capsule;
bool m_Crouching;
void Start()
{
m_Animator = GetComponent<Animator>();
m_Rigidbody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
m_CapsuleHeight = m_Capsule.height;
m_CapsuleCenter = m_Capsule.center;
m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
m_OrigGroundCheckDistance = m_GroundCheckDistance;
}
public void Move(float moveMagnitude, float moveForwardAmount, float turnAmount, bool crouch, bool jump)
{
m_ForwardAmount = moveForwardAmount;
m_TurnAmount = turnAmount;
// convert the world relative moveInput vector into a local-relative
// turn amount and forward amount required to head in the desired
// direction.
//if (move.magnitude > 1f) move.Normalize();
//move = transform.InverseTransformDirection(move);
CheckGroundStatus();
//move = Vector3.ProjectOnPlane(move, m_GroundNormal);
//Debug.DrawRay (transform.position, move, Color.red);
//m_TurnAmount = Mathf.Atan2(move.x, move.z);
//m_ForwardAmount = move.z;
//Vector3 characterForward = Vector3.ProjectOnPlane(transform.forward, m_GroundNormal);
//Vector3 characterRight = Vector3.Cross (m_GroundNormal, characterForward);
//Vector3 moveRightProj = Vector3.ProjectOnPlane(move.normalized, characterForward);
//Vector3 moveForwardProj = Vector3.ProjectOnPlane(move.normalized, characterRight);
//Debug.DrawRay (transform.position, move, Color.red);
//Debug.DrawRay (transform.position, moveRightProj, Color.yellow);
//Debug.DrawRay (transform.position, moveForwardProj, Color.green);
//Debug.DrawRay (transform.position, characterForward, Color.cyan);
//Debug.DrawRay (transform.position, characterRight, Color.cyan);
//Debug.DrawRay (transform.position, m_GroundNormal, Color.cyan);
//atan2(norm(cross(a,b)), dot(a,b))
//m_TurnAmount = Mathf.Atan2(moveRight.magnitude, moveForward.magnitude);
// float angleBetweenMoveAndForward = Vector3.Angle(characterForward, move);
//m_ForwardAmount = Vector3.Dot (move, characterForward.normalized);
//m_TurnAmount = Mathf.Atan2(characterRight, characterForward);
//m_TurnAmount = Mathf.Atan2 (Vector3.Cross (moveRightProj, moveForwardProj).magnitude, Vector3.Dot (moveRightProj, moveForwardProj));
//m_TurnAmount = 45; //Vector3.Angle(characterForward, move);
//string xpto = Time.time.ToString("R");
//Debug.Log (xpto + " >>>>>>>>>>>>>>>>>> " + m_TurnAmount);
//m_TurnAmount = 2 * Mathf.Atan( (moveRightProj*(moveForwardProj.magnitude) - moveForwardProj*(moveRightProj.magnitude)).magnitude / (moveRightProj * (moveForwardProj.magnitude) + moveForwardProj*(moveRightProj.magnitude )).magnitude);
ApplyExtraTurnRotation();
// control and velocity handling is different when grounded and airborne:
if (m_IsGrounded)
{
// HandleGroundedMovement(crouch, jump);
}
else
{
// HandleAirborneMovement();
}
//ScaleCapsuleForCrouching(crouch);
//PreventStandingInLowHeadroom();
// send input and other state parameters to the animator
UpdateAnimator(moveMagnitude);
}
void ScaleCapsuleForCrouching(bool crouch)
{
/*if (m_IsGrounded && crouch)
{
if (m_Crouching) return;
m_Capsule.height = m_Capsule.height / 2f;
m_Capsule.center = m_Capsule.center / 2f;
m_Crouching = true;
}
else
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
return;
}
m_Capsule.height = m_CapsuleHeight;
m_Capsule.center = m_CapsuleCenter;
m_Crouching = false;
}*/
}
void PreventStandingInLowHeadroom()
{
// prevent standing up in crouch-only zones
//if (!m_Crouching)
//{
// Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
// float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
// if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore))
// {
// m_Crouching = true;
// }
//}
}
void UpdateAnimator(float moveMagnitude)
{
// update the animator parameters
m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
m_Animator.SetBool("Crouch", m_Crouching);
m_Animator.SetBool("OnGround", m_IsGrounded);
if (!m_IsGrounded)
{
//m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
}
// calculate which leg is behind, so as to leave that leg trailing in the jump animation
// (This code is reliant on the specific run cycle offset in our animations,
// and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
float runCycle =
Mathf.Repeat(
m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);
float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
if (m_IsGrounded)
{
//m_Animator.SetFloat("JumpLeg", jumpLeg);
}
// the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
// which affects the movement speed because of the root motion.
if (m_IsGrounded && moveMagnitude > 0)
{
m_Animator.speed = m_AnimSpeedMultiplier;
}
else
{
// don't use that while airborne
m_Animator.speed = 1;
}
}
void HandleAirborneMovement()
{
// apply extra gravity from multiplier:
//Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
//m_Rigidbody.AddForce(extraGravityForce);
//m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
}
void HandleGroundedMovement(bool crouch, bool jump)
{
// check whether conditions are right to allow a jump:
if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
{
// jump!
//m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
m_IsGrounded = false;
m_Animator.applyRootMotion = false;
m_GroundCheckDistance = 0.1f;
}
}
void ApplyExtraTurnRotation()
{
// help the character turn faster (this is in addition to root rotation in the animation)
float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
//transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
GameObject planet = GameObject.Find ("/1Orbit/Sphere");
Vector3 gravity = planet == null ? new Vector3(0,-1,0) :(planet.transform. position - transform.position).normalized;
Vector3 rotation = -gravity * m_TurnAmount * Time.deltaTime; //* m_TurnAmount * turnSpeed * Time.deltaTime;
transform.Rotate(rotation);
}
public void OnAnimatorMove()
{
// we implement this function to override the default root motion.
// this allows us to modify the positional speed before it's applied.
if (m_IsGrounded && Time.deltaTime > 0)
{
Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;
// we preserve the existing y part of the current velocity.
//v.y = m_Rigidbody.velocity.y;
m_Rigidbody.velocity = v;
}
}
void CheckGroundStatus()
{
GameObject planet = GameObject.Find ("/1Orbit/Sphere");
Vector3 gravity = planet == null ? new Vector3(0, -1, 0):(planet.transform. position - transform.position).normalized;
RaycastHit hitInfo;
#if UNITY_EDITOR
// helper to visualise the ground check ray in the scene view
Debug.DrawLine(transform.position + (-gravity * 0.1f), transform.position + (-gravity * 0.1f) + (gravity * m_GroundCheckDistance));
#endif
// 0.1f is a small offset to start the ray from inside the character
// it is also good to note that the transform position in the sample assets is at the base of the character
if (Physics.Raycast(transform.position + (-gravity * 0.1f), gravity, out hitInfo, m_GroundCheckDistance))
{
m_GroundNormal = hitInfo.normal;
m_IsGrounded = true;
m_Animator.applyRootMotion = true;
}
else
{
m_IsGrounded = false;
m_GroundNormal = -gravity;
m_Animator.applyRootMotion = false;
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace BuildIt.CognitiveServices
{
public partial class SpellCheckAPIV5 : Microsoft.Rest.ServiceClient<SpellCheckAPIV5>, ISpellCheckAPIV5
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SpellCheckAPIV5 class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SpellCheckAPIV5(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SpellCheckAPIV5 class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SpellCheckAPIV5(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SpellCheckAPIV5 class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SpellCheckAPIV5(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SpellCheckAPIV5 class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SpellCheckAPIV5(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new System.Uri("https://api.cognitive.microsoft.com/bing/v5.0/spellcheck");
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <param name='mode'>
/// Mode of spellcheck:
/// <ul><li>Proof - Meant to provide Office Word like spelling
/// corrections. It can correct long queries, provide casing corrections and
/// suppresses aggressive corrections.</li>
/// <li>Spell - Meant to provide Search engine like spelling
/// corrections. It will correct small queries(up to length 9 tokens) without
/// any casing changes and will be more optimized (perf and relevance)
/// towards search like queries.</li></ul>
/// . Possible values include: 'spell', 'proof'
/// </param>
/// <param name='mkt'>
/// For proof mode, only support en-us, es-es, pt-br,
/// For spell mode, support all language codes. Possible values include:
/// 'en-us', 'es-es', 'pt-br'
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> SpellCheckWithHttpMessagesAsync(string mode = default(string), string mkt = default(string), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("mode", mode);
tracingParameters.Add("mkt", mkt);
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "SpellCheck", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (mode != null)
{
_queryParameters.Add(string.Format("mode={0}", System.Uri.EscapeDataString(mode)));
}
if (mkt != null)
{
_queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(mkt)));
}
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
if (customHeaders != null)
{
foreach (var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 429)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='mode'>
/// Mode of spellcheck:
/// <ul><li>Proof - Meant to provide Office Word like spelling
/// corrections. It can correct long queries, provide casing corrections and
/// suppresses aggressive corrections.</li>
/// <li>Spell - Meant to provide Search engine like spelling
/// corrections. It will correct small queries(up to length 9 tokens) without
/// any casing changes and will be more optimized (perf and relevance)
/// towards search like queries.</li></ul>
/// . Possible values include: 'spell', 'proof'
/// </param>
/// <param name='preContextText'>
/// A string that gives context to the text string. For example, the text
/// string petal is valid; however, if you set preContextText to bike, the
/// context changes and the text string becomes not valid. In this case, the
/// API will suggest that you change petal to pedal (as in bike pedal).
/// </param>
/// <param name='postContextText'>
/// A string that gives context to the text string. For example, the text
/// string read is valid; however, if you set postContextText to carpet, the
/// context changes and the text string becomes not valid. In this case, the
/// API will suggest that you change read to red (as in red carpet).
/// </param>
/// <param name='mkt'>
/// For proof mode, only support en-us, es-es, pt-br,
/// For spell mode, support all language codes. Possible values include:
/// 'en-us', 'es-es', 'pt-br'
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> SpellCheckWithHttpMessagesAsync(string text, string mode = default(string), string preContextText = default(string), string postContextText = default(string), string mkt = default(string), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("mode", mode);
tracingParameters.Add("text", text);
tracingParameters.Add("preContextText", preContextText);
tracingParameters.Add("postContextText", postContextText);
tracingParameters.Add("mkt", mkt);
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "SpellCheck", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (mode != null)
{
_queryParameters.Add(string.Format("mode={0}", System.Uri.EscapeDataString(mode)));
}
if (text != null)
{
_queryParameters.Add(string.Format("text={0}", System.Uri.EscapeDataString(text)));
}
if (preContextText != null)
{
_queryParameters.Add(string.Format("preContextText={0}", System.Uri.EscapeDataString(preContextText)));
}
if (postContextText != null)
{
_queryParameters.Add(string.Format("postContextText={0}", System.Uri.EscapeDataString(postContextText)));
}
if (mkt != null)
{
_queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(mkt)));
}
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
if (customHeaders != null)
{
foreach (var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 429)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using Xunit;
namespace System.Globalization.CalendarsTests
{
// System.Globalization.ThaiBuddhistCalendar.GetWeekOfYear(DateTime,CalendarWeekRule,DayOfWeek)
public class ThaiBuddhistCalendarGetWeekOfYear
{
private readonly int[] _DAYS_PER_MONTHS_IN_LEAP_YEAR = new int[13]
{
0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
private readonly int[] _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR = new int[13]
{
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
#region Positive Tests
// PosTest1: Verify the DateTime is a random Date
[Fact]
public void PosTest1()
{
System.Globalization.Calendar tbc = new ThaiBuddhistCalendar();
Random rand = new Random(-55);
int year = rand.Next(tbc.MinSupportedDateTime.Year, tbc.MaxSupportedDateTime.Year);
int month = rand.Next(1, 12);
int day;
if (IsLeapYear(year))
{
day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1);
}
else
{
day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1);
}
DateTime dt = new DateTime(year, month, day);
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 3; j++)
{
int actualWeek = getWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i);
int resultWeek = tbc.GetWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i);
Assert.Equal(actualWeek, resultWeek);
}
}
}
// PosTest2: Verify the DateTime is ThaiBuddhistCalendar MaxSupportDateTime
[Fact]
public void PosTest2()
{
System.Globalization.Calendar tbc = new ThaiBuddhistCalendar();
DateTime dt = tbc.MaxSupportedDateTime;
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 3; j++)
{
int actualWeek = getWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i);
int resultWeek = tbc.GetWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i);
Assert.Equal(actualWeek, resultWeek);
}
}
}
// PosTest3: Verify the DateTime is ThaiBuddhistCalendar MinSupportedDateTime
[Fact]
public void PosTest3()
{
System.Globalization.Calendar tbc = new ThaiBuddhistCalendar();
DateTime dt = tbc.MinSupportedDateTime;
dt = dt.AddYears(543);
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 3; j++)
{
int actualWeek = getWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i);
int resultWeek = tbc.GetWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i);
Assert.Equal(actualWeek, resultWeek);
}
}
}
// PosTest4: Verify the DateTime is the last day of the year
[Fact]
public void PosTest4()
{
System.Globalization.Calendar tbc = new ThaiBuddhistCalendar();
System.Globalization.Calendar gc = new GregorianCalendar();
Random rand = new Random(-55);
int year = rand.Next(tbc.MinSupportedDateTime.Year, tbc.MaxSupportedDateTime.Year);
int month = 12;
int day = 31;
int actualWeek = 53;
DateTime dt = new DateTime(year, month, day);
CultureInfo myCI = new CultureInfo("th-TH");
int resultWeek = tbc.GetWeekOfYear(dt, myCI.DateTimeFormat.CalendarWeekRule, myCI.DateTimeFormat.FirstDayOfWeek);
Assert.Equal(actualWeek, resultWeek);
}
#endregion
#region Negative Tests
// NegTest1: firstDayOfWeek is outside the range supported by the calendar
[Fact]
public void NegTest1()
{
System.Globalization.Calendar tbc = new ThaiBuddhistCalendar();
Random rand = new Random(-55);
int year = rand.Next(tbc.MinSupportedDateTime.Year, tbc.MaxSupportedDateTime.Year);
int month = rand.Next(1, 12);
int day;
if (IsLeapYear(year))
{
day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1);
}
else
{
day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1);
}
DateTime dt = new DateTime(year, month, day);
CultureInfo myCI = new CultureInfo("th-TH");
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
tbc.GetWeekOfYear(dt, myCI.DateTimeFormat.CalendarWeekRule, (DayOfWeek)7);
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
tbc.GetWeekOfYear(dt, myCI.DateTimeFormat.CalendarWeekRule, (DayOfWeek)(-1));
});
}
// NegTest2: CalendarWeekRule is outside the range supported by the calendar
[Fact]
public void NegTest2()
{
System.Globalization.Calendar tbc = new ThaiBuddhistCalendar();
Random rand = new Random(-55);
int year = rand.Next(tbc.MinSupportedDateTime.Year, tbc.MaxSupportedDateTime.Year);
int month = rand.Next(1, 12);
int day;
if (IsLeapYear(year))
{
day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1);
}
else
{
day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1);
}
DateTime dt = new DateTime(year, month, day);
CultureInfo myCI = new CultureInfo("th-TH");
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
tbc.GetWeekOfYear(dt, (CalendarWeekRule)3, myCI.DateTimeFormat.FirstDayOfWeek);
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
tbc.GetWeekOfYear(dt, (CalendarWeekRule)(-1), myCI.DateTimeFormat.FirstDayOfWeek);
});
}
#endregion
#region Helper Methods
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
{
System.Globalization.Calendar gc = new GregorianCalendar();
int dayOfYear = gc.GetDayOfYear(time) - 1;
// Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)gc.GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
//BCLDebug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
internal int GetWeekOfYearFullDays(DateTime time, CalendarWeekRule rule, int firstDayOfWeek, int fullDays)
{
int dayForJan1;
int offset;
int day;
System.Globalization.Calendar gc = new GregorianCalendar();
int dayOfYear = gc.GetDayOfYear(time) - 1;
// Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)gc.GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Substract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
offset -= 7;
}
// Calculate the day of year for specified time by taking offset into account.
day = dayOfYear - offset;
if (day >= 0)
{
// If the day of year value is greater than zero, get the week of year.
return (day / 7 + 1);
}
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), rule, firstDayOfWeek, fullDays));
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
private int getWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
{
throw new ArgumentOutOfRangeException();
}
switch (rule)
{
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, rule, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, rule, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException();
}
private bool IsLeapYear(int year)
{
return ((year % 4) == 0) && !(((year % 100) == 0) || ((year % 400) == 0));
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation 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 HOLDER 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.Web;
using WebsitePanel.EnterpriseServer;
using System.Collections.Generic;
using WebsitePanel.Portal.UserControls;
namespace WebsitePanel.Portal
{
public partial class DomainsAddDomain : WebsitePanelModuleBase
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
// bind controls
BindControls();
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
if (Utils.CheckQouta(Quotas.WEB_ENABLEHOSTNAMESUPPORT, cntx))
{
lblHostName.Visible = txtHostName.Visible = true;
UserSettings settings = ES.Services.Users.GetUserSettings(PanelSecurity.LoggedUserId, UserSettings.WEB_POLICY);
txtHostName.Text = String.IsNullOrEmpty(settings["HostName"]) ? "" : settings["HostName"];
}
else
{
lblHostName.Visible = txtHostName.Visible = false;
txtHostName.Text = "";
}
DomainType type = GetDomainType(Request["DomainType"]);
if ((PanelSecurity.LoggedUser.Role == UserRole.User) & (type != DomainType.SubDomain))
{
if (cntx.Groups.ContainsKey(ResourceGroups.Dns))
{
if (!PackagesHelper.CheckGroupQuotaEnabled(PanelSecurity.PackageId, ResourceGroups.Dns, Quotas.DNS_EDITOR))
this.DisableControls = true;
}
}
}
catch (Exception ex)
{
ShowErrorMessage("DOMAIN_GET_DOMAIN", ex);
}
}
private void BindControls()
{
// get domain type
DomainType type = GetDomainType(Request["DomainType"]);
// enable domain/sub-domain fields
if (type == DomainType.Domain || type == DomainType.DomainPointer)
{
// domains
DomainName.IsSubDomain = false;
}
else
{
// sub-domains
DomainName.IsSubDomain = true;
// fill sub-domains
if (!IsPostBack)
{
if (type == DomainType.SubDomain)
BindUserDomains();
else
BindResellerDomains();
}
}
// load package context
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
if ((type == DomainType.DomainPointer || (type == DomainType.Domain)) && !IsPostBack)
{
// bind web sites
WebSitesList.DataSource = ES.Services.WebServers.GetWebSites(PanelSecurity.PackageId, false);
WebSitesList.DataBind();
}
if ((type == DomainType.DomainPointer || (type == DomainType.Domain)) && !IsPostBack)
{
// bind mail domains
MailDomainsList.DataSource = ES.Services.MailServers.GetMailDomains(PanelSecurity.PackageId, false);
MailDomainsList.DataBind();
}
// create web site option
CreateWebSitePanel.Visible = (type == DomainType.Domain || type == DomainType.SubDomain)
&& cntx.Groups.ContainsKey(ResourceGroups.Web);
if (PointWebSite.Checked)
{
CreateWebSite.Checked = false;
CreateWebSite.Enabled = false;
}
else
{
CreateWebSite.Enabled = true;
CreateWebSite.Checked &= CreateWebSitePanel.Visible;
}
// point Web site
PointWebSitePanel.Visible = (type == DomainType.DomainPointer || (type == DomainType.Domain))
&& cntx.Groups.ContainsKey(ResourceGroups.Web) && WebSitesList.Items.Count > 0;
WebSitesList.Enabled = PointWebSite.Checked;
// point mail domain
PointMailDomainPanel.Visible = (type == DomainType.DomainPointer || (type == DomainType.Domain))
&& cntx.Groups.ContainsKey(ResourceGroups.Mail) && MailDomainsList.Items.Count > 0;
MailDomainsList.Enabled = PointMailDomain.Checked;
// DNS option
EnableDnsPanel.Visible = cntx.Groups.ContainsKey(ResourceGroups.Dns);
EnableDns.Checked &= EnableDnsPanel.Visible;
// instant alias
// check if instant alias was setup
bool instantAliasAllowed = false;
PackageSettings settings = ES.Services.Packages.GetPackageSettings(PanelSecurity.PackageId, PackageSettings.INSTANT_ALIAS);
instantAliasAllowed = (settings != null && !String.IsNullOrEmpty(settings["InstantAlias"]));
InstantAliasPanel.Visible = instantAliasAllowed && (type != DomainType.DomainPointer) /*&& EnableDnsPanel.Visible*/;
CreateInstantAlias.Checked &= InstantAliasPanel.Visible;
// allow sub-domains
AllowSubDomainsPanel.Visible = (type == DomainType.Domain) && PanelSecurity.EffectiveUser.Role != UserRole.User;
if (IsPostBack)
{
CheckForCorrectIdnDomainUsage(DomainName.Text);
}
}
private DomainType GetDomainType(string typeName)
{
DomainType type = DomainType.Domain;
if (!String.IsNullOrEmpty(typeName))
type = (DomainType)Enum.Parse(typeof(DomainType), typeName, true);
return type;
}
private void BindUserDomains()
{
DomainInfo[] allDomains = ES.Services.Servers.GetMyDomains(PanelSecurity.PackageId);
// filter domains
List<DomainInfo> domains = new List<DomainInfo>();
foreach (DomainInfo domain in allDomains)
if (!domain.IsDomainPointer && !domain.IsSubDomain && !domain.IsInstantAlias)
domains.Add(domain);
DomainName.DataSource = domains;
DomainName.DataBind();
}
private void BindResellerDomains()
{
DomainName.DataSource = ES.Services.Servers.GetResellerDomains(PanelSecurity.PackageId);
DomainName.DataBind();
}
private void AddDomain()
{
if (!Page.IsValid)
return;
// get domain type
DomainType type = GetDomainType(Request["DomainType"]);
// get domain name
var domainName = DomainName.Text;
int pointWebSiteId = 0;
int pointMailDomainId = 0;
// load package context
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
if (type == DomainType.DomainPointer || (type == DomainType.Domain))
{
if (PointWebSite.Checked && WebSitesList.Items.Count > 0)
pointWebSiteId = Utils.ParseInt(WebSitesList.SelectedValue, 0);
}
if (type == DomainType.DomainPointer || (type == DomainType.Domain))
{
if (PointMailDomain.Checked && MailDomainsList.Items.Count > 0)
pointMailDomainId = Utils.ParseInt(MailDomainsList.SelectedValue, 0);
}
// add domain
int domainId = 0;
try
{
domainId = ES.Services.Servers.AddDomainWithProvisioning(PanelSecurity.PackageId,
domainName.ToLower(), type, CreateWebSite.Checked, pointWebSiteId, pointMailDomainId,
EnableDns.Checked, CreateInstantAlias.Checked, AllowSubDomains.Checked, (PointWebSite.Checked && WebSitesList.Items.Count > 0) ? string.Empty : txtHostName.Text.ToLower());
if (domainId < 0)
{
ShowResultMessage(domainId);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("DOMAIN_ADD_DOMAIN", ex);
return;
}
// put created domain to the cookie
HttpCookie domainCookie = new HttpCookie("CreatedDomainId", domainId.ToString());
Response.Cookies.Add(domainCookie);
// return
RedirectBack();
}
private void RedirectBack()
{
RedirectSpaceHomePage();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
// return
RedirectBack();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (CheckForCorrectIdnDomainUsage(DomainName.Text))
{
AddDomain();
}
}
private bool CheckForCorrectIdnDomainUsage(string domainName)
{
// If the choosen domain is a idn domain, don't allow to create mail
if (Utils.IsIdnDomain(domainName) && PointMailDomain.Checked)
{
ShowErrorMessage("IDNDOMAIN_NO_MAIL");
return false;
}
return true;
}
}
}
| |
// Copyright 2016 Google Inc. 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.
using UnityEngine;
using UnityEngine.VR;
using System.Collections;
/// Standard implementation for a mathematical model to make the virtual controller approximate the
/// physical location of the Daydream controller.
public class GvrArmModel : GvrBaseArmModel{
/// Position of the elbow joint relative to the head before the arm model is applied.
public Vector3 elbowRestPosition = DEFAULT_ELBOW_REST_POSITION;
/// Position of the wrist joint relative to the elbow before the arm model is applied.
public Vector3 wristRestPosition = DEFAULT_WRIST_REST_POSITION;
/// Position of the controller joint relative to the wrist before the arm model is applied.
public Vector3 controllerRestPosition = DEFAULT_CONTROLLER_REST_POSITION;
/// Offset applied to the elbow position as the controller is rotated upwards.
public Vector3 armExtensionOffset = DEFAULT_ARM_EXTENSION_OFFSET;
/// Ratio of the controller's rotation to apply to the rotation of the elbow.
/// The remaining rotation is applied to the wrist's rotation.
[Range(0.0f, 1.0f)]
public float elbowBendRatio = DEFAULT_ELBOW_BEND_RATIO;
/// Offset in front of the controller to determine what position to use when determing if the
/// controller should fade. This is useful when objects are attached to the controller.
[Range(0.0f, 0.4f)]
public float fadeControllerOffset = 0.0f;
/// Controller distance from the front/back of the head after which the controller disappears (meters).
[Range(0.0f, 0.4f)]
public float fadeDistanceFromHeadForward = 0.25f;
/// Controller distance from the left/right of the head after which the controller disappears (meters).
[Range(0.0f, 0.4f)]
public float fadeDistanceFromHeadSide = 0.15f;
/// Controller distance from face after which the tooltips appear (meters).
[Range(0.4f, 0.6f)]
public float tooltipMinDistanceFromFace = 0.45f;
/// When the angle (degrees) between the controller and the head is larger than
/// this value, the tooltips disappear.
/// If the value is 180, then the tooltips are always shown.
/// If the value is 90, the tooltips are only shown when they are facing the camera.
[Range(0, 180)]
public int tooltipMaxAngleFromCamera = 80;
/// If true, the root of the pose is locked to the local position of the player's neck.
public bool isLockedToNeck = false;
/// Represents the controller's position relative to the user's head.
public override Vector3 ControllerPositionFromHead {
get {
return controllerPosition;
}
}
/// Represent the controller's rotation relative to the user's head.
public override Quaternion ControllerRotationFromHead {
get {
return controllerRotation;
}
}
/// The suggested rendering alpha value of the controller.
/// This is to prevent the controller from intersecting the face.
/// The range is always 0 - 1.
public override float PreferredAlpha {
get {
return preferredAlpha;
}
}
/// The suggested rendering alpha value of the controller tooltips.
/// This is to only display the tooltips when the player is looking
/// at the controller, and also to prevent the tooltips from intersecting the
/// player's face.
public override float TooltipAlphaValue {
get {
return tooltipAlphaValue;
}
}
/// Represent the neck's position relative to the user's head.
/// If isLockedToNeck is true, this will be the InputTracking position of the Head node modified
/// by an inverse neck model to approximate the neck position.
/// Otherwise, it is always zero.
public Vector3 NeckPosition {
get {
return neckPosition;
}
}
/// Represent the shoulder's position relative to the user's head.
/// This is not actually used as part of the arm model calculations, and exists for debugging.
public Vector3 ShoulderPosition {
get {
Vector3 shoulderPosition = neckPosition + torsoRotation * Vector3.Scale(SHOULDER_POSITION, handedMultiplier);
return shoulderPosition;
}
}
/// Represent the shoulder's rotation relative to the user's head.
/// This is not actually used as part of the arm model calculations, and exists for debugging.
public Quaternion ShoulderRotation {
get {
return torsoRotation;
}
}
/// Represent the elbow's position relative to the user's head.
public Vector3 ElbowPosition {
get {
return elbowPosition;
}
}
/// Represent the elbow's rotation relative to the user's head.
public Quaternion ElbowRotation {
get {
return elbowRotation;
}
}
/// Represent the wrist's position relative to the user's head.
public Vector3 WristPosition {
get {
return wristPosition;
}
}
/// Represent the wrist's rotation relative to the user's head.
public Quaternion WristRotation {
get {
return wristRotation;
}
}
protected Vector3 neckPosition;
protected Vector3 elbowPosition;
protected Quaternion elbowRotation;
protected Vector3 wristPosition;
protected Quaternion wristRotation;
protected Vector3 controllerPosition;
protected Quaternion controllerRotation;
protected float preferredAlpha;
protected float tooltipAlphaValue;
/// Multiplier for handedness such that 1 = Right, 0 = Center, -1 = left.
protected Vector3 handedMultiplier;
/// Forward direction of user's torso.
protected Vector3 torsoDirection;
/// Orientation of the user's torso.
protected Quaternion torsoRotation;
// Default values for tuning variables.
public static readonly Vector3 DEFAULT_ELBOW_REST_POSITION = new Vector3(0.195f, -0.5f, 0.005f);
public static readonly Vector3 DEFAULT_WRIST_REST_POSITION = new Vector3(0.0f, 0.0f, 0.25f);
public static readonly Vector3 DEFAULT_CONTROLLER_REST_POSITION = new Vector3(0.0f, 0.0f, 0.05f);
public static readonly Vector3 DEFAULT_ARM_EXTENSION_OFFSET = new Vector3(-0.13f, 0.14f, 0.08f);
public const float DEFAULT_ELBOW_BEND_RATIO = 0.6f;
/// Increases elbow bending as the controller moves up (unitless).
protected const float EXTENSION_WEIGHT = 0.4f;
/// Rest position for shoulder joint.
protected static readonly Vector3 SHOULDER_POSITION = new Vector3(0.17f, -0.2f, -0.03f);
/// Neck offset used to apply the inverse neck model when locked to the head.
protected static readonly Vector3 NECK_OFFSET = new Vector3(0.0f, 0.075f, 0.08f);
/// Amount of normalized alpha transparency to change per second.
protected const float DELTA_ALPHA = 4.0f;
/// Angle ranges the for arm extension offset to start and end (degrees).
protected const float MIN_EXTENSION_ANGLE = 7.0f;
protected const float MAX_EXTENSION_ANGLE = 60.0f;
protected virtual void OnEnable() {
// Register the controller update listener.
GvrControllerInput.OnControllerInputUpdated += OnControllerInputUpdated;
// Update immediately to avoid a frame delay before the arm model is applied.
OnControllerInputUpdated();
}
protected virtual void OnDisable() {
GvrControllerInput.OnControllerInputUpdated -= OnControllerInputUpdated;
}
protected virtual void OnControllerInputUpdated() {
UpdateHandedness();
UpdateTorsoDirection();
UpdateNeckPosition();
ApplyArmModel();
UpdateTransparency();
}
protected virtual void UpdateHandedness() {
// Update user handedness if the setting has changed
GvrSettings.UserPrefsHandedness handedness = GvrSettings.Handedness;
// Determine handedness multiplier.
handedMultiplier.Set(0, 1, 1);
if (handedness == GvrSettings.UserPrefsHandedness.Right) {
handedMultiplier.x = 1.0f;
} else if (handedness == GvrSettings.UserPrefsHandedness.Left) {
handedMultiplier.x = -1.0f;
}
}
protected virtual void UpdateTorsoDirection() {
// Determine the gaze direction horizontally.
Vector3 gazeDirection = GetHeadForward();
gazeDirection.y = 0.0f;
gazeDirection.Normalize();
// Use the gaze direction to update the forward direction.
float angularVelocity = GvrControllerInput.Gyro.magnitude;
float gazeFilterStrength = Mathf.Clamp((angularVelocity - 0.2f) / 45.0f, 0.0f, 0.1f);
torsoDirection = Vector3.Slerp(torsoDirection, gazeDirection, gazeFilterStrength);
// Calculate the torso rotation.
torsoRotation = Quaternion.FromToRotation(Vector3.forward, torsoDirection);
}
protected virtual void UpdateNeckPosition() {
if (isLockedToNeck) {
// Returns the center of the eyes.
// However, we actually want to lock to the center of the head.
neckPosition = GetHeadPosition();
// Find the approximate neck position by Applying an inverse neck model.
// This transforms the head position to the center of the head and also accounts
// for the head's rotation so that the motion feels more natural.
neckPosition = ApplyInverseNeckModel(neckPosition);
} else {
neckPosition = Vector3.zero;
}
}
protected virtual void ApplyArmModel() {
// Set the starting positions of the joints before they are transformed by the arm model.
SetUntransformedJointPositions();
// Get the controller's orientation.
Quaternion controllerOrientation;
Quaternion xyRotation;
float xAngle;
GetControllerRotation(out controllerOrientation, out xyRotation, out xAngle);
// Offset the elbow by the extension offset.
float extensionRatio = CalculateExtensionRatio(xAngle);
ApplyExtensionOffset(extensionRatio);
// Calculate the lerp rotation, which is used to control how much the rotation of the
// controller impacts each joint.
Quaternion lerpRotation = CalculateLerpRotation(xyRotation, extensionRatio);
CalculateFinalJointRotations(controllerOrientation, xyRotation, lerpRotation);
ApplyRotationToJoints();
}
/// Set the starting positions of the joints before they are transformed by the arm model.
protected virtual void SetUntransformedJointPositions() {
elbowPosition = Vector3.Scale(elbowRestPosition, handedMultiplier);
wristPosition = Vector3.Scale(wristRestPosition, handedMultiplier);
controllerPosition = Vector3.Scale(controllerRestPosition, handedMultiplier);
}
/// Calculate the extension ratio based on the angle of the controller along the x axis.
protected virtual float CalculateExtensionRatio(float xAngle) {
float normalizedAngle = (xAngle - MIN_EXTENSION_ANGLE) / (MAX_EXTENSION_ANGLE - MIN_EXTENSION_ANGLE);
float extensionRatio = Mathf.Clamp(normalizedAngle, 0.0f, 1.0f);
return extensionRatio;
}
/// Offset the elbow by the extension offset.
protected virtual void ApplyExtensionOffset(float extensionRatio) {
Vector3 extensionOffset = Vector3.Scale(armExtensionOffset, handedMultiplier);
elbowPosition += extensionOffset * extensionRatio;
}
/// Calculate the lerp rotation, which is used to control how much the rotation of the
/// controller impacts each joint.
protected virtual Quaternion CalculateLerpRotation(Quaternion xyRotation, float extensionRatio) {
float totalAngle = Quaternion.Angle(xyRotation, Quaternion.identity);
float lerpSuppresion = 1.0f - Mathf.Pow(totalAngle / 180.0f, 6.0f);
float inverseElbowBendRatio = 1.0f - elbowBendRatio;
float lerpValue = inverseElbowBendRatio + elbowBendRatio * extensionRatio * EXTENSION_WEIGHT;
lerpValue *= lerpSuppresion;
return Quaternion.Lerp(Quaternion.identity, xyRotation, lerpValue);
}
/// Determine the final joint rotations relative to the head.
protected virtual void CalculateFinalJointRotations(Quaternion controllerOrientation, Quaternion xyRotation, Quaternion lerpRotation) {
elbowRotation = torsoRotation * Quaternion.Inverse(lerpRotation) * xyRotation;
wristRotation = elbowRotation * lerpRotation;
controllerRotation = torsoRotation * controllerOrientation;
}
/// Apply the joint rotations to the positions of the joints to determine the final pose.
protected virtual void ApplyRotationToJoints() {
elbowPosition = neckPosition + torsoRotation * elbowPosition;
wristPosition = elbowPosition + elbowRotation * wristPosition;
controllerPosition = wristPosition + wristRotation * controllerPosition;
}
/// Transform the head position into an approximate neck position.
protected virtual Vector3 ApplyInverseNeckModel(Vector3 headPosition) {
Quaternion headRotation = GetHeadRotation();
Vector3 rotatedNeckOffset =
headRotation * NECK_OFFSET - NECK_OFFSET.y * Vector3.up;
headPosition -= rotatedNeckOffset;
return headPosition;
}
/// Controls the transparency of the controller to prevent the controller from clipping through
/// the user's head. Also, controls the transparency of the tooltips so they are only visible
/// when the controller is held up.
protected virtual void UpdateTransparency() {
Vector3 controllerForward = controllerRotation * Vector3.forward;
Vector3 offsetControllerPosition = controllerPosition + (controllerForward * fadeControllerOffset);
Vector3 controllerRelativeToHead = offsetControllerPosition - neckPosition;
Vector3 headForward = GetHeadForward();
float distanceToHeadForward = Vector3.Scale(controllerRelativeToHead, headForward).magnitude;
Vector3 headRight = Vector3.Cross(headForward, Vector3.up);
float distanceToHeadSide = Vector3.Scale(controllerRelativeToHead, headRight).magnitude;
float distanceToHeadUp = Mathf.Abs(controllerRelativeToHead.y);
bool shouldFadeController = distanceToHeadForward < fadeDistanceFromHeadForward
&& distanceToHeadUp < fadeDistanceFromHeadForward
&& distanceToHeadSide < fadeDistanceFromHeadSide;
// Determine how vertical the controller is pointing.
float animationDelta = DELTA_ALPHA * Time.unscaledDeltaTime;
if (shouldFadeController) {
preferredAlpha = Mathf.Max(0.0f, preferredAlpha - animationDelta);
} else {
preferredAlpha = Mathf.Min(1.0f, preferredAlpha + animationDelta);
}
float dot = Vector3.Dot(controllerRotation * Vector3.up, -controllerRelativeToHead.normalized);
float minDot = (tooltipMaxAngleFromCamera - 90.0f) / -90.0f;
float distToFace = Vector3.Distance(controllerRelativeToHead, Vector3.zero);
if (shouldFadeController
|| distToFace > tooltipMinDistanceFromFace
|| dot < minDot) {
tooltipAlphaValue = Mathf.Max(0.0f, tooltipAlphaValue - animationDelta);
} else {
tooltipAlphaValue = Mathf.Min(1.0f, tooltipAlphaValue + animationDelta);
}
}
/// Get the controller's orientation.
protected void GetControllerRotation(out Quaternion rotation, out Quaternion xyRotation, out float xAngle) {
// Find the controller's orientation relative to the player.
rotation = GvrControllerInput.Orientation;
rotation = Quaternion.Inverse(torsoRotation) * rotation;
// Extract just the x rotation angle.
Vector3 controllerForward = rotation * Vector3.forward;
xAngle = 90.0f - Vector3.Angle(controllerForward, Vector3.up);
// Remove the z rotation from the controller.
xyRotation = Quaternion.FromToRotation(Vector3.forward, controllerForward);
}
protected Vector3 GetHeadForward() {
return GetHeadRotation() * Vector3.forward;
}
protected Quaternion GetHeadRotation() {
#if UNITY_EDITOR
return GvrEditorEmulator.HeadRotation;
#else
return InputTracking.GetLocalRotation(VRNode.Head);
#endif // UNITY_EDITOR
}
protected Vector3 GetHeadPosition() {
#if UNITY_EDITOR
return GvrEditorEmulator.HeadPosition;
#else
return InputTracking.GetLocalPosition(VRNode.Head);
#endif // UNITY_EDITOR
}
#if UNITY_EDITOR
protected virtual void OnDrawGizmosSelected() {
if (!enabled) {
return;
}
Gizmos.color = Color.red;
Vector3 worldShoulder = transform.parent.TransformPoint(ShoulderPosition);
Gizmos.DrawSphere(worldShoulder, 0.02f);
Gizmos.color = Color.green;
Vector3 worldElbow = transform.parent.TransformPoint(elbowPosition);
Gizmos.DrawSphere(worldElbow, 0.02f);
Gizmos.color = Color.cyan;
Vector3 worldwrist = transform.parent.TransformPoint(wristPosition);
Gizmos.DrawSphere(worldwrist, 0.02f);
Gizmos.color = Color.blue;
Vector3 worldcontroller = transform.parent.TransformPoint(controllerPosition);
Gizmos.DrawSphere(worldcontroller, 0.02f);
}
#endif // UNITY_EDITOR
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Globalization;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Host;
using System.Collections.Generic;
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation.Internal.Host
{
/// <summary>
///
/// Wraps PSHost instances to provide a shim layer
/// between InternalCommand and the host-supplied PSHost instance.
///
/// This class exists for the purpose of ensuring that an externally-supplied PSHost meets the minimum proper required
/// implementation, and also to provide a leverage point at which the monad engine can hook the interaction between the engine,
/// cmdlets, and that external host.
///
/// That leverage may be necessary to manage concurrent access between multiple pipelines sharing the same instance of
/// PSHost.
///
/// </summary>
internal class InternalHost : PSHost, IHostSupportsInteractiveSession
{
/// <summary>
///
/// There should only be one instance of InternalHost per runspace (i.e. per engine), and all engine use of the host
/// should be through that single instance. If we ever accidentally create more than one instance of InternalHost per
/// runspace, then some of the internal state checks that InternalHost makes, like checking the nestedPromptCounter, can
/// be messed up.
///
/// To ensure that this constraint is met, I wanted to make this class a singleton. However, Hitesh rightly pointed out
/// that a singleton would be appdomain-global, which would prevent having multiple runspaces per appdomain. So we will
/// just have to be careful not to create extra instances of InternalHost per runspace.
///
/// </summary>
internal InternalHost(PSHost externalHost, ExecutionContext executionContext)
{
Dbg.Assert(externalHost != null, "must supply an PSHost");
Dbg.Assert(!(externalHost is InternalHost), "try to create an InternalHost from another InternalHost");
Dbg.Assert(executionContext != null, "must supply an ExecutionContext");
_externalHostRef = new ObjectRef<PSHost>(externalHost);
Context = executionContext;
PSHostUserInterface ui = externalHost.UI;
_internalUIRef = new ObjectRef<InternalHostUserInterface>(new InternalHostUserInterface(ui, this));
_zeroGuid = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
_idResult = _zeroGuid;
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="NotImplementedException">
///
/// when the external host's Name is null or empty.
///
/// </exception>
public override string Name
{
get
{
if (String.IsNullOrEmpty(_nameResult))
{
_nameResult = _externalHostRef.Value.Name;
#pragma warning disable 56503
if (String.IsNullOrEmpty(_nameResult))
{
throw PSTraceSource.NewNotImplementedException();
}
#pragma warning restore 56503
}
return _nameResult;
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="NotImplementedException">
///
/// when the external host's Version is null.
///
/// </exception>
public override System.Version Version
{
get
{
if (_versionResult == null)
{
_versionResult = _externalHostRef.Value.Version;
#pragma warning disable 56503
if (_versionResult == null)
{
throw PSTraceSource.NewNotImplementedException();
}
#pragma warning restore 56503
}
return _versionResult;
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="NotImplementedException">
///
/// when the external host's InstaceId is a zero Guid.
///
/// </exception>
public override System.Guid InstanceId
{
get
{
if (_idResult == _zeroGuid)
{
_idResult = _externalHostRef.Value.InstanceId;
#pragma warning disable 56503
if (_idResult == _zeroGuid)
{
throw PSTraceSource.NewNotImplementedException();
}
#pragma warning restore 56503
}
return _idResult;
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value>
/// </value>
public override System.Management.Automation.Host.PSHostUserInterface UI
{
get
{
return _internalUIRef.Value;
}
}
/// <summary>
/// Interface to be used for interaction with internal
/// host UI. InternalHostUserInterface wraps the host UI
/// supplied during construction. Use this wrapper to access
/// functionality specific to InternalHost.
/// </summary>
internal InternalHostUserInterface InternalUI
{
get
{
return _internalUIRef.Value;
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value>
/// </value>
/// <exception cref="NotImplementedException">
///
/// when the external host's CurrentCulture is null.
///
/// </exception>
public override System.Globalization.CultureInfo CurrentCulture
{
get
{
CultureInfo ci = _externalHostRef.Value.CurrentCulture ?? CultureInfo.InvariantCulture;
return ci;
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value>
/// </value>
/// <exception cref="NotImplementedException">
///
/// If the external host's CurrentUICulture is null.
///
/// </exception>
public override CultureInfo CurrentUICulture
{
get
{
#if CORECLR // No CultureInfo.InstalledUICulture In CoreCLR. Locale cannot be changed On CSS.
CultureInfo ci = _externalHostRef.Value.CurrentUICulture ?? CultureInfo.CurrentUICulture;
#else
CultureInfo ci = _externalHostRef.Value.CurrentUICulture ?? CultureInfo.InstalledUICulture;
#endif
return ci;
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <param name="exitCode"></param>
public override void SetShouldExit(int exitCode)
{
_externalHostRef.Value.SetShouldExit(exitCode);
}
/// <summary>
///
/// See base class
///
/// <seealso cref="ExitNestedPrompt"/>
/// </summary>
public override void EnterNestedPrompt()
{
EnterNestedPrompt(null);
}
private struct PromptContextData
{
public object SavedCurrentlyExecutingCommandVarValue;
public object SavedPSBoundParametersVarValue;
public ExecutionContext.SavedContextData SavedContextData;
public RunspaceAvailability RunspaceAvailability;
public PSLanguageMode LanguageMode;
}
/// <summary>
/// Internal proxy for EnterNestedPrompt
/// </summary>
/// <param name="callingCommand"></param>
///
internal void EnterNestedPrompt(InternalCommand callingCommand)
{
// Ensure we are in control of the pipeline
LocalRunspace localRunspace = null;
// This needs to be in a try / catch, since the LocalRunspace cast
// tries to verify that the host supports interactive sessions.
// Tests hosts do not.
try { localRunspace = this.Runspace as LocalRunspace; }
catch (PSNotImplementedException) { }
if (localRunspace != null)
{
Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline();
if ((currentlyRunningPipeline != null) &&
(currentlyRunningPipeline == localRunspace.PulsePipeline))
throw new InvalidOperationException();
}
// NTRAID#Windows OS Bugs-986407-2004/07/29 When kumarp has done the configuration work in the engine, it
// should include setting a bit that indicates that the initialization is complete, and code should be
// added here to throw an exception if this function is called before that bit is set.
if (NestedPromptCount < 0)
{
Dbg.Assert(false, "nested prompt counter should never be negative.");
throw PSTraceSource.NewInvalidOperationException(
InternalHostStrings.EnterExitNestedPromptOutOfSync);
}
// Increment our nesting counter. When we set the value of the variable, we will replace any existing variable
// of the same name. This is good, as any existing value is either 1) ours, and we have claim to replace it, or
// 2) is a squatter, and we have claim to clobber it.
++NestedPromptCount;
Context.SetVariable(SpecialVariables.NestedPromptCounterVarPath, NestedPromptCount);
// On entering a subshell, save and reset values of certain bits of session state
PromptContextData contextData = new PromptContextData();
contextData.SavedContextData = Context.SaveContextData();
contextData.SavedCurrentlyExecutingCommandVarValue = Context.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath);
contextData.SavedPSBoundParametersVarValue = Context.GetVariableValue(SpecialVariables.PSBoundParametersVarPath);
contextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability;
contextData.LanguageMode = Context.LanguageMode;
PSPropertyInfo commandInfoProperty = null;
PSPropertyInfo stackTraceProperty = null;
object oldCommandInfo = null;
object oldStackTrace = null;
if (callingCommand != null)
{
Dbg.Assert(callingCommand.Context == Context, "I expect that the contexts should match");
// Populate $CurrentlyExecutingCommand to facilitate debugging. One of the gotchas is that we are going to want
// to expose more and more debug info. We could just populate more and more local variables but that is probably
// a lousy approach as it pollutes the namespace. A better way to do it is to add NOTES to the variable value
// object.
PSObject newValue = PSObject.AsPSObject(callingCommand);
commandInfoProperty = newValue.Properties["CommandInfo"];
if (commandInfoProperty == null)
{
newValue.Properties.Add(new PSNoteProperty("CommandInfo", callingCommand.CommandInfo));
}
else
{
oldCommandInfo = commandInfoProperty.Value;
commandInfoProperty.Value = callingCommand.CommandInfo;
}
#if !CORECLR //TODO:CORECLR StackTrace not in CoreCLR
stackTraceProperty = newValue.Properties["StackTrace"];
if (stackTraceProperty == null)
{
newValue.Properties.Add(new PSNoteProperty("StackTrace", new System.Diagnostics.StackTrace()));
}
else
{
oldStackTrace = stackTraceProperty.Value;
stackTraceProperty.Value = new System.Diagnostics.StackTrace();
}
#endif
Context.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue);
}
_contextStack.Push(contextData);
Dbg.Assert(_contextStack.Count == NestedPromptCount, "number of saved contexts should equal nesting count");
Context.PSDebugTraceStep = false;
Context.PSDebugTraceLevel = 0;
Context.ResetShellFunctionErrorOutputPipe();
// Lock down the language in the nested prompt
if (Context.HasRunspaceEverUsedConstrainedLanguageMode)
{
Context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
}
this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true);
try
{
_externalHostRef.Value.EnterNestedPrompt();
}
catch
{
// So where things really go south is this path; which is possible for hosts (like our ConsoleHost)
// that don't return from EnterNestedPrompt immediately.
// EnterNestedPrompt() starts
// ExitNestedPrompt() called
// EnterNestedPrompt throws
ExitNestedPromptHelper();
throw;
}
finally
{
if (commandInfoProperty != null)
{
commandInfoProperty.Value = oldCommandInfo;
}
if (stackTraceProperty != null)
{
stackTraceProperty.Value = oldStackTrace;
}
}
Dbg.Assert(NestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0");
}
private void ExitNestedPromptHelper()
{
--NestedPromptCount;
Context.SetVariable(SpecialVariables.NestedPromptCounterVarPath, NestedPromptCount);
// restore the saved context
Dbg.Assert(_contextStack.Count > 0, "ExitNestedPrompt: called without any saved context");
if (_contextStack.Count > 0)
{
PromptContextData pcd = _contextStack.Pop();
pcd.SavedContextData.RestoreContextData(Context);
Context.LanguageMode = pcd.LanguageMode;
Context.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, pcd.SavedCurrentlyExecutingCommandVarValue);
Context.SetVariable(SpecialVariables.PSBoundParametersVarPath, pcd.SavedPSBoundParametersVarValue);
this.Context.CurrentRunspace.UpdateRunspaceAvailability(pcd.RunspaceAvailability, true);
}
Dbg.Assert(_contextStack.Count == NestedPromptCount, "number of saved contexts should equal nesting count");
}
/// <summary>
///
/// See base class
///
/// <seealso cref="EnterNestedPrompt()"/>
/// </summary>
public override void ExitNestedPrompt()
{
Dbg.Assert(NestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0");
if (NestedPromptCount == 0)
return;
try
{
_externalHostRef.Value.ExitNestedPrompt();
}
finally
{
ExitNestedPromptHelper();
}
ExitNestedPromptException enpe = new ExitNestedPromptException();
throw enpe;
}
/// <summary>
///
/// See base class
///
/// </summary>
public override PSObject PrivateData
{
get
{
PSObject result = _externalHostRef.Value.PrivateData;
return result;
}
}
/// <summary>
///
/// See base class
///
/// <seealso cref="NotifyEndApplication"/>
/// </summary>
public override void NotifyBeginApplication()
{
_externalHostRef.Value.NotifyBeginApplication();
}
/// <summary>
///
/// Called by the engine to notify the host that the execution of a legacy command has completed.
///
/// <seealso cref="NotifyBeginApplication"/>
/// </summary>
public override void NotifyEndApplication()
{
_externalHostRef.Value.NotifyEndApplication();
}
/// <summary>
/// This property enables and disables the host debugger if debugging is supported.
/// </summary>
public override bool DebuggerEnabled { get; set; } = true;
/// <summary>
/// Gets the external host as an IHostSupportsInteractiveSession if it implements this interface;
/// throws an exception otherwise.
/// </summary>
private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession()
{
IHostSupportsInteractiveSession host = _externalHostRef.Value as IHostSupportsInteractiveSession;
if (host == null)
{
throw new PSNotImplementedException();
}
return host;
}
/// <summary>
/// Called by the engine to notify the host that a runspace push has been requested.
/// </summary>
/// <seealso cref="PopRunspace"/>
public void PushRunspace(System.Management.Automation.Runspaces.Runspace runspace)
{
IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();
host.PushRunspace(runspace);
}
/// <summary>
/// Called by the engine to notify the host that a runspace pop has been requested.
/// </summary>
/// <seealso cref="PushRunspace"/>
public void PopRunspace()
{
IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();
host.PopRunspace();
}
/// <summary>
/// True if a runspace is pushed; false otherwise.
/// </summary>
public bool IsRunspacePushed
{
get
{
IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();
return host.IsRunspacePushed;
}
}
/// <summary>
/// Returns the current runspace associated with this host.
/// </summary>
public Runspace Runspace
{
get
{
IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();
return host.Runspace;
}
}
/// <summary>
/// Checks if the host is in a nested prompt
/// </summary>
/// <returns>true, if host in nested prompt
/// false, otherwise</returns>
internal bool HostInNestedPrompt()
{
if (NestedPromptCount > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Sets the reference to the external host and the internal UI to a temporary
/// new host and its UI. This exists so that if the PowerShell/Pipeline
/// object has a different host from the runspace it can set it's host during its
/// invocation, and then revert it after the invocation is completed.
/// </summary>
/// <seealso cref="RevertHostRef"/> and
internal void SetHostRef(PSHost psHost)
{
_externalHostRef.Override(psHost);
_internalUIRef.Override(new InternalHostUserInterface(psHost.UI, this));
}
/// <summary>
/// Reverts the temporary host set by SetHost. If no host was temporarily set, this has no effect.
/// </summary>
/// <seealso cref="SetHostRef"/> and
internal void RevertHostRef()
{
// nothing to revert if Host reference is not set.
if (!IsHostRefSet) { return; }
_externalHostRef.Revert();
_internalUIRef.Revert();
}
/// <summary>
/// Returns true if the external host reference is temporarily set to another host, masking the original host.
/// </summary>
internal bool IsHostRefSet
{
get { return _externalHostRef.IsOverridden; }
}
internal ExecutionContext Context { get; }
internal PSHost ExternalHost
{
get
{
return _externalHostRef.Value;
}
}
internal int NestedPromptCount { get; private set; }
// Masked variables.
private ObjectRef<PSHost> _externalHostRef;
private ObjectRef<InternalHostUserInterface> _internalUIRef;
// Private variables.
private string _nameResult;
private Version _versionResult;
private Guid _idResult;
private Stack<PromptContextData> _contextStack = new Stack<PromptContextData>();
private readonly Guid _zeroGuid;
}
} // namespace
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using LWBoilerPlate.Areas.HelpPage.ModelDescriptions;
using LWBoilerPlate.Areas.HelpPage.Models;
namespace LWBoilerPlate.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2001
//
// File: LineGeometry.cs
//------------------------------------------------------------------------------
using System;
using MS.Internal;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Windows.Media;
using System.Windows;
using System.Text.RegularExpressions;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media
{
/// <summary>
/// This is the Geometry class for Lines.
/// </summary>
public sealed partial class LineGeometry : Geometry
{
#region Constructors
/// <summary>
///
/// </summary>
public LineGeometry()
{
}
/// <summary>
///
/// </summary>
public LineGeometry(Point startPoint, Point endPoint)
{
StartPoint = startPoint;
EndPoint = endPoint;
}
/// <summary>
///
/// </summary>
public LineGeometry(
Point startPoint,
Point endPoint,
Transform transform) : this(startPoint, endPoint)
{
Transform = transform;
}
#endregion
/// <summary>
/// Gets the bounds of this Geometry as an axis-aligned bounding box
/// </summary>
public override Rect Bounds
{
get
{
ReadPreamble();
Rect rect = new Rect(StartPoint, EndPoint);
Transform transform = Transform;
if (transform != null && !transform.IsIdentity)
{
transform.TransformRect(ref rect);
}
return rect;
}
}
/// <summary>
/// Returns the axis-aligned bounding rectangle when stroked with a pen, after applying
/// the supplied transform (if non-null).
/// </summary>
internal override Rect GetBoundsInternal(Pen pen, Matrix worldMatrix, double tolerance, ToleranceType type)
{
Matrix geometryMatrix;
Transform.GetTransformValue(Transform, out geometryMatrix);
return LineGeometry.GetBoundsHelper(
pen,
worldMatrix,
StartPoint,
EndPoint,
geometryMatrix,
tolerance,
type);
}
/// <SecurityNote>
/// Critical - it calls a critical method, Geometry.GetBoundsHelper and has an unsafe block
/// TreatAsSafe - returning a LineGeometry's bounds is considered safe
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static Rect GetBoundsHelper(Pen pen, Matrix worldMatrix, Point pt1, Point pt2,
Matrix geometryMatrix, double tolerance, ToleranceType type)
{
Debug.Assert(worldMatrix != null);
Debug.Assert(geometryMatrix != null);
if (pen == null && worldMatrix.IsIdentity && geometryMatrix.IsIdentity)
{
return new Rect(pt1, pt2);
}
else
{
unsafe
{
Point* pPoints = stackalloc Point[2];
pPoints[0] = pt1;
pPoints[1] = pt2;
fixed (byte *pTypes = LineGeometry.s_lineTypes)
{
return Geometry.GetBoundsHelper(
pen,
&worldMatrix,
pPoints,
pTypes,
c_pointCount,
c_segmentCount,
&geometryMatrix,
tolerance,
type,
false); // skip hollows - meaningless here, this is never a hollow
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe block and calls critical method Geometry.ContainsInternal.
/// TreatAsSafe - as this doesn't expose anything sensitive.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal override bool ContainsInternal(Pen pen, Point hitPoint, double tolerance, ToleranceType type)
{
unsafe
{
Point *pPoints = stackalloc Point[2];
pPoints[0] = StartPoint;
pPoints[1] = EndPoint;
fixed (byte* pTypes = GetTypeList())
{
return ContainsInternal(
pen,
hitPoint,
tolerance,
type,
pPoints,
GetPointCount(),
pTypes,
GetSegmentCount());
}
}
}
/// <summary>
/// Returns true if this geometry is empty
/// </summary>
public override bool IsEmpty()
{
return false;
}
/// <summary>
/// Returns true if this geometry may have curved segments
/// </summary>
public override bool MayHaveCurves()
{
return false;
}
/// <summary>
/// Gets the area of this geometry
/// </summary>
/// <param name="tolerance">The computational error tolerance</param>
/// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param>
public override double GetArea(double tolerance, ToleranceType type)
{
return 0.0;
}
private byte[] GetTypeList() { return s_lineTypes; }
private static byte[] s_lineTypes = new byte[] { (byte)MILCoreSegFlags.SegTypeLine };
private uint GetPointCount() { return c_pointCount; }
private uint GetSegmentCount() { return c_segmentCount; }
/// <summary>
/// GetAsPathGeometry - return a PathGeometry version of this Geometry
/// </summary>
internal override PathGeometry GetAsPathGeometry()
{
PathStreamGeometryContext ctx = new PathStreamGeometryContext(FillRule.EvenOdd, Transform);
PathGeometry.ParsePathGeometryData(GetPathGeometryData(), ctx);
return ctx.GetPathGeometry();
}
internal override PathFigureCollection GetTransformedFigureCollection(Transform transform)
{
// This is lossy for consistency with other GetPathFigureCollection() implementations
// however this limitation doesn't otherwise need to exist for LineGeometry.
Point startPoint = StartPoint;
Point endPoint = EndPoint;
// Apply internal transform
Transform internalTransform = Transform;
if (internalTransform != null && !internalTransform.IsIdentity)
{
Matrix matrix = internalTransform.Value;
startPoint *= matrix;
endPoint *= matrix;
}
// Apply external transform
if (transform != null && !transform.IsIdentity)
{
Matrix matrix = transform.Value;
startPoint *= matrix;
endPoint *= matrix;
}
PathFigureCollection collection = new PathFigureCollection();
collection.Add(
new PathFigure(
startPoint,
new PathSegment[]{new LineSegment(endPoint, true)},
false // ==> not closed
)
);
return collection;
}
/// <summary>
/// GetPathGeometryData - returns a byte[] which contains this Geometry represented
/// as a path geometry's serialized format.
/// </summary>
internal override PathGeometryData GetPathGeometryData()
{
if (IsObviouslyEmpty())
{
return Geometry.GetEmptyPathGeometryData();
}
PathGeometryData data = new PathGeometryData();
data.FillRule = FillRule.EvenOdd;
data.Matrix = CompositionResourceManager.TransformToMilMatrix3x2D(Transform);
ByteStreamGeometryContext ctx = new ByteStreamGeometryContext();
ctx.BeginFigure(StartPoint, true /* is filled */, false /* is closed */);
ctx.LineTo(EndPoint, true /* is stroked */, false /* is smooth join */);
ctx.Close();
data.SerializedData = ctx.GetData();
return data;
}
#region Static Data
private const UInt32 c_segmentCount = 1;
private const UInt32 c_pointCount = 2;
#endregion
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// 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.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Base for handling both client side and server side calls.
/// Manages native call lifecycle and provides convenience methods.
/// </summary>
internal abstract class AsyncCallBase<TWrite, TRead> : IReceivedMessageCallback, ISendCompletionCallback
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>();
protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message.");
readonly Func<TWrite, byte[]> serializer;
readonly Func<byte[], TRead> deserializer;
protected readonly object myLock = new object();
protected INativeCall call;
protected bool disposed;
protected bool started;
protected bool cancelRequested;
protected TaskCompletionSource<TRead> streamingReadTcs; // Completion of a pending streaming read if not null.
protected TaskCompletionSource<object> streamingWriteTcs; // Completion of a pending streaming write or send close from client if not null.
protected TaskCompletionSource<object> sendStatusFromServerTcs;
protected bool isStreamingWriteCompletionDelayed; // Only used for the client side.
protected bool readingDone; // True if last read (i.e. read with null payload) was already received.
protected bool halfcloseRequested; // True if send close have been initiated.
protected bool finished; // True if close has been received from the peer.
protected bool initialMetadataSent;
protected long streamingWritesCounter; // Number of streaming send operations started so far.
public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer)
{
this.serializer = GrpcPreconditions.CheckNotNull(serializer);
this.deserializer = GrpcPreconditions.CheckNotNull(deserializer);
}
/// <summary>
/// Requests cancelling the call.
/// </summary>
public void Cancel()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.Cancel();
}
}
}
/// <summary>
/// Requests cancelling the call with given status.
/// </summary>
protected void CancelWithStatus(Status status)
{
lock (myLock)
{
cancelRequested = true;
if (!disposed)
{
call.CancelWithStatus(status);
}
}
}
protected void InitializeInternal(INativeCall call)
{
lock (myLock)
{
this.call = call;
}
}
/// <summary>
/// Initiates sending a message. Only one send operation can be active at a time.
/// </summary>
protected Task SendMessageInternalAsync(TWrite msg, WriteFlags writeFlags)
{
byte[] payload = UnsafeSerialize(msg);
lock (myLock)
{
GrpcPreconditions.CheckState(started);
var earlyResult = CheckSendAllowedOrEarlyResult();
if (earlyResult != null)
{
return earlyResult;
}
call.StartSendMessage(SendCompletionCallback, payload, writeFlags, !initialMetadataSent);
initialMetadataSent = true;
streamingWritesCounter++;
streamingWriteTcs = new TaskCompletionSource<object>();
return streamingWriteTcs.Task;
}
}
/// <summary>
/// Initiates reading a message. Only one read operation can be active at a time.
/// </summary>
protected Task<TRead> ReadMessageInternalAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
if (readingDone)
{
// the last read that returns null or throws an exception is idempotent
// and maintains its state.
GrpcPreconditions.CheckState(streamingReadTcs != null, "Call does not support streaming reads.");
return streamingReadTcs.Task;
}
GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time");
GrpcPreconditions.CheckState(!disposed);
call.StartReceiveMessage(ReceivedMessageCallback);
streamingReadTcs = new TaskCompletionSource<TRead>();
return streamingReadTcs.Task;
}
}
/// <summary>
/// If there are no more pending actions and no new actions can be started, releases
/// the underlying native resources.
/// </summary>
protected bool ReleaseResourcesIfPossible()
{
if (!disposed && call != null)
{
bool noMoreSendCompletions = streamingWriteTcs == null && (halfcloseRequested || cancelRequested || finished);
if (noMoreSendCompletions && readingDone && finished)
{
ReleaseResources();
return true;
}
}
return false;
}
protected abstract bool IsClient
{
get;
}
/// <summary>
/// Returns an exception to throw for a failed send operation.
/// It is only allowed to call this method for a call that has already finished.
/// </summary>
protected abstract Exception GetRpcExceptionClientOnly();
private void ReleaseResources()
{
if (call != null)
{
call.Dispose();
}
disposed = true;
OnAfterReleaseResourcesLocked();
}
protected virtual void OnAfterReleaseResourcesLocked()
{
}
protected virtual void OnAfterReleaseResourcesUnlocked()
{
}
/// <summary>
/// Checks if sending is allowed and possibly returns a Task that allows short-circuiting the send
/// logic by directly returning the write operation result task. Normally, null is returned.
/// </summary>
protected abstract Task CheckSendAllowedOrEarlyResult();
protected byte[] UnsafeSerialize(TWrite msg)
{
return serializer(msg);
}
protected Exception TryDeserialize(byte[] payload, out TRead msg)
{
try
{
msg = deserializer(payload);
return null;
}
catch (Exception e)
{
msg = default(TRead);
return e;
}
}
/// <summary>
/// Handles send completion (including SendCloseFromClient).
/// </summary>
protected void HandleSendFinished(bool success)
{
bool delayCompletion = false;
TaskCompletionSource<object> origTcs = null;
bool releasedResources;
lock (myLock)
{
if (!success && !finished && IsClient) {
// We should be setting this only once per call, following writes will be short circuited
// because they cannot start until the entire call finishes.
GrpcPreconditions.CheckState(!isStreamingWriteCompletionDelayed);
// leave streamingWriteTcs set, it will be completed once call finished.
isStreamingWriteCompletionDelayed = true;
delayCompletion = true;
}
else
{
origTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (!success)
{
if (!delayCompletion)
{
if (IsClient)
{
GrpcPreconditions.CheckState(finished); // implied by !success && !delayCompletion && IsClient
origTcs.SetException(GetRpcExceptionClientOnly());
}
else
{
origTcs.SetException (new IOException("Error sending from server."));
}
}
// if delayCompletion == true, postpone SetException until call finishes.
}
else
{
origTcs.SetResult(null);
}
}
/// <summary>
/// Handles send status from server completion.
/// </summary>
protected void HandleSendStatusFromServerFinished(bool success)
{
bool releasedResources;
lock (myLock)
{
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (!success)
{
sendStatusFromServerTcs.SetException(new IOException("Error sending status from server."));
}
else
{
sendStatusFromServerTcs.SetResult(null);
}
}
/// <summary>
/// Handles streaming read completion.
/// </summary>
protected void HandleReadFinished(bool success, byte[] receivedMessage)
{
// if success == false, received message will be null. It that case we will
// treat this completion as the last read an rely on C core to handle the failed
// read (e.g. deliver approriate statusCode on the clientside).
TRead msg = default(TRead);
var deserializeException = (success && receivedMessage != null) ? TryDeserialize(receivedMessage, out msg) : null;
TaskCompletionSource<TRead> origTcs = null;
bool releasedResources;
lock (myLock)
{
origTcs = streamingReadTcs;
if (receivedMessage == null)
{
// This was the last read.
readingDone = true;
}
if (deserializeException != null && IsClient)
{
readingDone = true;
// TODO(jtattermusch): it might be too late to set the status
CancelWithStatus(DeserializeResponseFailureStatus);
}
if (!readingDone)
{
streamingReadTcs = null;
}
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (deserializeException != null && !IsClient)
{
origTcs.SetException(new IOException("Failed to deserialize request message.", deserializeException));
return;
}
origTcs.SetResult(msg);
}
protected ISendCompletionCallback SendCompletionCallback => this;
void ISendCompletionCallback.OnSendCompletion(bool success)
{
HandleSendFinished(success);
}
IReceivedMessageCallback ReceivedMessageCallback => this;
void IReceivedMessageCallback.OnReceivedMessage(bool success, byte[] receivedMessage)
{
HandleReadFinished(success, receivedMessage);
}
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace System
{
public partial class String
{
//
//Native Static Methods
//
private static unsafe int FastCompareStringHelper(uint* strAChars, int countA, uint* strBChars, int countB)
{
int count = (countA < countB) ? countA : countB;
#if BIT64
long diff = (long)((byte*)strAChars - (byte*)strBChars);
#else
int diff = (int)((byte*)strAChars - (byte*)strBChars);
#endif
#if BIT64
int alignmentA = (int)((long)strAChars) & (sizeof(IntPtr) - 1);
int alignmentB = (int)((long)strBChars) & (sizeof(IntPtr) - 1);
if (alignmentA == alignmentB)
{
if ((alignmentA == 2 || alignmentA == 6) && (count >= 1))
{
char* ptr2 = (char*)strBChars;
if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0)
return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2);
strBChars = (uint*)(++ptr2);
count -= 1;
alignmentA = (alignmentA == 2 ? 4 : 0);
}
if ((alignmentA == 4) && (count >= 2))
{
uint* ptr2 = (uint*)strBChars;
if ((*((uint*)((byte*)ptr2 + diff)) - *ptr2) != 0)
{
char* chkptr1 = (char*)((byte*)strBChars + diff);
char* chkptr2 = (char*)strBChars;
if (*chkptr1 != *chkptr2)
return ((int)*chkptr1 - (int)*chkptr2);
return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1));
}
strBChars = ++ptr2;
count -= 2;
alignmentA = 0;
}
if ((alignmentA == 0))
{
while (count >= 4)
{
long* ptr2 = (long*)strBChars;
if ((*((long*)((byte*)ptr2 + diff)) - *ptr2) != 0)
{
if ((*((uint*)((byte*)ptr2 + diff)) - *(uint*)ptr2) != 0)
{
char* chkptr1 = (char*)((byte*)strBChars + diff);
char* chkptr2 = (char*)strBChars;
if (*chkptr1 != *chkptr2)
return ((int)*chkptr1 - (int)*chkptr2);
return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1));
}
else
{
char* chkptr1 = (char*)((uint*)((byte*)strBChars + diff) + 1);
char* chkptr2 = (char*)((uint*)strBChars + 1);
if (*chkptr1 != *chkptr2)
return ((int)*chkptr1 - (int)*chkptr2);
return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1));
}
}
strBChars = (uint*)(++ptr2);
count -= 4;
}
}
{
char* ptr2 = (char*)strBChars;
while ((count -= 1) >= 0)
{
if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0)
return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2);
++ptr2;
}
}
}
else
#endif // BIT64
{
#if BIT64
if (Math.Abs(alignmentA - alignmentB) == 4)
{
if ((alignmentA == 2) || (alignmentB == 2))
{
char* ptr2 = (char*)strBChars;
if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0)
return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2);
strBChars = (uint*)(++ptr2);
count -= 1;
}
}
#endif // BIT64
// Loop comparing a DWORD at a time.
// Reads are potentially unaligned
while ((count -= 2) >= 0)
{
if ((*((uint*)((byte*)strBChars + diff)) - *strBChars) != 0)
{
char* ptr1 = (char*)((byte*)strBChars + diff);
char* ptr2 = (char*)strBChars;
if (*ptr1 != *ptr2)
return ((int)*ptr1 - (int)*ptr2);
return ((int)*(ptr1 + 1) - (int)*(ptr2 + 1));
}
++strBChars;
}
int c;
if (count == -1)
if ((c = *((char*)((byte*)strBChars + diff)) - *((char*)strBChars)) != 0)
return c;
}
return countA - countB;
}
//
//
// NATIVE INSTANCE METHODS
//
//
//
// Search/Query methods
//
//
// Common worker for the various Equality methods. The caller must have already ensured that
// both strings are non-null and that their lengths are equal. Ther caller should also have
// done the Object.ReferenceEquals() fastpath check as we won't repeat it here.
//
private static unsafe bool EqualsHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// PERF: No length check needed as there is always an int32 worth of string allocated
// This read can also include the null terminator which both strings will have
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
// for 64-bit platforms we unroll by 12 and
// check 3 qword at a time. This is less code
// than the 32 bit case and is a shorter path length
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto ReturnFalse;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto ReturnFalse;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto ReturnFalse;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto ReturnFalse;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto ReturnFalse;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto ReturnFalse;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto ReturnFalse;
length -= 10; a += 10; b += 10;
}
#endif
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
}
return true;
ReturnFalse:
return false;
}
}
private static unsafe bool StartsWithOrdinalHelper(String str, String startsWith)
{
Debug.Assert(str != null);
Debug.Assert(startsWith != null);
Debug.Assert(str.Length >= startsWith.Length);
int length = startsWith.Length;
fixed (char* ap = &str._firstChar) fixed (char* bp = &startsWith._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// No length check needed as this method is called when length >= 2
Debug.Assert(length >= 2);
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto ReturnFalse;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto ReturnFalse;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto ReturnFalse;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto ReturnFalse;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto ReturnFalse;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto ReturnFalse;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto ReturnFalse;
length -= 10; a += 10; b += 10;
}
#endif
while (length >= 2)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
}
// PERF: This depends on the fact that the String objects are always zero terminated
// and that the terminating zero is not included in the length. For even string sizes
// this compare can include the zero terminator. Bitwise OR avoids a branch.
return length == 0 | *a == *b;
ReturnFalse:
return false;
}
}
private static unsafe int CompareOrdinalHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined
Debug.Assert(strA._firstChar == strB._firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
// Check if the second chars are different here
// The reason we check if _firstChar is different is because
// it's the most common case and allows us to avoid a method call
// to here.
// The reason we check if the second char is different is because
// if the first two chars the same we can increment by 4 bytes,
// leaving us word-aligned on both 32-bit (12 bytes into the string)
// and 64-bit (16 bytes) platforms.
// For empty strings, the second char will be null due to padding.
// The start of the string is the EE type pointer + string length,
// which takes up 8 bytes on 32-bit, 12 on x64. For empty strings,
// the null terminator immediately follows, leaving us with an object
// 10/14 bytes in size. Since everything needs to be a multiple
// of 4/8, this will get padded and zeroed out.
// For one-char strings the second char will be the null terminator.
// NOTE: If in the future there is a way to read the second char
// without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe
// is exposed to mscorlib, or a future version of C# allows inline IL),
// then do that and short-circuit before the fixed.
if (*(a + 1) != *(b + 1)) goto DiffOffset1;
// Since we know that the first two chars are the same,
// we can increment by 2 here and skip 4 bytes.
// This leaves us 8-byte aligned, which results
// on better perf for 64-bit platforms.
length -= 2; a += 2; b += 2;
// unroll the loop
#if BIT64
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto DiffOffset0;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8;
length -= 12; a += 12; b += 12;
}
#else // BIT64
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto DiffOffset0;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8;
length -= 10; a += 10; b += 10;
}
#endif // BIT64
// Fallback loop:
// go back to slower code path and do comparison on 4 bytes at a time.
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto DiffNextInt;
length -= 2;
a += 2;
b += 2;
}
// At this point, we have compared all the characters in at least one string.
// The longer string will be larger.
return strA.Length - strB.Length;
#if BIT64
DiffOffset8: a += 4; b += 4;
DiffOffset4: a += 4; b += 4;
#else // BIT64
// Use jumps instead of falling through, since
// otherwise going to DiffOffset8 will involve
// 8 add instructions before getting to DiffNextInt
DiffOffset8: a += 8; b += 8; goto DiffOffset0;
DiffOffset6: a += 6; b += 6; goto DiffOffset0;
DiffOffset4: a += 2; b += 2;
DiffOffset2: a += 2; b += 2;
#endif // BIT64
DiffOffset0:
// If we reached here, we already see a difference in the unrolled loop above
#if BIT64
if (*(int*)a == *(int*)b)
{
a += 2; b += 2;
}
#endif // BIT64
DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
internal static unsafe int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB)
{
// Argument validation should be handled by callers.
Debug.Assert(strA != null && strB != null);
Debug.Assert(indexA >= 0 && indexB >= 0);
Debug.Assert(countA >= 0 && countB >= 0);
Debug.Assert(countA <= strA.Length - indexA);
Debug.Assert(countB <= strB.Length - indexB);
// Set up the loop variables.
fixed (char* pStrA = &strA._firstChar, pStrB = &strB._firstChar)
{
char* strAChars = pStrA + indexA;
char* strBChars = pStrB + indexB;
return FastCompareStringHelper((uint*)strAChars, countA, (uint*)strBChars, countB);
}
}
public static int Compare(String strA, String strB)
{
return Compare(strA, strB, StringComparison.CurrentCulture);
}
public static int Compare(String strA, String strB, bool ignoreCase)
{
var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
return Compare(strA, strB, comparisonType);
}
// Provides a more flexible function for string comparision. See StringComparison
// for meaning of different comparisonType.
public static int Compare(String strA, String strB, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return FormatProvider.Compare(strA, 0, strA.Length, strB, 0, strB.Length);
case StringComparison.CurrentCultureIgnoreCase:
return FormatProvider.CompareIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length);
case StringComparison.Ordinal:
// Most common case: first character is different.
// Returns false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
case StringComparison.OrdinalIgnoreCase:
return FormatProvider.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
default:
throw new NotSupportedException(SR.NotSupported_StringComparison);
}
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
//
public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return culture.CompareInfo.Compare(strA, strB, options);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase, and the culture is set
// by culture
//
public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo culture)
{
CompareOptions options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, strB, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length)
{
// NOTE: It's important we call the boolean overload, and not the StringComparison
// one. The two have some subtly different behavior (see notes in the former).
return Compare(strA, indexA, strB, indexB, length, ignoreCase: false);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length count is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase)
{
// Ideally we would just forward to the string.Compare overload that takes
// a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase.
// That function will return early if an optimization can be applied, e.g. if
// (object)strA == strB && indexA == indexB then it will return 0 straightaway.
// There are a couple of subtle behavior differences that prevent us from doing so
// however:
// - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works
// since that method also returns early for nulls before validation. It shouldn't
// for this overload.
// - Since we originally forwarded to FormatProvider for all of the argument
// validation logic, the ArgumentOutOfRangeExceptions thrown will contain different
// parameter names.
// Therefore, we have to duplicate some of the logic here.
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
return ignoreCase ?
FormatProvider.CompareIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB) :
FormatProvider.Compare(strA, indexA, lengthA, strB, indexB, lengthB);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean,
// and the culture is set by culture.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture)
{
CompareOptions options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, indexA, strB, indexB, length, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// @TODO: Spec#: Figure out what to do here with the return statement above.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return FormatProvider.Compare(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.CurrentCultureIgnoreCase:
return FormatProvider.CompareIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.Ordinal:
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.OrdinalIgnoreCase:
return FormatProvider.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
default:
throw new ArgumentException(SR.NotSupported_StringComparison);
}
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(String strA, String strB)
{
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
// Most common case, first character is different.
// This will return false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
}
public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length)
{
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// COMPAT: Checking for nulls should become before the arguments are validated,
// but other optimizations which allow us to return early should come after.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
}
// Compares this String to another String (cast as object), returning an integer that
// indicates the relationship. This method returns a value less than 0 if this is less than value, 0
// if this is equal to value, or a value greater than 0 if this is greater than value.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
string other = value as string;
if (other == null)
{
throw new ArgumentException(SR.Arg_MustBeString);
}
return CompareTo(other); // will call the string-based overload
}
// Determines the sorting relation of StrB to the current instance.
//
public int CompareTo(String strB)
{
return string.Compare(this, strB, StringComparison.CurrentCulture);
}
// Determines whether a specified string is a suffix of the the current instance.
//
// The case-sensitive and culture-sensitive option is set by options,
// and the default culture is used.
//
public Boolean EndsWith(String value)
{
return EndsWith(value, StringComparison.CurrentCulture);
}
public Boolean EndsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
if ((Object)this == (Object)value)
{
return true;
}
if (value.Length == 0)
{
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return FormatProvider.IsSuffix(this, value);
case StringComparison.CurrentCultureIgnoreCase:
return FormatProvider.IsSuffixIgnoreCase(this, value);
case StringComparison.Ordinal:
return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
case StringComparison.OrdinalIgnoreCase:
return this.Length < value.Length ? false : (FormatProvider.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture;
if (culture == null)
referenceCulture = CultureInfo.CurrentCulture;
else
referenceCulture = culture;
return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool EndsWith(char value)
{
int thisLen = Length;
return thisLen != 0 && this[thisLen - 1] == value;
}
// Determines whether two strings match.
public override bool Equals(Object obj)
{
if (Object.ReferenceEquals(this, obj))
return true;
String str = obj as String;
if (str == null)
return false;
if (this.Length != str.Length)
return false;
return EqualsHelper(this, str);
}
// Determines whether two strings match.
public bool Equals(String value)
{
if (Object.ReferenceEquals(this, value))
return true;
// NOTE: No need to worry about casting to object here.
// If either side of an == comparison between strings
// is null, Roslyn generates a simple ceq instruction
// instead of calling string.op_Equality.
if (value == null)
return false;
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
}
public bool Equals(String value, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
if ((Object)this == (Object)value)
{
return true;
}
if ((Object)value == null)
{
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (FormatProvider.Compare(this, 0, this.Length, value, 0, value.Length) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (FormatProvider.CompareIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0);
case StringComparison.Ordinal:
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length != value.Length)
return false;
else
{
return FormatProvider.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0;
}
case StringComparison.InvariantCulture:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Determines whether two Strings match.
public static bool Equals(String a, String b)
{
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null || a.Length != b.Length)
{
return false;
}
return EqualsHelper(a, b);
}
public static bool Equals(String a, String b, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null)
{
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (FormatProvider.Compare(a, 0, a.Length, b, 0, b.Length) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (FormatProvider.CompareIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0);
case StringComparison.Ordinal:
if (a.Length != b.Length)
return false;
return EqualsHelper(a, b);
case StringComparison.OrdinalIgnoreCase:
if (a.Length != b.Length)
return false;
else
{
return FormatProvider.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0;
}
case StringComparison.InvariantCulture:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static bool operator ==(String a, String b)
{
if (Object.ReferenceEquals(a, b))
return true;
if (a == null || b == null || a.Length != b.Length)
return false;
return EqualsHelper(a, b);
}
public static bool operator !=(String a, String b)
{
if (Object.ReferenceEquals(a, b))
return false;
if (a == null || b == null || a.Length != b.Length)
return true;
return !EqualsHelper(a, b);
}
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
public override int GetHashCode()
{
return Marvin.ComputeHash32(ref Unsafe.As<char, byte>(ref _firstChar), _stringLength * 2, Marvin.DefaultSeed);
}
// Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile
// hash table).
internal int GetLegacyNonRandomizedHashCode()
{
unsafe
{
fixed (char* src = &_firstChar)
{
Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
#if BIT64
int hash1 = 5381;
#else // !BIT64 (32)
int hash1 = (5381<<16) + 5381;
#endif
int hash2 = hash1;
#if BIT64
int c;
char* s = src;
while ((c = s[0]) != 0)
{
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2) ^ c;
s += 2;
}
#else // !BIT64 (32)
// 32 bit machines.
int* pint = (int *)src;
int len = this.Length;
while (len > 2)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1];
pint += 2;
len -= 4;
}
if (len > 0)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
}
#endif
return hash1 + (hash2 * 1566083941);
}
}
}
// Determines whether a specified string is a prefix of the current instance
//
public Boolean StartsWith(String value)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
return StartsWith(value, StringComparison.CurrentCulture);
}
public Boolean StartsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
if ((Object)this == (Object)value)
{
return true;
}
if (value.Length == 0)
{
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return FormatProvider.IsPrefix(this, value);
case StringComparison.CurrentCultureIgnoreCase:
return FormatProvider.IsPrefixIgnoreCase(this, value);
case StringComparison.Ordinal:
if (this.Length < value.Length || _firstChar != value._firstChar)
{
return false;
}
return (value.Length == 1) ?
true : // First char is the same and thats all there is to compare
StartsWithOrdinalHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length < value.Length)
{
return false;
}
return FormatProvider.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0;
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture;
if (culture == null)
referenceCulture = CultureInfo.CurrentCulture;
else
referenceCulture = culture;
return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool StartsWith(char value) => Length != 0 && _firstChar == value;
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2021 Tim Stair
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
namespace Support.Util
{
/// <summary>
/// Summary description for CommandLineParser.
/// </summary>
public class CommandLineParser
{
private readonly Dictionary<string, List<string>> s_dictionaryArgs = new Dictionary<string, List<string>>();
/// <summary>
/// Private constructor (static class)
/// </summary>
public CommandLineParser(){}
/// <summary>
/// Parse the command line into a Hashtable. Arguments are space delimited.
/// Examples:
/// -x filename (would associate the "filename" with -x)
/// -y (simply flags -y as part of the command line)
/// </summary>
/// <param name="args"></param>
public CommandLineParser Parse(string[] args)
{
var nIdx = 0;
// sort out the command line into a dictionary of lists
var listArgumentValues = new List<string>();
// initialize a dumping ground for no arg params
AddArgument(string.Empty, listArgumentValues);
while (nIdx < args.Length)
{
if (args[nIdx].StartsWith("-"))
{
listArgumentValues = new List<string>();
AddArgument(args[nIdx].ToUpper().Substring(1), listArgumentValues);
}
else
{
listArgumentValues.Add(args[nIdx]);
}
nIdx++;
}
return this;
}
/// <summary>
/// Adds the specified argument to the argument table if it has not been previously defined.
/// </summary>
/// <param name="sArg">Argument string</param>
/// <param name="sValue">Argument value</param>
private void AddArgument(string sArg, List<string> listArgumentValues)
{
if (s_dictionaryArgs.ContainsKey(sArg))
{
s_dictionaryArgs.Remove(sArg);
}
s_dictionaryArgs.Add(sArg, listArgumentValues);
}
/// <summary>
/// Gets the value associated with the argument or the supplied default
/// </summary>
/// <param name="sArg">The argument to get</param>
/// <param name="sDefault">The default value to get if the argument is not specified</param>
/// <returns></returns>
public string GetStringArg(string sArg, string sDefault)
{
string sReturn = GetStringArg(sArg);
if (null == sReturn)
{
return sDefault;
}
return sReturn;
}
/// <summary>
///
/// </summary>
/// <param name="eArg"></param>
/// <returns></returns>
public string GetStringArg(Enum eArg)
{
return GetStringArg(eArg.ToString());
}
/// <summary>
/// Gets the value associated with the argument.
/// </summary>
/// <param name="sArg">The argument to get the value of.</param>
/// <returns></returns>
public string GetStringArg(string sArg)
{
string sKey = sArg.ToUpper();
if (s_dictionaryArgs.ContainsKey(sKey))
{
if (null == s_dictionaryArgs[sKey])
{
return string.Empty;
}
StringBuilder zBuilder = new StringBuilder();
foreach(string sValue in s_dictionaryArgs[sKey])
{
zBuilder.Append(sValue + " ");
}
return zBuilder.ToString().Trim();
}
return null;
}
/// <summary>
/// Gets the arguments associated with an option as an array
/// </summary>
/// <param name="eArg"></param>
/// <returns></returns>
public string[] GetStringArgs(Enum eArg)
{
return GetStringArgs(eArg.ToString());
}
/// <summary>
/// Gets the arguments associated with an option as an array
/// </summary>
/// <param name="sArg"></param>
/// <returns></returns>
public string[] GetStringArgs(string sArg)
{
string sKey = sArg.ToUpper();
if (s_dictionaryArgs.ContainsKey(sKey))
{
return s_dictionaryArgs[sKey].ToArray();
}
return null;
}
/// <summary>
/// Gets whether the argument was specified on the command line.
/// </summary>
/// <param name="sArg"></param>
/// <returns></returns>
public bool GetFlagArg(Enum eArg)
{
return GetFlagArg(eArg.ToString());
}
/// <summary>
/// Gets whether the argument was specified on the command line.
/// </summary>
/// <param name="sArg"></param>
/// <returns></returns>
public bool GetFlagArg(string sArg)
{
return s_dictionaryArgs.ContainsKey(sArg.ToUpper());
}
/// <summary>
/// Gets the number of arguments from the command line
/// </summary>
/// <returns>The number of command line arguments(pairs) </returns>
public int GetArgCount()
{
return s_dictionaryArgs.Count;
}
/// <summary>
/// Wrapper for printing the usage of the application.
/// </summary>
/// <param name="sUsage">Usage string</param>
public static void PrintUsage(string sUsage)
{
Console.WriteLine("[" + Assembly.GetExecutingAssembly().ManifestModule.ToString() + " Command Line] " +
Assembly.GetExecutingAssembly().GetName().Version);
Console.WriteLine(sUsage);
}
/// <summary>
/// Debugging to see what the args are
/// </summary>
public void PrintArgs()
{
foreach (var sKey in s_dictionaryArgs.Keys)
{
Console.WriteLine(sKey + " [" + GetStringArg(sKey) + "]");
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// AsynchronousOneToOneChannel.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Linq.Parallel
{
/// <summary>
/// This is a bounded channel meant for single-producer/single-consumer scenarios.
/// </summary>
/// <typeparam name="T">Specifies the type of data in the channel.</typeparam>
internal sealed class AsynchronousChannel<T> : IDisposable
{
// The producer will be blocked once the channel reaches a capacity, and unblocked
// as soon as a consumer makes room. A consumer can block waiting until a producer
// enqueues a new element. We use a chunking scheme to adjust the granularity and
// frequency of synchronization, e.g. by enqueueing/dequeueing N elements at a time.
// Because there is only ever a single producer and consumer, we are able to achieve
// efficient and low-overhead synchronization.
//
// In general, the buffer has four logical states:
// FULL <--> OPEN <--> EMPTY <--> DONE
//
// Here is a summary of the state transitions and what they mean:
// * OPEN:
// A buffer starts in the OPEN state. When the buffer is in the READY state,
// a consumer and producer can dequeue and enqueue new elements.
// * OPEN->FULL:
// A producer transitions the buffer from OPEN->FULL when it enqueues a chunk
// that causes the buffer to reach capacity; a producer can no longer enqueue
// new chunks when this happens, causing it to block.
// * FULL->OPEN:
// When the consumer takes a chunk from a FULL buffer, it transitions back from
// FULL->OPEN and the producer is woken up.
// * OPEN->EMPTY:
// When the consumer takes the last chunk from a buffer, the buffer is
// transitioned from OPEN->EMPTY; a consumer can no longer take new chunks,
// causing it to block.
// * EMPTY->OPEN:
// Lastly, when the producer enqueues an item into an EMPTY buffer, it
// transitions to the OPEN state. This causes any waiting consumers to wake up.
// * EMPTY->DONE:
// If the buffer is empty, and the producer is done enqueueing new
// items, the buffer is DONE. There will be no more consumption or production.
//
// Assumptions:
// There is only ever one producer and one consumer operating on this channel
// concurrently. The internal synchronization cannot handle anything else.
//
// ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING **
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
//
// There... got your attention now... just in case you didn't read the comments
// very carefully above, this channel will deadlock, become corrupt, and generally
// make you an unhappy camper if you try to use more than 1 producer or more than
// 1 consumer thread to access this thing concurrently. It's been carefully designed
// to avoid locking, but only because of this restriction...
private readonly T[]?[] _buffer; // The buffer of chunks.
private readonly int _index; // Index of this channel
private volatile int _producerBufferIndex; // Producer's current index, i.e. where to put the next chunk.
private volatile int _consumerBufferIndex; // Consumer's current index, i.e. where to get the next chunk.
private volatile bool _done; // Set to true once the producer is done.
private T[]? _producerChunk; // The temporary chunk being generated by the producer.
private int _producerChunkIndex; // A producer's index into its temporary chunk.
private T[]? _consumerChunk; // The temporary chunk being enumerated by the consumer.
private int _consumerChunkIndex; // A consumer's index into its temporary chunk.
private readonly int _chunkSize; // The number of elements that comprise a chunk.
// These events are used to signal a waiting producer when the consumer dequeues, and to signal a
// waiting consumer when the producer enqueues.
private ManualResetEventSlim? _producerEvent;
private IntValueEvent? _consumerEvent;
// These two-valued ints track whether a producer or consumer _might_ be waiting. They are marked
// volatile because they are used in synchronization critical regions of code (see usage below).
private volatile int _producerIsWaiting;
private volatile int _consumerIsWaiting;
private readonly CancellationToken _cancellationToken;
//-----------------------------------------------------------------------------------
// Initializes a new channel with the specific capacity and chunk size.
//
// Arguments:
// orderingHelper - the ordering helper to use for order preservation
// capacity - the maximum number of elements before a producer blocks
// chunkSize - the granularity of chunking on enqueue/dequeue. 0 means default size.
//
// Notes:
// The capacity represents the maximum number of chunks a channel can hold. That
// means producers will actually block after enqueueing capacity*chunkSize
// individual elements.
//
internal AsynchronousChannel(int index, int chunkSize, CancellationToken cancellationToken, IntValueEvent? consumerEvent) :
this(index, Scheduling.DEFAULT_BOUNDED_BUFFER_CAPACITY, chunkSize, cancellationToken, consumerEvent)
{
}
internal AsynchronousChannel(int index, int capacity, int chunkSize, CancellationToken cancellationToken, IntValueEvent? consumerEvent)
{
if (chunkSize == 0) chunkSize = Scheduling.GetDefaultChunkSize<T>();
Debug.Assert(chunkSize > 0, "chunk size must be greater than 0");
Debug.Assert(capacity > 1, "this impl doesn't support capacity of 1 or 0");
// Initialize a buffer with enough space to hold 'capacity' elements.
// We need one extra unused element as a sentinel to detect a full buffer,
// thus we add one to the capacity requested.
_index = index;
_buffer = new T[capacity + 1][];
_producerBufferIndex = 0;
_consumerBufferIndex = 0;
_producerEvent = new ManualResetEventSlim();
_consumerEvent = consumerEvent;
_chunkSize = chunkSize;
_producerChunk = new T[chunkSize];
_producerChunkIndex = 0;
_cancellationToken = cancellationToken;
}
//-----------------------------------------------------------------------------------
// Checks whether the buffer is full. If the consumer is calling this, they can be
// assured that a true value won't change before the consumer has a chance to dequeue
// elements. That's because only one consumer can run at once. A producer might see
// a true value, however, and then a consumer might transition to non-full, so it's
// not stable for them. Lastly, it's of course possible to see a false value when
// there really is a full queue, it's all dependent on small race conditions.
//
internal bool IsFull
{
get
{
// Read the fields once. One of these is always stable, since the only threads
// that call this are the 1 producer/1 consumer threads.
int producerIndex = _producerBufferIndex;
int consumerIndex = _consumerBufferIndex;
// Two cases:
// 1) Is the producer index one less than the consumer?
// 2) The producer is at the end of the buffer and the consumer at the beginning.
return (producerIndex == consumerIndex - 1) ||
(consumerIndex == 0 && producerIndex == _buffer.Length - 1);
// Note to readers: you might have expected us to consider the case where
// _producerBufferIndex == _buffer.Length && _consumerBufferIndex == 1.
// That is, a producer has gone off the end of the array, but is about to
// wrap around to the 0th element again. We don't need this for a subtle
// reason. It is SAFE for a consumer to think we are non-full when we
// actually are full; it is NOT for a producer; but thankfully, there is
// only one producer, and hence the producer will never see this seemingly
// invalid state. Hence, we're fine producing a false negative. It's all
// based on a race condition we have to deal with anyway.
}
}
//-----------------------------------------------------------------------------------
// Checks whether the buffer is empty. If the producer is calling this, they can be
// assured that a true value won't change before the producer has a chance to enqueue
// an item. That's because only one producer can run at once. A consumer might see
// a true value, however, and then a producer might transition to non-empty.
//
internal bool IsChunkBufferEmpty
{
get
{
// The queue is empty when the producer and consumer are at the same index.
return _producerBufferIndex == _consumerBufferIndex;
}
}
//-----------------------------------------------------------------------------------
// Checks whether the producer is done enqueueing new elements.
//
internal bool IsDone
{
get { return _done; }
}
//-----------------------------------------------------------------------------------
// Used by a producer to flush out any internal buffers that have been accumulating
// data, but which hasn't yet been published to the consumer.
internal void FlushBuffers()
{
TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::FlushBuffers() called",
Environment.CurrentManagedThreadId);
// Ensure that a partially filled chunk is made available to the consumer.
FlushCachedChunk();
}
//-----------------------------------------------------------------------------------
// Used by a producer to signal that it is done producing new elements. This will
// also wake up any consumers that have gone to sleep.
//
internal void SetDone()
{
TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::SetDone() called",
Environment.CurrentManagedThreadId);
// This is set with a volatile write to ensure that, after the consumer
// sees done, they can re-read the enqueued chunks and see the last one we
// enqueued just above.
_done = true;
// We set the event to ensure consumers that may have waited or are
// considering waiting will notice that the producer is done. This is done
// after setting the done flag to facilitate a Dekker-style check/recheck.
//
// Because we can race with threads trying to Dispose of the event, we must
// acquire a lock around our setting, and double-check that the event isn't null.
//
// Update 8/2/2011: Dispose() should never be called with SetDone() concurrently,
// but in order to reduce churn late in the product cycle, we decided not to
// remove the lock.
lock (this)
{
if (_consumerEvent != null)
{
_consumerEvent.Set(_index);
}
}
}
//-----------------------------------------------------------------------------------
// Enqueues a new element to the buffer, possibly blocking in the process.
//
// Arguments:
// item - the new element to enqueue
// timeoutMilliseconds - a timeout (or -1 for no timeout) used in case the buffer
// is full; we return false if it expires
//
// Notes:
// This API will block until the buffer is non-full. This internally buffers
// elements up into chunks, so elements are not immediately available to consumers.
//
internal void Enqueue(T item)
{
Debug.Assert(_producerChunk != null);
// Store the element into our current chunk.
int producerChunkIndex = _producerChunkIndex;
_producerChunk[producerChunkIndex] = item;
// And lastly, if we have filled a chunk, make it visible to consumers.
if (producerChunkIndex == _chunkSize - 1)
{
EnqueueChunk(_producerChunk);
_producerChunk = new T[_chunkSize];
}
_producerChunkIndex = (producerChunkIndex + 1) % _chunkSize;
}
//-----------------------------------------------------------------------------------
// Internal helper to queue a real chunk, not just an element.
//
// Arguments:
// chunk - the chunk to make visible to consumers
// timeoutMilliseconds - an optional timeout; we return false if it expires
//
// Notes:
// This API will block if the buffer is full. A chunk must contain only valid
// elements; if the chunk wasn't filled, it should be trimmed to size before
// enqueueing it for consumers to observe.
//
private void EnqueueChunk(T[] chunk)
{
Debug.Assert(chunk != null);
Debug.Assert(!_done, "can't continue producing after the production is over");
if (IsFull)
WaitUntilNonFull();
Debug.Assert(!IsFull, "expected a non-full buffer");
// We can safely store into the current producer index because we know no consumers
// will be reading from it concurrently.
int bufferIndex = _producerBufferIndex;
_buffer[bufferIndex] = chunk;
// Increment the producer index, taking into count wrapping back to 0. This is a shared
// write; the CLR 2.0 memory model ensures the write won't move before the write to the
// corresponding element, so a consumer won't see the new index but the corresponding
// element in the array as empty.
Interlocked.Exchange(ref _producerBufferIndex, (bufferIndex + 1) % _buffer.Length);
// (If there is a consumer waiting, we have to ensure to signal the event. Unfortunately,
// this requires that we issue a memory barrier: We need to guarantee that the write to
// our producer index doesn't pass the read of the consumer waiting flags; the CLR memory
// model unfortunately permits this reordering. That is handled by using a CAS above.)
if (_consumerIsWaiting == 1 && !IsChunkBufferEmpty)
{
TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waking consumer");
Debug.Assert(_consumerEvent != null);
_consumerIsWaiting = 0;
_consumerEvent.Set(_index);
}
}
//-----------------------------------------------------------------------------------
// Just waits until the queue is non-full.
//
private void WaitUntilNonFull()
{
Debug.Assert(_producerEvent != null);
// We must loop; sometimes the producer event will have been set
// prematurely due to the way waiting flags are managed. By looping,
// we will only return from this method when space is truly available.
do
{
// If the queue is full, we have to wait for a consumer to make room.
// Reset the event to unsignaled state before waiting.
_producerEvent.Reset();
// We have to handle the case where a producer and consumer are racing to
// wait simultaneously. For instance, a producer might see a full queue (by
// reading IsFull just above), but meanwhile a consumer might drain the queue
// very quickly, suddenly seeing an empty queue. This would lead to deadlock
// if we aren't careful. Therefore we check the empty/full state AGAIN after
// setting our flag to see if a real wait is warranted.
Interlocked.Exchange(ref _producerIsWaiting, 1);
// (We have to prevent the reads that go into determining whether the buffer
// is full from moving before the write to the producer-wait flag. Hence the CAS.)
// Because we might be racing with a consumer that is transitioning the
// buffer from full to non-full, we must check that the queue is full once
// more. Otherwise, we might decide to wait and never be woken up (since
// we just reset the event).
if (IsFull)
{
// Assuming a consumer didn't make room for us, we can wait on the event.
TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waiting, buffer full");
_producerEvent.Wait(_cancellationToken);
}
else
{
// Reset the flags, we don't actually have to wait after all.
_producerIsWaiting = 0;
}
}
while (IsFull);
}
//-----------------------------------------------------------------------------------
// Flushes any built up elements that haven't been made available to a consumer yet.
// Only safe to be called by a producer.
//
// Notes:
// This API can block if the channel is currently full.
//
private void FlushCachedChunk()
{
// If the producer didn't fill their temporary working chunk, flushing forces an enqueue
// so that a consumer will see the partially filled chunk of elements.
if (_producerChunk != null && _producerChunkIndex != 0)
{
// Trim the partially-full chunk to an array just big enough to hold it.
Debug.Assert(1 <= _producerChunkIndex && _producerChunkIndex <= _chunkSize);
T[] leftOverChunk = new T[_producerChunkIndex];
Array.Copy(_producerChunk, 0, leftOverChunk, 0, _producerChunkIndex);
// And enqueue the right-sized temporary chunk, possibly blocking if it's full.
EnqueueChunk(leftOverChunk);
_producerChunk = null;
}
}
//-----------------------------------------------------------------------------------
// Dequeues the next element in the queue.
//
// Arguments:
// item - a byref to the location into which we'll store the dequeued element
//
// Return Value:
// True if an item was found, false otherwise.
//
internal bool TryDequeue([MaybeNullWhen(false), AllowNull] ref T item)
{
// Ensure we have a chunk to work with.
if (_consumerChunk == null)
{
if (!TryDequeueChunk(ref _consumerChunk))
{
Debug.Assert(_consumerChunk == null);
return false;
}
_consumerChunkIndex = 0;
}
// Retrieve the current item in the chunk.
Debug.Assert(_consumerChunk != null, "consumer chunk is null");
Debug.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds");
item = _consumerChunk[_consumerChunkIndex];
// And lastly, if we have consumed the chunk, null it out so we'll get the
// next one when dequeue is called again.
++_consumerChunkIndex;
if (_consumerChunkIndex == _consumerChunk.Length)
{
_consumerChunk = null;
}
return true;
}
//-----------------------------------------------------------------------------------
// Internal helper method to dequeue a whole chunk.
//
// Arguments:
// chunk - a byref to the location into which we'll store the chunk
//
// Return Value:
// True if a chunk was found, false otherwise.
//
private bool TryDequeueChunk([NotNullWhen(true)] ref T[]? chunk)
{
// This is the non-blocking version of dequeue. We first check to see
// if the queue is empty. If the caller chooses to wait later, they can
// call the overload with an event.
if (IsChunkBufferEmpty)
{
return false;
}
chunk = InternalDequeueChunk();
return true;
}
//-----------------------------------------------------------------------------------
// Blocking dequeue for the next element. This version of the API is used when the
// caller will possibly wait for a new chunk to be enqueued.
//
// Arguments:
// item - a byref for the returned element
// waitEvent - a byref for the event used to signal blocked consumers
//
// Return Value:
// True if an element was found, false otherwise.
//
// Notes:
// If the return value is false, it doesn't always mean waitEvent will be non-
// null. If the producer is done enqueueing, the return will be false and the
// event will remain null. A caller must check for this condition.
//
// If the return value is false and an event is returned, there have been
// side-effects on the channel. Namely, the flag telling producers a consumer
// might be waiting will have been set. DequeueEndAfterWait _must_ be called
// eventually regardless of whether the caller actually waits or not.
//
internal bool TryDequeue([MaybeNullWhen(false), AllowNull] ref T item, ref bool isDone)
{
isDone = false;
// Ensure we have a buffer to work with.
if (_consumerChunk == null)
{
if (!TryDequeueChunk(ref _consumerChunk, ref isDone))
{
Debug.Assert(_consumerChunk == null);
return false;
}
_consumerChunkIndex = 0;
}
// Retrieve the current item in the chunk.
Debug.Assert(_consumerChunk != null, "consumer chunk is null");
Debug.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds");
item = _consumerChunk[_consumerChunkIndex];
// And lastly, if we have consumed the chunk, null it out.
++_consumerChunkIndex;
if (_consumerChunkIndex == _consumerChunk.Length)
{
_consumerChunk = null;
}
return true;
}
//-----------------------------------------------------------------------------------
// Internal helper method to dequeue a whole chunk. This version of the API is used
// when the caller will wait for a new chunk to be enqueued.
//
// Arguments:
// chunk - a byref for the dequeued chunk
// waitEvent - a byref for the event used to signal blocked consumers
//
// Return Value:
// True if a chunk was found, false otherwise.
//
// Notes:
// If the return value is false, it doesn't always mean waitEvent will be non-
// null. If the producer is done enqueueing, the return will be false and the
// event will remain null. A caller must check for this condition.
//
// If the return value is false and an event is returned, there have been
// side-effects on the channel. Namely, the flag telling producers a consumer
// might be waiting will have been set. DequeueEndAfterWait _must_ be called
// eventually regardless of whether the caller actually waits or not.
//
private bool TryDequeueChunk([NotNullWhen(true)] ref T[]? chunk, ref bool isDone)
{
isDone = false;
// We will register our interest in waiting, and then return an event
// that the caller can use to wait.
while (IsChunkBufferEmpty)
{
// If the producer is done and we've drained the queue, we can bail right away.
if (IsDone)
{
// We have to see if the buffer is empty AFTER we've seen that it's done.
// Otherwise, we would possibly miss the elements enqueued before the
// producer signaled that it's done. This is done with a volatile load so
// that the read of empty doesn't move before the read of done.
if (IsChunkBufferEmpty)
{
// Return isDone=true so callers know not to wait
isDone = true;
return false;
}
}
// We have to handle the case where a producer and consumer are racing to
// wait simultaneously. For instance, a consumer might see an empty queue (by
// reading IsChunkBufferEmpty just above), but meanwhile a producer might fill the queue
// very quickly, suddenly seeing a full queue. This would lead to deadlock
// if we aren't careful. Therefore we check the empty/full state AGAIN after
// setting our flag to see if a real wait is warranted.
Interlocked.Exchange(ref _consumerIsWaiting, 1);
// (We have to prevent the reads that go into determining whether the buffer
// is full from moving before the write to the producer-wait flag. Hence the CAS.)
// Because we might be racing with a producer that is transitioning the
// buffer from empty to non-full, we must check that the queue is empty once
// more. Similarly, if the queue has been marked as done, we must not wait
// because we just reset the event, possibly losing as signal. In both cases,
// we would otherwise decide to wait and never be woken up (i.e. deadlock).
if (IsChunkBufferEmpty && !IsDone)
{
// Note that the caller must eventually call DequeueEndAfterWait to set the
// flags back to a state where no consumer is waiting, whether they choose
// to wait or not.
TraceHelpers.TraceInfo("AsynchronousChannel::DequeueChunk - consumer possibly waiting");
return false;
}
else
{
// Reset the wait flags, we don't need to wait after all. We loop back around
// and recheck that the queue isn't empty, done, etc.
_consumerIsWaiting = 0;
}
}
Debug.Assert(!IsChunkBufferEmpty, "single-consumer should never witness an empty queue here");
chunk = InternalDequeueChunk();
return true;
}
//-----------------------------------------------------------------------------------
// Internal helper method that dequeues a chunk after we've verified that there is
// a chunk available to dequeue.
//
// Return Value:
// The dequeued chunk.
//
// Assumptions:
// The caller has verified that a chunk is available, i.e. the queue is non-empty.
//
private T[] InternalDequeueChunk()
{
Debug.Assert(!IsChunkBufferEmpty);
// We can safely read from the consumer index because we know no producers
// will write concurrently.
int consumerBufferIndex = _consumerBufferIndex;
T[] chunk = _buffer[consumerBufferIndex]!;
// Zero out contents to avoid holding on to memory for longer than necessary. This
// ensures the entire chunk is eligible for GC sooner. (More important for big chunks.)
_buffer[consumerBufferIndex] = null;
// Increment the consumer index, taking into count wrapping back to 0. This is a shared
// write; the CLR 2.0 memory model ensures the write won't move before the write to the
// corresponding element, so a consumer won't see the new index but the corresponding
// element in the array as empty.
Interlocked.Exchange(ref _consumerBufferIndex, (consumerBufferIndex + 1) % _buffer.Length);
// (Unfortunately, this whole sequence requires a memory barrier: We need to guarantee
// that the write to _consumerBufferIndex doesn't pass the read of the wait-flags; the CLR memory
// model sadly permits this reordering. Hence the CAS above.)
if (_producerIsWaiting == 1 && !IsFull)
{
TraceHelpers.TraceInfo("BoundedSingleLockFreeChannel::DequeueChunk - consumer waking producer");
Debug.Assert(_producerEvent != null);
_producerIsWaiting = 0;
_producerEvent.Set();
}
return chunk;
}
//-----------------------------------------------------------------------------------
// Clears the flag set when a blocking Dequeue is called, letting producers know
// the consumer is no longer waiting.
//
internal void DoneWithDequeueWait()
{
// On our way out, be sure to reset the flags.
_consumerIsWaiting = 0;
}
//-----------------------------------------------------------------------------------
// Closes Win32 events possibly allocated during execution.
//
public void Dispose()
{
// We need to take a lock to deal with consumer threads racing to call Dispose
// and producer threads racing inside of SetDone.
//
// Update 8/2/2011: Dispose() should never be called with SetDone() concurrently,
// but in order to reduce churn late in the product cycle, we decided not to
// remove the lock.
lock (this)
{
Debug.Assert(_done, "Expected channel to be done before disposing");
Debug.Assert(_producerEvent != null);
Debug.Assert(_consumerEvent != null);
_producerEvent.Dispose();
_producerEvent = null;
_consumerEvent = null;
}
}
}
}
| |
// 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 Xunit;
namespace System.Text.Tests
{
public class UTF8EncodingDecode
{
public static IEnumerable<object[]> Decode_TestData()
{
// All ASCII chars
for (char c = char.MinValue; c <= 0x7F; c++)
{
yield return new object[] { new byte[] { (byte)c }, 0, 1, c.ToString() };
yield return new object[] { new byte[] { 97, (byte)c, 98 }, 1, 1, c.ToString() };
yield return new object[] { new byte[] { 97, (byte)c, 98 }, 0, 3, "a" + c.ToString() + "b" };
}
// Mixture of ASCII and Unicode
yield return new object[] { new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 }, 0, 8, "FooBA\u0400R" };
yield return new object[] { new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 }, 0, 9, "\u00C0nima\u0300l" };
yield return new object[] { new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 }, 0, 12, "Test\uD803\uDD75Test" };
yield return new object[] { new byte[] { 0, 84, 101, 10, 115, 116, 0, 9, 0, 84, 15, 101, 115, 116, 0 }, 0, 15, "\0Te\nst\0\t\0T\u000Fest\0" };
yield return new object[] { new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 }, 0, 12, "\uD803\uDD75\uD803\uDD75\uD803\uDD75" };
yield return new object[] { new byte[] { 196, 176 }, 0, 2, "\u0130" };
yield return new object[] { new byte[] { 0x61, 0xCC, 0x8A }, 0, 3, "\u0061\u030A" };
yield return new object[] { new byte[] { 0xC2, 0xA4, 0xC3, 0x90, 0x61, 0x52, 0x7C, 0x7B, 0x41, 0x6E, 0x47, 0x65, 0xC2, 0xA3, 0xC2, 0xA4 }, 0, 16, "\u00A4\u00D0aR|{AnGe\u00A3\u00A4" };
yield return new object[] { new byte[] { 0x00, 0x7F }, 0, 2, "\u0000\u007F" };
yield return new object[] { new byte[] { 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F }, 0, 14, "\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F" };
yield return new object[] { new byte[] { 0xC2, 0x80, 0xDF, 0xBF }, 0, 4, "\u0080\u07FF" };
yield return new object[] { new byte[] { 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF }, 0, 16, "\u0080\u07FF\u0080\u07FF\u0080\u07FF\u0080\u07FF" };
yield return new object[] { new byte[] { 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF }, 0, 6, "\u0800\u0FFF" };
yield return new object[] { new byte[] { 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF, 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF, 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF }, 0, 18, "\u0800\u0FFF\u0800\u0FFF\u0800\u0FFF" };
yield return new object[] { new byte[] { 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF }, 0, 6, "\u1000\uCFFF" };
yield return new object[] { new byte[] { 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF, 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF, 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF }, 0, 18, "\u1000\uCFFF\u1000\uCFFF\u1000\uCFFF" };
yield return new object[] { new byte[] { 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF }, 0, 6, "\uD000\uD7FF" };
yield return new object[] { new byte[] { 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF, 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF, 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF }, 0, 18, "\uD000\uD7FF\uD000\uD7FF\uD000\uD7FF" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF }, 0, 8, "\uD800\uDC00\uD8BF\uDFFF" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF }, 0, 16, "\uD800\uDC00\uD8BF\uDFFF\uD800\uDC00\uD8BF\uDFFF" };
yield return new object[] { new byte[] { 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF }, 0, 8, "\uD8C0\uDC00\uDBBF\uDFFF" };
yield return new object[] { new byte[] { 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF, 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF }, 0, 16, "\uD8C0\uDC00\uDBBF\uDFFF\uD8C0\uDC00\uDBBF\uDFFF" };
yield return new object[] { new byte[] { 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF }, 0, 8, "\uDBC0\uDC00\uDBFF\uDFFF" };
yield return new object[] { new byte[] { 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF, 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF }, 0, 16, "\uDBC0\uDC00\uDBFF\uDFFF\uDBC0\uDC00\uDBFF\uDFFF" };
// Long ASCII strings
yield return new object[] { new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, 0, 10, "TestString" };
yield return new object[] { new byte[] { 84, 101, 115, 116, 84, 101, 115, 116 }, 0, 8, "TestTest" };
// Control codes
yield return new object[] { new byte[] { 0x1F, 0x10, 0x00, 0x09 }, 0, 4, "\u001F\u0010\u0000\u0009" };
yield return new object[] { new byte[] { 0x1F, 0x00, 0x10, 0x09 }, 0, 4, "\u001F\u0000\u0010\u0009" };
yield return new object[] { new byte[] { 0x00, 0x1F, 0x10, 0x09 }, 0, 4, "\u0000\u001F\u0010\u0009" };
// BOM
yield return new object[] { new byte[] { 0xEF, 0xBB, 0xBF, 0x41 }, 0, 4, "\uFEFF\u0041" };
// U+FDD0 - U+FDEF
yield return new object[] { new byte[] { 0xEF, 0xB7, 0x90, 0xEF, 0xB7, 0xAF }, 0, 6, "\uFDD0\uFDEF" };
// 2 byte encoding
yield return new object[] { new byte[] { 0xC3, 0xA1 }, 0, 2, "\u00E1" };
yield return new object[] { new byte[] { 0xC3, 0x85 }, 0, 2, "\u00C5" };
// 3 byte encoding
yield return new object[] { new byte[] { 0xE8, 0x80, 0x80 }, 0, 3, "\u8000" };
yield return new object[] { new byte[] { 0xE2, 0x84, 0xAB }, 0, 3, "\u212B" };
// Surrogate pairs
yield return new object[] { new byte[] { 240, 144, 128, 128 }, 0, 4, "\uD800\uDC00" };
yield return new object[] { new byte[] { 97, 240, 144, 128, 128, 98 }, 0, 6, "a\uD800\uDC00b" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x8F, 0xBF }, 0, 4, "\uD800\uDFFF" };
yield return new object[] { new byte[] { 0xF4, 0x8F, 0xB0, 0x80 }, 0, 4, "\uDBFF\uDC00" };
yield return new object[] { new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, 0, 4, "\uDBFF\uDFFF" };
yield return new object[] { new byte[] { 0xF3, 0xB0, 0x80, 0x80 }, 0, 4, "\uDB80\uDC00" };
// High BMP non-chars
yield return new object[] { new byte[] { 239, 191, 189 }, 0, 3, "\uFFFD" };
yield return new object[] { new byte[] { 239, 191, 190 }, 0, 3, "\uFFFE" };
yield return new object[] { new byte[] { 239, 191, 191 }, 0, 3, "\uFFFF" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0xAE }, 0, 3, "\uFFEE" };
yield return new object[] { new byte[] { 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF, 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF, 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF }, 0, 18, "\uE000\uFFFF\uE000\uFFFF\uE000\uFFFF" };
// Empty strings
yield return new object[] { new byte[0], 0, 0, string.Empty };
yield return new object[] { new byte[10], 10, 0, string.Empty };
yield return new object[] { new byte[10], 0, 0, string.Empty };
}
[Theory]
[MemberData(nameof(Decode_TestData))]
[ActiveIssue("https://github.com/dotnet/corefx/issues/20525", TargetFrameworkMonikers.UapAot)]
public void Decode(byte[] bytes, int index, int count, string expected)
{
EncodingHelpers.Decode(new UTF8Encoding(true, false), bytes, index, count, expected);
EncodingHelpers.Decode(new UTF8Encoding(false, false), bytes, index, count, expected);
EncodingHelpers.Decode(new UTF8Encoding(false, true), bytes, index, count, expected);
EncodingHelpers.Decode(new UTF8Encoding(true, true), bytes, index, count, expected);
}
public static IEnumerable<object[]> Decode_InvalidBytes_TestData()
{
yield return new object[] { new byte[] { 196, 84, 101, 115, 116, 196, 196, 196, 176, 176, 84, 101, 115, 116, 176 }, 0, 15, "\uFFFDTest\uFFFD\uFFFD\u0130\uFFFDTest\uFFFD" };
yield return new object[] { new byte[] { 240, 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 240 }, 0, 12, "\uFFFD\uD803\uDD75\uD803\uDD75\uFFFD\uFFFD" };
// Invalid surrogate bytes
byte[] validSurrogateBytes = new byte[] { 240, 144, 128, 128 };
yield return new object[] { validSurrogateBytes, 0, 3, "\uFFFD" };
yield return new object[] { validSurrogateBytes, 1, 3, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { validSurrogateBytes, 0, 2, "\uFFFD" };
yield return new object[] { validSurrogateBytes, 1, 2, "\uFFFD\uFFFD" };
yield return new object[] { validSurrogateBytes, 2, 2, "\uFFFD\uFFFD" };
yield return new object[] { validSurrogateBytes, 2, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xA0, 0x80 }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xAF, 0xBF }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xB0, 0x80 }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xBF, 0xBF }, 0, 3, "\uFFFD\uFFFD" };
// Invalid surrogate pair (low/low, high/high, low/high)
yield return new object[] { new byte[] { 0xED, 0xA0, 0x80, 0xED, 0xAF, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xB0, 0x80, 0xED, 0xB0, 0x80 }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xA0, 0x80, 0xED, 0xA0, 0x80 }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD" };
// Too high scalar value in surrogates
yield return new object[] { new byte[] { 0xED, 0xA0, 0x80, 0xEE, 0x80, 0x80 }, 0, 6, "\uFFFD\uFFFD\uE000" };
yield return new object[] { new byte[] { 0xF4, 0x90, 0x80, 0x80 }, 0, 4, "\uFFFD\uFFFD\uFFFD" };
// These are examples of overlong sequences. This can cause security
// vulnerabilities (e.g. MS00-078) so it is important we parse these as invalid.
yield return new object[] { new byte[] { 0xC0 }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xC0, 0xAF }, 0, 2, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0x80, 0xBF }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x80, 0x80, 0xBF }, 0, 4, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF8, 0x80, 0x80, 0x80, 0xBF }, 0, 5, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xFC, 0x80, 0x80, 0x80, 0x80, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xC0, 0xBF }, 0, 2, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0x9C, 0x90 }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x8F, 0xA4, 0x80 }, 0, 4, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xEF, 0x41 }, 0, 2, "\uFFFD\u0041" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0xAE }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0x41 }, 0, 3, "\uFFFD\u0041" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0x61 }, 0, 3, "\uFFFD\u0061" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0xEF, 0xBF, 0xAE }, 0, 5, "\uFFFD\uFFEE" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0xC0, 0xBF }, 0, 4, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0xC4, 0x80 }, 0, 3, "\uFFFD\u0100" };
yield return new object[] { new byte[] { 176 }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 196 }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xA4, 0xD0, 0x61, 0x52, 0x7C, 0x7B, 0x41, 0x6E, 0x47, 0x65, 0xA3, 0xA4 }, 0, 12, "\uFFFD\uFFFD\u0061\u0052\u007C\u007B\u0041\u006E\u0047\u0065\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xA3 }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xA3, 0xA4 }, 0, 2, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x65, 0xA3, 0xA4 }, 0, 3, "\u0065\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x47, 0x65, 0xA3, 0xA4 }, 0, 4, "\u0047\u0065\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xA4, 0xD0, 0x61, 0xA3, 0xA4 }, 0, 5, "\uFFFD\uFFFD\u0061\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xA4, 0xD0, 0x61, 0xA3 }, 0, 4, "\uFFFD\uFFFD\u0061\uFFFD" };
yield return new object[] { new byte[] { 0xD0, 0x61, 0xA3 }, 0, 3, "\uFFFD\u0061\uFFFD" };
yield return new object[] { new byte[] { 0xA4, 0x61, 0xA3 }, 0, 3, "\uFFFD\u0061\uFFFD" };
yield return new object[] { new byte[] { 0xD0, 0x61, 0x52, 0xA3 }, 0, 4, "\uFFFD\u0061\u0052\uFFFD" };
yield return new object[] { new byte[] { 0xAA }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xAA, 0x41 }, 0, 2, "\uFFFD\u0041" };
yield return new object[] { new byte[] { 0xEF, 0xFF, 0xEE }, 0, 3, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xEF, 0xFF, 0xAE }, 0, 3, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x80, 0x90, 0xA0, 0xB0, 0xC1 }, 0, 5, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x80, 0x90, 0xA0, 0xB0, 0xC1 }, 0, 15, "\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x80, 0x90, 0xA0, 0xB0, 0xC1, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F }, 0, 15, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F" };
yield return new object[] { new byte[] { 0xC2, 0x7F, 0xC2, 0xC0, 0xDF, 0x7F, 0xDF, 0xC0 }, 0, 8, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xC2, 0xDF }, 0, 2, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x80, 0x80, 0xC1, 0x80, 0xC1, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xC2, 0x7F, 0xC2, 0xC0, 0x7F, 0x7F, 0x7F, 0x7F, 0xC3, 0xA1, 0xDF, 0x7F, 0xDF, 0xC0 }, 0, 14, "\uFFFD\u007F\uFFFD\uFFFD\u007F\u007F\u007F\u007F\u00E1\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0xA0, 0x7F, 0xE0, 0xA0, 0xC0, 0xE0, 0xBF, 0x7F, 0xE0, 0xBF, 0xC0 }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0x9F, 0x80, 0xE0, 0xC0, 0x80, 0xE0, 0x9F, 0xBF, 0xE0, 0xC0, 0xBF }, 0, 12, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0xA0, 0x7F, 0xE0, 0xA0, 0xC0, 0x7F, 0xE0, 0xBF, 0x7F, 0xC3, 0xA1, 0xE0, 0xBF, 0xC0 }, 0, 15, "\uFFFD\u007F\uFFFD\uFFFD\u007F\uFFFD\u007F\u00E1\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE1, 0x80, 0x7F, 0xE1, 0x80, 0xC0, 0xE1, 0xBF, 0x7F, 0xE1, 0xBF, 0xC0, 0xEC, 0x80, 0x7F, 0xEC, 0x80, 0xC0, 0xEC, 0xBF, 0x7F, 0xEC, 0xBF, 0xC0 }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE1, 0x7F, 0x80, 0xE1, 0xC0, 0x80, 0xE1, 0x7F, 0xBF, 0xE1, 0xC0, 0xBF, 0xEC, 0x7F, 0x80, 0xEC, 0xC0, 0x80, 0xEC, 0x7F, 0xBF, 0xEC, 0xC0, 0xBF }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0x80, 0x7F, 0xED, 0x80, 0xC0, 0xED, 0x9F, 0x7F, 0xED, 0x9F, 0xC0 }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0x7F, 0x80, 0xED, 0xA0, 0x80, 0xED, 0x7F, 0xBF, 0xED, 0xA0, 0xBF }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0x7F, 0x80, 0xED, 0xA0, 0x80, 0xE8, 0x80, 0x80, 0xED, 0x7F, 0xBF, 0xED, 0xA0, 0xBF }, 0, 15, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u8000\uFFFD\u007F\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xEE, 0x80, 0x7F, 0xEE, 0x80, 0xC0, 0xEE, 0xBF, 0x7F, 0xEE, 0xBF, 0xC0, 0xEF, 0x80, 0x7F, 0xEF, 0x80, 0xC0, 0xEF, 0xBF, 0x7F, 0xEF, 0xBF, 0xC0 }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xEE, 0x7F, 0x80, 0xEE, 0xC0, 0x80, 0xEE, 0x7F, 0xBF, 0xEE, 0xC0, 0xBF, 0xEF, 0x7F, 0x80, 0xEF, 0xC0, 0x80, 0xEF, 0x7F, 0xBF, 0xEF, 0xC0, 0xBF }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x80, 0x7F, 0xF0, 0x90, 0x80, 0xC0, 0xF0, 0xBF, 0xBF, 0x7F, 0xF0, 0xBF, 0xBF, 0xC0 }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x7F, 0x80, 0xF0, 0x90, 0xC0, 0x80, 0xF0, 0x90, 0x7F, 0xBF, 0xF0, 0x90, 0xC0, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x8F, 0x80, 0x80, 0xF0, 0xC0, 0x80, 0x80, 0xF0, 0x8F, 0xBF, 0xBF, 0xF0, 0xC0, 0xBF, 0xBF }, 0, 16, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF1, 0x80, 0x80, 0x7F, 0xF1, 0x80, 0x80, 0xC0, 0xF1, 0xBF, 0xBF, 0x7F, 0xF1, 0xBF, 0xBF, 0xC0, 0xF3, 0x80, 0x80, 0x7F, 0xF3, 0x80, 0x80, 0xC0, 0xF3, 0xBF, 0xBF, 0x7F, 0xF3, 0xBF, 0xBF, 0xC0 }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF1, 0x80, 0x7F, 0x80, 0xF1, 0x80, 0xC0, 0x80, 0xF1, 0x80, 0x7F, 0xBF, 0xF1, 0x80, 0xC0, 0xBF, 0xF3, 0x80, 0x7F, 0x80, 0xF3, 0x80, 0xC0, 0x80, 0xF3, 0x80, 0x7F, 0xBF, 0xF3, 0x80, 0xC0, 0xBF }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF1, 0x7F, 0x80, 0x80, 0xF1, 0xC0, 0x80, 0x80, 0xF1, 0x7F, 0xBF, 0xBF, 0xF1, 0xC0, 0xBF, 0xBF, 0xF3, 0x7F, 0x80, 0x80, 0xF3, 0xC0, 0x80, 0x80, 0xF3, 0x7F, 0xBF, 0xBF, 0xF3, 0xC0, 0xBF, 0xBF }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF4, 0x80, 0x80, 0x7F, 0xF4, 0x80, 0x80, 0xC0, 0xF4, 0x8F, 0xBF, 0x7F, 0xF4, 0x8F, 0xBF, 0xC0 }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF4, 0x80, 0x7F, 0x80, 0xF4, 0x80, 0xC0, 0x80, 0xF4, 0x80, 0x7F, 0xBF, 0xF4, 0x80, 0xC0, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF4, 0x7F, 0x80, 0x80, 0xF4, 0x90, 0x80, 0x80, 0xF4, 0x7F, 0xBF, 0xBF, 0xF4, 0x90, 0xBF, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
}
[Theory]
[MemberData(nameof(Decode_InvalidBytes_TestData))]
public static void Decode_InvalidBytes(byte[] bytes, int index, int count, string expected)
{
EncodingHelpers.Decode(new UTF8Encoding(true, false), bytes, index, count, expected);
EncodingHelpers.Decode(new UTF8Encoding(false, false), bytes, index, count, expected);
NegativeEncodingTests.Decode_Invalid(new UTF8Encoding(false, true), bytes, index, count);
NegativeEncodingTests.Decode_Invalid(new UTF8Encoding(true, true), bytes, index, count);
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using System.IO;
using System.Text;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
public partial class CReaderFactory : CFactory
{
//Enum defined for different API calls. This is superset of the actual reader types.
protected enum ReaderOverload
{
StreamReader,
StringReader,
FileStream,
MemoryStream,
CoreReader,
CustomReader
};
public enum ReadThru
{
XmlReader,
TextReader,
Stream
};
//The required objects that will be used during the variation processing.
private XmlReaderSettings _settings = new XmlReaderSettings();
private XmlReaderSettings _underlyingSettings = new XmlReaderSettings();
private Encoding _enc = null;
private Stream _stream = null;
private string _baseUri = null;
private TextReader _textReader = null;
private ReaderOverload _overload;
private XmlReader _factoryReader = null;
private XmlReader _underlyingReader = null;
protected short numEventHandlers = 0;
// Parse Optional data specific to reader tests.
protected override void PreTest()
{
SetupSettings();
Log("--Setup Settings Done");
SetupReadOverload();
Log("--Setup ReadOverload Done");
SetupEncoding();
Log("--Setup Encoding Done");
SetupBaseUri();
Log("--Setup BaseUri Done");
pstate = TestState.PreTest;
}
protected override void PostTest()
{
//Cleanup and release files you may hold.
if (_stream != null)
_stream.Dispose();
if (_textReader != null)
_textReader.Dispose();
if (_underlyingReader != null)
_underlyingReader.Dispose();
if (_factoryReader != null)
_factoryReader.Dispose();
pstate = TestState.Complete;
}
/// <summary>
/// This method will test the read based on different settings.
/// It will call the correct overload and set the state properly.
/// </summary>
protected override void Test()
{
CError.WriteLine("Testing : " + TestFileName);
string tempStr = null;
switch (_overload)
{
case ReaderOverload.StreamReader:
_textReader = new StreamReader(FilePathUtil.getStream(GetFile(TestFileName)));
CreateReader(ReadThru.TextReader);
break;
case ReaderOverload.StringReader:
StreamReader sr = new StreamReader(FilePathUtil.getStream(GetFile(TestFileName)));
tempStr = sr.ReadToEnd();
sr.Dispose();
_textReader = new StringReader(tempStr);
CreateReader(ReadThru.TextReader);
break;
case ReaderOverload.FileStream:
_stream = FilePathUtil.getStream(TestFileName);
CreateReader(ReadThru.Stream);
break;
case ReaderOverload.MemoryStream:
StreamReader sr1 = new StreamReader(FilePathUtil.getStream(GetFile(TestFileName)));
tempStr = sr1.ReadToEnd();
sr1.Dispose();
byte[] bits = _enc.GetBytes(tempStr);
_stream = new MemoryStream(bits);
CreateReader(ReadThru.Stream);
break;
case ReaderOverload.CoreReader:
_underlyingSettings.DtdProcessing = DtdProcessing.Ignore;
_underlyingSettings.ConformanceLevel = _settings.ConformanceLevel;
StringReader strr = new StringReader(new StreamReader(FilePathUtil.getStream(GetFile(TestFileName))).ReadToEnd());
_underlyingReader = ReaderHelper.CreateReader(_overload.ToString(),
strr,
false,
null,
_underlyingSettings,
(_settings.ConformanceLevel == ConformanceLevel.Fragment)); //should this be settings or underlyingSettings?
CError.Compare(_underlyingReader != null, "ReaderHelper returned null Reader");
CreateReader(ReadThru.XmlReader);
break;
case ReaderOverload.CustomReader:
if (AsyncUtil.IsAsyncEnabled)
{
pstate = TestState.Skip;
return;
}
if (_settings.ConformanceLevel != ConformanceLevel.Fragment)
_underlyingReader = new CustomReader(FilePathUtil.getStream(GetFile(TestFileName)), false);
else
_underlyingReader = new CustomReader(FilePathUtil.getStream(GetFile(TestFileName)), true);
CError.Compare(_underlyingReader != null, "ReaderHelper returned null Reader");
CreateReader(ReadThru.XmlReader);
break;
default:
throw new CTestFailedException("Unknown ReaderOverload: " + _overload);
}
if (_underlyingReader != null)
CError.WriteLineIgnore("Type of Reader : " + _underlyingReader.GetType());
if (pstate == TestState.Pass) return;
CError.Compare(pstate, TestState.CreateSuccess, "Invalid State after Create: " + pstate);
//By this time the factory Reader is already set up correctly. So we must go Consume it now.
CError.Compare(pstate != TestState.Pass && pstate == TestState.CreateSuccess, "Invalid state before Consuming Reader: " + pstate);
//Call TestReader to Consume Reader;
TestReader();
if (pstate == TestState.Pass) return;
CError.Compare(pstate != TestState.Pass && pstate == TestState.Consume, "Invalid state after Consuming Reader: " + pstate);
}
protected void TestReader()
{
pstate = TestState.Consume;
try
{
ConsumeReader(_factoryReader);
if (!IsVariationValid)
{
//Invalid Case didnt throw exception.
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException("Invalid Variation didnt throw exception");
}
else
{
pstate = TestState.Pass;
}
}
finally
{
if (_factoryReader != null)
_factoryReader.Dispose();
}
//If you are not in PASS state at this point you are in Error.
if (pstate != TestState.Pass)
pstate = TestState.Error;
}
protected void CompareSettings()
{
Log("Comparing ErrorSettings");
XmlReaderSettings actual = _factoryReader.Settings;
if (actual == null)
throw new CTestFailedException("Factory Reader Settings returned null");
CError.Compare(actual.CheckCharacters, _settings.CheckCharacters, "CheckCharacters");
CError.Compare(actual.IgnoreComments, _settings.IgnoreComments, "IgnoreComments");
CError.Compare(actual.IgnoreProcessingInstructions, _settings.IgnoreProcessingInstructions, "IgnorePI");
CError.Compare(actual.IgnoreWhitespace, _settings.IgnoreWhitespace, "IgnoreWhitespace");
CError.Compare(actual.LineNumberOffset, _settings.LineNumberOffset, "LinenumberOffset");
CError.Compare(actual.LinePositionOffset, _settings.LinePositionOffset, "LinePositionOffset");
}
protected void ConsumeReader(XmlReader reader)
{
while (reader.Read())
{
string x = reader.Name + reader.NodeType + reader.Value;
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.HasAttributes)
{
reader.MoveToFirstAttribute();
int index = 0;
reader.MoveToAttribute(index);
index++;
while (reader.MoveToNextAttribute())
{
string name = reader.Name;
string value;
value = reader.GetAttribute(index);
value = reader.GetAttribute(name);
value = reader.GetAttribute(name, null);
reader.ReadAttributeValue();
reader.MoveToAttribute(index);
reader.MoveToAttribute(name, null);
index++;
}
}
}
if (reader.NodeType == XmlNodeType.EndElement)
{
reader.Skip();
}
}
}
/// <summary>
/// This method calls the Create Method on the XmlReader and puts the state in CreateSuccess or TestPass.
/// It goes in PASS also if the reader threw an expected error. In all other cases it should throw
/// TestFailedException.
/// </summary>
/// <param name="readThru">This param determines which overload to call.
/// In future on multiple overloads we can make this param
/// an enum which can be set using the spec file data</param>
protected void CreateReader(ReadThru readThru)
{
//Assumption is that the Create method doesnt throw NullReferenceException and
//it is not the goal of this framework to test if they are thrown anywhere.
//but if they are thrown thats a problem and they shouldnt be caught but exposed.
try
{
switch (readThru)
{
case ReadThru.TextReader:
_factoryReader = ReaderHelper.Create(_textReader, _settings, _baseUri);
break;
case ReadThru.XmlReader:
_factoryReader = ReaderHelper.Create(_underlyingReader, _settings);
break;
case ReadThru.Stream:
_factoryReader = ReaderHelper.Create(_stream, _settings);
break;
default:
throw new CTestFailedException("Unknown ReadThru type: " + readThru);
}
pstate = TestState.CreateSuccess;
}
catch (ArgumentNullException ane)
{
Log(ane.Message);
Log(ane.StackTrace);
if (!IsVariationValid)
{
if (!CheckException(ane))
{
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException(
"Argument Null Exception Thrown in CreateMethod, is your variation data correct?");
}
else
{
//This means that the Exception was checked and everything is fine.
pstate = TestState.Pass;
}
}
else
{
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException(
"Argument Null Exception Thrown in CreateMethod, is your variation data correct?");
}
}
}
/// <summary>
/// Setup Settings basically reads the variation info and populates the info block.
/// <ConformanceLevel>Fragment</ConformanceLevel>
/// <CheckCharacters>true</CheckCharacters>
/// <ReaderType>Dtd</ReaderType>
/// <NameTable>new</NameTable>
/// <LineNumberOffset>1</LineNumberOffset>
/// <LinePositionOffset>0</LinePositionOffset>
/// <IgnoreInlineSchema>false</IgnoreInlineSchema>
/// <IgnoreSchemaLocation>true</IgnoreSchemaLocation>
/// <IgnoreIdentityConstraints>false</IgnoreIdentityConstraints>
/// <IgnoreValidationWarnings>true</IgnoreValidationWarnings>
/// <Schemas>2</Schemas>
/// <ValidationEventHandler>0</ValidationEventHandler>
/// <ProhibitDtd>true</ProhibitDtd>
/// <IgnoreWS>false</IgnoreWS>
/// <IgnorePI>true</IgnorePI>
/// <IgnoreCS>true</IgnoreCS>
/// </summary>
private void SetupSettings()
{
_settings = new XmlReaderSettings();
_callbackWarningCount1 = 0;
_callbackWarningCount2 = 0;
_callbackErrorCount1 = 0;
_callbackErrorCount2 = 0;
//Conformance Level
_settings.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), ReadFilterCriteria("ConformanceLevel", true));
//CheckCharacters
_settings.CheckCharacters = Boolean.Parse(ReadFilterCriteria("CheckCharacters", true));
//Reader Type : Parse and then set the Xsd or Dtd validation accordingly.
string readertype = ReadFilterCriteria("ReaderType", true);
switch (readertype)
{
case "Dtd":
case "Xsd":
case "Binary":
throw new CTestSkippedException("Skipped: ReaderType " + readertype);
case "Core":
break;
default:
throw new CTestFailedException("Unexpected ReaderType Criteria");
}
//Nametable
string nt = ReadFilterCriteria("NameTable", true);
switch (nt)
{
case "new":
_settings.NameTable = new NameTable();
break;
case "null":
_settings.NameTable = null;
break;
case "custom":
_settings.NameTable = new MyNameTable();
break;
default:
throw new CTestFailedException("Unexpected Nametable Criteria : " + nt);
}
//Line number
_settings.LineNumberOffset = Int32.Parse(ReadFilterCriteria("LineNumberOffset", true));
//Line position
_settings.LinePositionOffset = Int32.Parse(ReadFilterCriteria("LinePositionOffset", true));
_settings.IgnoreProcessingInstructions = Boolean.Parse(ReadFilterCriteria("IgnorePI", true));
_settings.IgnoreComments = Boolean.Parse(ReadFilterCriteria("IgnoreComments", true));
_settings.IgnoreWhitespace = Boolean.Parse(ReadFilterCriteria("IgnoreWhiteSpace", true));
}//End of SetupSettings
//Validation Event Handlers and their Counts for Reader to verify
private int _callbackWarningCount1 = 0;
private int _callbackWarningCount2 = 0;
private int _callbackErrorCount1 = 0;
private int _callbackErrorCount2 = 0;
public int EventWarningCount1
{
get { return _callbackWarningCount1; }
}
public int EventWarningCount2
{
get { return _callbackWarningCount2; }
}
public int EventErrorCount1
{
get { return _callbackErrorCount1; }
}
public int EventErrorCount2
{
get { return _callbackErrorCount2; }
}
/// <summary>
/// Sets up the Correct Read Overload Method to be called.
/// </summary>
public void SetupReadOverload()
{
string ol = ReadFilterCriteria("Load", true);
if (ol == "HTTPStream" || ol == "FileName" || ol == "XmlTextReader" || ol == "XmlValidatingReader" || ol == "CoreValidatingReader"
|| ol == "CoreXsdReader" || ol == "XmlBinaryReader" || ol == "XPathNavigatorReader" || ol == "XmlNodeReader" || ol == "XmlNodeReaderDD"
|| ol == "XsltReader")
{
throw new CTestSkippedException("Skipped: OverLoad " + ol);
}
_overload = (ReaderOverload)Enum.Parse(typeof(ReaderOverload), ol);
}
public void SetupBaseUri()
{
string bUri = ReadFilterCriteria("BaseUri", true);
switch (bUri)
{
case "valid":
_baseUri = GetPath(TestFileName, false);
Log("Setting baseuri = " + _baseUri);
break;
case "~null":
break;
default:
_baseUri = "";
break;
}
}
public void SetupEncoding()
{
string strEnc = ReadFilterCriteria("Encoding", true);
if (strEnc != "~null")
_enc = Encoding.GetEncoding(strEnc);
}
//Custom Nametable
public class MyNameTable : XmlNameTable
{
private NameTable _nt = new NameTable();
public override string Get(string array)
{
return _nt.Get(array);
}
public override string Get(char[] array, int offset, int length)
{
return _nt.Get(array, offset, length);
}
public override string Add(string array)
{
return _nt.Add(array);
}
public override string Add(char[] array, int offset, int length)
{
return _nt.Add(array, offset, length);
}
}
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* 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.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.OneD
{
/// <summary>
/// <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p>
/// <author>Sean Owen</author>
/// @see Code93Reader
/// </summary>
public sealed class Code39Reader : OneDReader
{
internal static String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
// Note this lacks '*' compared to ALPHABET_STRING
private static readonly String CHECK_DIGIT_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%";
/// <summary>
/// Returns a string with all possible characters
/// </summary>
public static string Alphabet
{
get { return ALPHABET_STRING; }
}
/// <summary>
/// These represent the encodings of characters, as patterns of wide and narrow bars.
/// The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
/// with 1s representing "wide" and 0s representing narrow.
/// </summary>
internal static int[] CHARACTER_ENCODINGS = {
0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
0x0A8, 0x0A2, 0x08A, 0x02A // $-%
};
internal static readonly int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
private readonly bool usingCheckDigit;
private readonly bool extendedMode;
private readonly StringBuilder decodeRowResult;
private readonly int[] counters;
/// <summary>
/// Creates a reader that assumes all encoded data is data, and does not treat the final
/// character as a check digit. It will not decoded "extended Code 39" sequences.
/// </summary>
public Code39Reader()
:this(false)
{
}
/// <summary>
/// Creates a reader that can be configured to check the last character as a check digit.
/// It will not decoded "extended Code 39" sequences.
/// </summary>
/// <param name="usingCheckDigit">if true, treat the last data character as a check digit, not
/// data, and verify that the checksum passes.</param>
public Code39Reader(bool usingCheckDigit)
:this(usingCheckDigit, false)
{
}
/// <summary>
/// Creates a reader that can be configured to check the last character as a check digit,
/// or optionally attempt to decode "extended Code 39" sequences that are used to encode
/// the full ASCII character set.
/// </summary>
/// <param name="usingCheckDigit">if true, treat the last data character as a check digit, not
/// data, and verify that the checksum passes.</param>
/// <param name="extendedMode">if true, will attempt to decode extended Code 39 sequences in the text.</param>
public Code39Reader(bool usingCheckDigit, bool extendedMode)
{
this.usingCheckDigit = usingCheckDigit;
this.extendedMode = extendedMode;
decodeRowResult = new StringBuilder(20);
counters = new int[9];
}
/// <summary>
/// <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
/// </summary>
/// <param name="rowNumber">row number from top of the row</param>
/// <param name="row">the black/white pixel data of the row</param>
/// <param name="hints">decode hints</param>
/// <returns><see cref="Result"/>containing encoded string and start/end of barcode</returns>
override public Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
for (var index = 0; index < counters.Length; index++)
counters[index] = 0;
decodeRowResult.Length = 0;
int[] start = findAsteriskPattern(row, counters);
if (start == null)
return null;
// Read off white space
int nextStart = row.getNextSet(start[1]);
int end = row.Size;
char decodedChar;
int lastStart;
do
{
if (!recordPattern(row, nextStart, counters))
return null;
int pattern = toNarrowWidePattern(counters);
if (pattern < 0)
{
return null;
}
if (!patternToChar(pattern, out decodedChar))
return null;
decodeRowResult.Append(decodedChar);
lastStart = nextStart;
foreach (int counter in counters)
{
nextStart += counter;
}
// Read off white space
nextStart = row.getNextSet(nextStart);
} while (decodedChar != '*');
decodeRowResult.Length = decodeRowResult.Length - 1; // remove asterisk
// Look for whitespace after pattern:
int lastPatternSize = 0;
foreach (int counter in counters)
{
lastPatternSize += counter;
}
int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if (nextStart != end && (whiteSpaceAfterEnd << 1) < lastPatternSize)
{
return null;
}
// overriding constructor value is possible
bool useCode39CheckDigit = usingCheckDigit;
if (hints != null && hints.ContainsKey(DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT))
{
useCode39CheckDigit = (bool) hints[DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT];
}
if (useCode39CheckDigit)
{
int max = decodeRowResult.Length - 1;
int total = 0;
for (int i = 0; i < max; i++)
{
total += CHECK_DIGIT_STRING.IndexOf(decodeRowResult[i]);
}
if (decodeRowResult[max] != CHECK_DIGIT_STRING[total % 43])
{
return null;
}
decodeRowResult.Length = max;
}
if (decodeRowResult.Length == 0)
{
// false positive
return null;
}
// overriding constructor value is possible
bool useCode39ExtendedMode = extendedMode;
if (hints != null && hints.ContainsKey(DecodeHintType.USE_CODE_39_EXTENDED_MODE))
{
useCode39ExtendedMode = (bool)hints[DecodeHintType.USE_CODE_39_EXTENDED_MODE];
}
String resultString;
if (useCode39ExtendedMode)
{
resultString = decodeExtended(decodeRowResult.ToString());
if (resultString == null)
{
if (hints != null &&
hints.ContainsKey(DecodeHintType.RELAXED_CODE_39_EXTENDED_MODE) &&
Convert.ToBoolean(hints[DecodeHintType.RELAXED_CODE_39_EXTENDED_MODE]))
resultString = decodeRowResult.ToString();
else
return null;
}
}
else
{
resultString = decodeRowResult.ToString();
}
float left = (start[1] + start[0])/2.0f;
float right = lastStart + lastPatternSize / 2.0f;
var resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)
? null
: (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(left, rowNumber));
resultPointCallback(new ResultPoint(right, rowNumber));
}
return new Result(
resultString,
null,
new[]
{
new ResultPoint(left, rowNumber),
new ResultPoint(right, rowNumber)
},
BarcodeFormat.CODE_39);
}
private static int[] findAsteriskPattern(BitArray row, int[] counters)
{
int width = row.Size;
int rowOffset = row.getNextSet(0);
int counterPosition = 0;
int patternStart = rowOffset;
bool isWhite = false;
int patternLength = counters.Length;
for (int i = rowOffset; i < width; i++)
{
if (row[i] ^ isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == patternLength - 1)
{
if (toNarrowWidePattern(counters) == ASTERISK_ENCODING)
{
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (row.isRange(Math.Max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false))
{
return new int[] { patternStart, i };
}
}
patternStart += counters[0] + counters[1];
Array.Copy(counters, 2, counters, 0, patternLength - 2);
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
return null;
}
// For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
// per image when using some of our blackbox images.
private static int toNarrowWidePattern(int[] counters)
{
int numCounters = counters.Length;
int maxNarrowCounter = 0;
int wideCounters;
do
{
int minCounter = Int32.MaxValue;
foreach (var counter in counters)
{
if (counter < minCounter && counter > maxNarrowCounter)
{
minCounter = counter;
}
}
maxNarrowCounter = minCounter;
wideCounters = 0;
int totalWideCountersWidth = 0;
int pattern = 0;
for (int i = 0; i < numCounters; i++)
{
int counter = counters[i];
if (counter > maxNarrowCounter)
{
pattern |= 1 << (numCounters - 1 - i);
wideCounters++;
totalWideCountersWidth += counter;
}
}
if (wideCounters == 3)
{
// Found 3 wide counters, but are they close enough in width?
// We can perform a cheap, conservative check to see if any individual
// counter is more than 1.5 times the average:
for (int i = 0; i < numCounters && wideCounters > 0; i++)
{
int counter = counters[i];
if (counter > maxNarrowCounter)
{
wideCounters--;
// totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
if ((counter << 1) >= totalWideCountersWidth)
{
return -1;
}
}
}
return pattern;
}
} while (wideCounters > 3);
return -1;
}
private static bool patternToChar(int pattern, out char c)
{
for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++)
{
if (CHARACTER_ENCODINGS[i] == pattern)
{
c = ALPHABET_STRING[i];
return true;
}
}
c = '*';
return false;
}
private static String decodeExtended(String encoded)
{
int length = encoded.Length;
StringBuilder decoded = new StringBuilder(length);
for (int i = 0; i < length; i++)
{
char c = encoded[i];
if (c == '+' || c == '$' || c == '%' || c == '/')
{
if (i + 1 >= encoded.Length)
{
return null;
}
char next = encoded[i + 1];
char decodedChar = '\0';
switch (c)
{
case '+':
// +A to +Z map to a to z
if (next >= 'A' && next <= 'Z')
{
decodedChar = (char)(next + 32);
}
else
{
return null;
}
break;
case '$':
// $A to $Z map to control codes SH to SB
if (next >= 'A' && next <= 'Z')
{
decodedChar = (char)(next - 64);
}
else
{
return null;
}
break;
case '%':
// %A to %E map to control codes ESC to US
if (next >= 'A' && next <= 'E')
{
decodedChar = (char)(next - 38);
}
else if (next >= 'F' && next <= 'W')
{
decodedChar = (char)(next - 11);
}
else
{
return null;
}
break;
case '/':
// /A to /O map to ! to , and /Z maps to :
if (next >= 'A' && next <= 'O')
{
decodedChar = (char)(next - 32);
}
else if (next == 'Z')
{
decodedChar = ':';
}
else
{
return null;
}
break;
}
decoded.Append(decodedChar);
// bump up i again since we read two characters
i++;
}
else
{
decoded.Append(c);
}
}
return decoded.ToString();
}
}
}
| |
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using System.IO;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Search.Payloads
{
/*
* 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 BytesRef = Lucene.Net.Util.BytesRef;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using English = Lucene.Net.Util.English;
using Field = Field;
using FieldInvertState = Lucene.Net.Index.FieldInvertState;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MultiSpansWrapper = Lucene.Net.Search.Spans.MultiSpansWrapper;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using Spans = Lucene.Net.Search.Spans.Spans;
using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery;
using Term = Lucene.Net.Index.Term;
[TestFixture]
public class TestPayloadTermQuery : LuceneTestCase
{
private static IndexSearcher searcher;
private static IndexReader reader;
private static readonly Similarity similarity = new BoostingSimilarity();
private static readonly byte[] payloadField = { 1 };
private static readonly byte[] payloadMultiField1 = { 2 };
private static readonly byte[] payloadMultiField2 = { 4 };
protected internal static Directory directory;
private class PayloadAnalyzer : Analyzer
{
internal PayloadAnalyzer()
: base(PER_FIELD_REUSE_STRATEGY)
{
}
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer result = new MockTokenizer(reader, MockTokenizer.SIMPLE, true);
return new TokenStreamComponents(result, new PayloadFilter(result, fieldName));
}
}
private class PayloadFilter : TokenFilter
{
private readonly string fieldName;
private int numSeen = 0;
private readonly IPayloadAttribute payloadAtt;
public PayloadFilter(TokenStream input, string fieldName)
: base(input)
{
this.fieldName = fieldName;
payloadAtt = AddAttribute<IPayloadAttribute>();
}
public sealed override bool IncrementToken()
{
bool hasNext = m_input.IncrementToken();
if (hasNext)
{
if (fieldName.Equals("field", StringComparison.Ordinal))
{
payloadAtt.Payload = new BytesRef(payloadField);
}
else if (fieldName.Equals("multiField", StringComparison.Ordinal))
{
if (numSeen % 2 == 0)
{
payloadAtt.Payload = new BytesRef(payloadMultiField1);
}
else
{
payloadAtt.Payload = new BytesRef(payloadMultiField2);
}
numSeen++;
}
return true;
}
else
{
return false;
}
}
public override void Reset()
{
base.Reset();
this.numSeen = 0;
}
}
/// <summary>
/// LUCENENET specific
/// Is non-static because NewIndexWriterConfig is no longer static.
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new PayloadAnalyzer()).SetSimilarity(similarity).SetMergePolicy(NewLogMergePolicy()));
//writer.infoStream = System.out;
for (int i = 0; i < 1000; i++)
{
Document doc = new Document();
Field noPayloadField = NewTextField(PayloadHelper.NO_PAYLOAD_FIELD, English.Int32ToEnglish(i), Field.Store.YES);
//noPayloadField.setBoost(0);
doc.Add(noPayloadField);
doc.Add(NewTextField("field", English.Int32ToEnglish(i), Field.Store.YES));
doc.Add(NewTextField("multiField", English.Int32ToEnglish(i) + " " + English.Int32ToEnglish(i), Field.Store.YES));
writer.AddDocument(doc);
}
reader = writer.GetReader();
writer.Dispose();
searcher = NewSearcher(reader);
searcher.Similarity = similarity;
}
[OneTimeTearDown]
public override void AfterClass()
{
searcher = null;
reader.Dispose();
reader = null;
directory.Dispose();
directory = null;
base.AfterClass();
}
[Test]
public virtual void Test()
{
PayloadTermQuery query = new PayloadTermQuery(new Term("field", "seventy"), new MaxPayloadFunction());
TopDocs hits = searcher.Search(query, null, 100);
Assert.IsTrue(hits != null, "hits is null and it shouldn't be");
Assert.IsTrue(hits.TotalHits == 100, "hits Size: " + hits.TotalHits + " is not: " + 100);
//they should all have the exact same score, because they all contain seventy once, and we set
//all the other similarity factors to be 1
Assert.IsTrue(hits.MaxScore == 1, hits.MaxScore + " does not equal: " + 1);
for (int i = 0; i < hits.ScoreDocs.Length; i++)
{
ScoreDoc doc = hits.ScoreDocs[i];
Assert.IsTrue(doc.Score == 1, doc.Score + " does not equal: " + 1);
}
CheckHits.CheckExplanations(query, PayloadHelper.FIELD, searcher, true);
Spans spans = MultiSpansWrapper.Wrap(searcher.TopReaderContext, query);
Assert.IsTrue(spans != null, "spans is null and it shouldn't be");
/*float score = hits.Score(0);
for (int i =1; i < hits.Length(); i++)
{
Assert.IsTrue(score == hits.Score(i), "scores are not equal and they should be");
}*/
}
[Test]
public virtual void TestQuery()
{
PayloadTermQuery boostingFuncTermQuery = new PayloadTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"), new MaxPayloadFunction());
QueryUtils.Check(boostingFuncTermQuery);
SpanTermQuery spanTermQuery = new SpanTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"));
Assert.IsTrue(boostingFuncTermQuery.Equals(spanTermQuery) == spanTermQuery.Equals(boostingFuncTermQuery));
PayloadTermQuery boostingFuncTermQuery2 = new PayloadTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"), new AveragePayloadFunction());
QueryUtils.CheckUnequal(boostingFuncTermQuery, boostingFuncTermQuery2);
}
[Test]
public virtual void TestMultipleMatchesPerDoc()
{
PayloadTermQuery query = new PayloadTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"), new MaxPayloadFunction());
TopDocs hits = searcher.Search(query, null, 100);
Assert.IsTrue(hits != null, "hits is null and it shouldn't be");
Assert.IsTrue(hits.TotalHits == 100, "hits Size: " + hits.TotalHits + " is not: " + 100);
//they should all have the exact same score, because they all contain seventy once, and we set
//all the other similarity factors to be 1
//System.out.println("Hash: " + seventyHash + " Twice Hash: " + 2*seventyHash);
Assert.IsTrue(hits.MaxScore == 4.0, hits.MaxScore + " does not equal: " + 4.0);
//there should be exactly 10 items that score a 4, all the rest should score a 2
//The 10 items are: 70 + i*100 where i in [0-9]
int numTens = 0;
for (int i = 0; i < hits.ScoreDocs.Length; i++)
{
ScoreDoc doc = hits.ScoreDocs[i];
if (doc.Doc % 10 == 0)
{
numTens++;
Assert.IsTrue(doc.Score == 4.0, doc.Score + " does not equal: " + 4.0);
}
else
{
Assert.IsTrue(doc.Score == 2, doc.Score + " does not equal: " + 2);
}
}
Assert.IsTrue(numTens == 10, numTens + " does not equal: " + 10);
CheckHits.CheckExplanations(query, "field", searcher, true);
Spans spans = MultiSpansWrapper.Wrap(searcher.TopReaderContext, query);
Assert.IsTrue(spans != null, "spans is null and it shouldn't be");
//should be two matches per document
int count = 0;
//100 hits times 2 matches per hit, we should have 200 in count
while (spans.MoveNext())
{
count++;
}
Assert.IsTrue(count == 200, count + " does not equal: " + 200);
}
//Set includeSpanScore to false, in which case just the payload score comes through.
[Test]
public virtual void TestIgnoreSpanScorer()
{
PayloadTermQuery query = new PayloadTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"), new MaxPayloadFunction(), false);
IndexReader reader = DirectoryReader.Open(directory);
IndexSearcher theSearcher = NewSearcher(reader);
theSearcher.Similarity = new FullSimilarity();
TopDocs hits = searcher.Search(query, null, 100);
Assert.IsTrue(hits != null, "hits is null and it shouldn't be");
Assert.IsTrue(hits.TotalHits == 100, "hits Size: " + hits.TotalHits + " is not: " + 100);
//they should all have the exact same score, because they all contain seventy once, and we set
//all the other similarity factors to be 1
//System.out.println("Hash: " + seventyHash + " Twice Hash: " + 2*seventyHash);
Assert.IsTrue(hits.MaxScore == 4.0, hits.MaxScore + " does not equal: " + 4.0);
//there should be exactly 10 items that score a 4, all the rest should score a 2
//The 10 items are: 70 + i*100 where i in [0-9]
int numTens = 0;
for (int i = 0; i < hits.ScoreDocs.Length; i++)
{
ScoreDoc doc = hits.ScoreDocs[i];
if (doc.Doc % 10 == 0)
{
numTens++;
Assert.IsTrue(doc.Score == 4.0, doc.Score + " does not equal: " + 4.0);
}
else
{
Assert.IsTrue(doc.Score == 2, doc.Score + " does not equal: " + 2);
}
}
Assert.IsTrue(numTens == 10, numTens + " does not equal: " + 10);
CheckHits.CheckExplanations(query, "field", searcher, true);
Spans spans = MultiSpansWrapper.Wrap(searcher.TopReaderContext, query);
Assert.IsTrue(spans != null, "spans is null and it shouldn't be");
//should be two matches per document
int count = 0;
//100 hits times 2 matches per hit, we should have 200 in count
while (spans.MoveNext())
{
count++;
}
reader.Dispose();
}
[Test]
public virtual void TestNoMatch()
{
PayloadTermQuery query = new PayloadTermQuery(new Term(PayloadHelper.FIELD, "junk"), new MaxPayloadFunction());
TopDocs hits = searcher.Search(query, null, 100);
Assert.IsTrue(hits != null, "hits is null and it shouldn't be");
Assert.IsTrue(hits.TotalHits == 0, "hits Size: " + hits.TotalHits + " is not: " + 0);
}
[Test]
public virtual void TestNoPayload()
{
PayloadTermQuery q1 = new PayloadTermQuery(new Term(PayloadHelper.NO_PAYLOAD_FIELD, "zero"), new MaxPayloadFunction());
PayloadTermQuery q2 = new PayloadTermQuery(new Term(PayloadHelper.NO_PAYLOAD_FIELD, "foo"), new MaxPayloadFunction());
BooleanClause c1 = new BooleanClause(q1, Occur.MUST);
BooleanClause c2 = new BooleanClause(q2, Occur.MUST_NOT);
BooleanQuery query = new BooleanQuery();
query.Add(c1);
query.Add(c2);
TopDocs hits = searcher.Search(query, null, 100);
Assert.IsTrue(hits != null, "hits is null and it shouldn't be");
Assert.IsTrue(hits.TotalHits == 1, "hits Size: " + hits.TotalHits + " is not: " + 1);
int[] results = new int[1];
results[0] = 0; //hits.ScoreDocs[0].Doc;
CheckHits.CheckHitCollector(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, query, PayloadHelper.NO_PAYLOAD_FIELD, searcher, results);
}
internal class BoostingSimilarity : DefaultSimilarity
{
public override float QueryNorm(float sumOfSquaredWeights)
{
return 1;
}
public override float Coord(int overlap, int maxOverlap)
{
return 1;
}
// TODO: Remove warning after API has been finalized
public override float ScorePayload(int docId, int start, int end, BytesRef payload)
{
//we know it is size 4 here, so ignore the offset/length
return payload.Bytes[payload.Offset];
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//Make everything else 1 so we see the effect of the payload
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public override float LengthNorm(FieldInvertState state)
{
return state.Boost;
}
public override float SloppyFreq(int distance)
{
return 1;
}
public override float Idf(long docFreq, long numDocs)
{
return 1;
}
public override float Tf(float freq)
{
return freq == 0 ? 0 : 1;
}
}
internal class FullSimilarity : DefaultSimilarity
{
public virtual float ScorePayload(int docId, string fieldName, sbyte[] payload, int offset, int length)
{
//we know it is size 4 here, so ignore the offset/length
return payload[offset];
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TestHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;
namespace MS.Test.Common.MsTestLib
{
public class TestHelper
{
// default time out for runcmd
// AzCopy will retry for 15 min when server error happens
// Set command timeout to 20 min in case azcopy is terminated during retry and cause no error output
public const int CommandTimeoutInSec = 1200;
public const int CommandTimeoutInMs = CommandTimeoutInSec * 1000;
public const int WaitForKillTimeoutInMs = 30 * 1000;
public static int RunCmd(string cmd, string args, string input = null)
{
return RunCmd(cmd, args, CommandTimeoutInMs, input);
}
public static int RunCmd(string cmd, string args, out string stdout, out string stderr, string input = null)
{
return RunCmd(cmd, args, out stdout, out stderr, CommandTimeoutInMs, input);
}
public static int RunCmd(string cmd, string args, int timeout, string input = null)
{
string stdout, stderr;
return RunCmd(cmd, args, out stdout, out stderr, timeout, input);
}
public static int RunCmd(string cmd, string args, out string stdout, out string stderr, int timeout, string input = null)
{
Test.Logger.Verbose("Running: {0} {1}", cmd, args);
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
if (string.IsNullOrEmpty(input))
{
psi.RedirectStandardInput = false;
}
else
{
psi.RedirectStandardInput = true;
}
Process p = Process.Start(psi);
// To avoid deadlock between Process.WaitForExit and Process output redirection buffer filled up, we need to async read output before calling Process.WaitForExit
StringBuilder outputBuffer = new StringBuilder();
var outputBufferLock = new object();
p.OutputDataReceived += (sendingProcess, outLine) =>
{
if (!String.IsNullOrEmpty(outLine.Data))
{
lock (outputBufferLock)
{
outputBuffer.Append(outLine.Data + "\n");
}
}
};
StringBuilder errorBuffer = new StringBuilder();
var errorBufferLock = new object();
p.ErrorDataReceived += (sendingProcess, outLine) =>
{
if (!String.IsNullOrEmpty(outLine.Data))
{
lock (errorBufferLock)
{
errorBuffer.Append(outLine.Data + "\n");
}
}
};
if (!string.IsNullOrEmpty(input))
{
var writer = p.StandardInput;
writer.AutoFlush = true;
writer.WriteLine(input);
writer.Close();
}
p.BeginOutputReadLine();
p.BeginErrorReadLine();
if (p.WaitForExit(timeout))
{
GetStdOutAndStdErr(p, outputBuffer, errorBuffer, out stdout, out stderr);
return p.ExitCode;
}
else
{
Test.Logger.Verbose("--Command timed out!");
TestHelper.KillProcess(p);
GetStdOutAndStdErr(p, outputBuffer, errorBuffer, out stdout, out stderr);
return int.MinValue;
}
}
private static void GetStdOutAndStdErr(Process p, StringBuilder outputBuffer, StringBuilder errorBuffer, out string stdout, out string stderr)
{
// Call this overload of WaitForExit to make sure all stdout/stderr strings are flushed.
p.WaitForExit();
stdout = outputBuffer.ToString();
stderr = errorBuffer.ToString();
Test.Logger.Verbose("Stdout: {0}", stdout);
if (!string.IsNullOrEmpty(stderr)
&& !string.Equals(stdout, stderr, StringComparison.InvariantCultureIgnoreCase))
{
Test.Logger.Verbose("Stderr: {0}", stderr);
}
}
public delegate bool RunningCondition(object arg);
/// <summary>
/// run cmd and specify the running condition. If running condition is not met, process will be terminated.
/// </summary>
public static int RunCmd(string cmd, string args, out string stdout, out string stderr, RunningCondition rc, object rcArg, string input = null)
{
Test.Logger.Verbose("Running: {0} {1}", cmd, args);
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
if (string.IsNullOrEmpty(input))
{
psi.RedirectStandardInput = false;
}
else
{
psi.RedirectStandardInput = true;
}
Process p = Process.Start(psi);
// To avoid deadlock between Process.WaitForExit and Process output redirection buffer filled up, we need to async read output before calling Process.WaitForExit
StringBuilder outputBuffer = new StringBuilder();
p.OutputDataReceived += (sendingProcess, outLine) =>
{
if (!String.IsNullOrEmpty(outLine.Data))
{
outputBuffer.Append(outLine.Data + "\n");
}
};
StringBuilder errorBuffer = new StringBuilder();
p.ErrorDataReceived += (sendingProcess, outLine) =>
{
if (!String.IsNullOrEmpty(outLine.Data))
{
errorBuffer.Append(outLine.Data + "\n");
}
};
if (!string.IsNullOrEmpty(input))
{
var writer = p.StandardInput;
writer.AutoFlush = true;
writer.WriteLine(input);
writer.Close();
}
p.BeginOutputReadLine();
p.BeginErrorReadLine();
DateTime nowTime = DateTime.Now;
DateTime timeOut = nowTime.AddMilliseconds(CommandTimeoutInMs);
bool isTimedOut = false;
while (rc(rcArg))
{
if (p.HasExited)
{
// process has existed
break;
}
else if (timeOut < DateTime.Now)
{
//time out
isTimedOut = true;
break;
}
else
{
//continue to wait
Thread.Sleep(100);
}
}
stdout = outputBuffer.ToString();
stderr = errorBuffer.ToString();
if (p.HasExited)
{
Test.Logger.Verbose("Stdout: {0}", stdout);
if (!string.IsNullOrEmpty(stderr)
&& !string.Equals(stdout, stderr, StringComparison.InvariantCultureIgnoreCase))
Test.Logger.Verbose("Stderr: {0}", stderr);
return p.ExitCode;
}
else
{
if (isTimedOut)
{
Test.Logger.Verbose("--Command timed out!");
}
TestHelper.KillProcess(p);
Test.Logger.Verbose("Stdout: {0}", stdout);
if (!string.IsNullOrEmpty(stderr)
&& !string.Equals(stdout, stderr, StringComparison.InvariantCultureIgnoreCase))
Test.Logger.Verbose("Stderr: {0}", stderr);
return int.MinValue;
}
}
public static bool StringMatch(string source, string pattern, RegexOptions? regexOptions = null)
{
Regex r = null;
if (regexOptions.HasValue)
{
r = new Regex(pattern, regexOptions.Value);
}
else
{
r = new Regex(pattern);
}
Match m = r.Match(source);
return m.Success;
}
public static void KillProcess(Process process)
{
try
{
process.Kill();
bool exit = process.WaitForExit(WaitForKillTimeoutInMs);
Test.Assert(exit, "Process {0} should exit after being killed", process.Id);
}
catch (InvalidOperationException e)
{
Test.Info("InvalidOperationException caught while trying to kill process {0}: {1}", process.Id, e.ToString());
}
}
}
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudWatch.Model
{
/// <summary>
/// Container for the parameters to the GetMetricStatistics operation.
/// <para> Gets statistics for the specified metric. </para> <para><b>NOTE:</b> The maximum number of data points returned from a single
/// GetMetricStatistics request is 1,440. If a request is made that generates more than 1,440 data points, Amazon CloudWatch returns an error.
/// In such a case, alter the request by narrowing the specified time range or increasing the specified period. Alternatively, make multiple
/// requests across adjacent time ranges. </para> <para> Amazon CloudWatch aggregates data points based on the length of the <c>period</c> that
/// you specify. For example, if you request statistics with a one-minute granularity, Amazon CloudWatch aggregates data points with time stamps
/// that fall within the same one-minute period. In such a case, the data points queried can greatly outnumber the data points returned. </para>
/// <para><b>NOTE:</b> The maximum number of data points that can be queried is 50,850; whereas the maximum number of data points returned is
/// 1,440. </para> <para> The following examples show various statistics allowed by the data point query maximum of 50,850 when you call
/// <c>GetMetricStatistics</c> on Amazon EC2 instances with detailed (one-minute) monitoring enabled: </para>
/// <ul>
/// <li>Statistics for up to 400 instances for a span of one hour</li>
/// <li>Statistics for up to 35 instances over a span of 24 hours</li>
/// <li>Statistics for up to 2 instances over a span of 2 weeks</li>
///
/// </ul>
/// <para> For information about the namespace, metric names, and dimensions that other Amazon Web Services products use to send metrics to
/// Cloudwatch, go to Amazon CloudWatch Metrics, Namespaces, and Dimensions Reference in the <i>Amazon CloudWatch Developer Guide</i> .
/// </para>
/// </summary>
/// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.GetMetricStatistics"/>
public class GetMetricStatisticsRequest : AmazonWebServiceRequest
{
private string namespaceValue;
private string metricName;
private List<Dimension> dimensions = new List<Dimension>();
private DateTime? startTime;
private DateTime? endTime;
private int? period;
private List<string> statistics = new List<string>();
private string unit;
/// <summary>
/// The namespace of the metric, with or without spaces.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[^:].*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Namespace
{
get { return this.namespaceValue; }
set { this.namespaceValue = value; }
}
/// <summary>
/// Sets the Namespace property
/// </summary>
/// <param name="namespaceValue">The value to set for the Namespace property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithNamespace(string namespaceValue)
{
this.namespaceValue = namespaceValue;
return this;
}
// Check to see if Namespace property is set
internal bool IsSetNamespace()
{
return this.namespaceValue != null;
}
/// <summary>
/// The name of the metric, with or without spaces.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string MetricName
{
get { return this.metricName; }
set { this.metricName = value; }
}
/// <summary>
/// Sets the MetricName property
/// </summary>
/// <param name="metricName">The value to set for the MetricName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithMetricName(string metricName)
{
this.metricName = metricName;
return this;
}
// Check to see if MetricName property is set
internal bool IsSetMetricName()
{
return this.metricName != null;
}
/// <summary>
/// A list of dimensions describing qualities of the metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 10</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<Dimension> Dimensions
{
get { return this.dimensions; }
set { this.dimensions = value; }
}
/// <summary>
/// Adds elements to the Dimensions collection
/// </summary>
/// <param name="dimensions">The values to add to the Dimensions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithDimensions(params Dimension[] dimensions)
{
foreach (Dimension element in dimensions)
{
this.dimensions.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Dimensions collection
/// </summary>
/// <param name="dimensions">The values to add to the Dimensions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithDimensions(IEnumerable<Dimension> dimensions)
{
foreach (Dimension element in dimensions)
{
this.dimensions.Add(element);
}
return this;
}
// Check to see if Dimensions property is set
internal bool IsSetDimensions()
{
return this.dimensions.Count > 0;
}
/// <summary>
/// The time stamp to use for determining the first datapoint to return. The value specified is inclusive; results include datapoints with the
/// time stamp specified. <note> The specified start time is rounded down to the nearest value. Datapoints are returned for start times up to
/// two weeks in the past. Specified start times that are more than two weeks in the past will not return datapoints for metrics that are older
/// than two weeks. </note>
///
/// </summary>
public DateTime StartTime
{
get { return this.startTime ?? default(DateTime); }
set { this.startTime = value; }
}
/// <summary>
/// Sets the StartTime property
/// </summary>
/// <param name="startTime">The value to set for the StartTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithStartTime(DateTime startTime)
{
this.startTime = startTime;
return this;
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this.startTime.HasValue;
}
/// <summary>
/// The time stamp to use for determining the last datapoint to return. The value specified is exclusive; results will include datapoints up to
/// the time stamp specified.
///
/// </summary>
public DateTime EndTime
{
get { return this.endTime ?? default(DateTime); }
set { this.endTime = value; }
}
/// <summary>
/// Sets the EndTime property
/// </summary>
/// <param name="endTime">The value to set for the EndTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithEndTime(DateTime endTime)
{
this.endTime = endTime;
return this;
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this.endTime.HasValue;
}
/// <summary>
/// The granularity, in seconds, of the returned datapoints. <c>Period</c> must be at least 60 seconds and must be a multiple of 60. The default
/// value is 60.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>60 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int Period
{
get { return this.period ?? default(int); }
set { this.period = value; }
}
/// <summary>
/// Sets the Period property
/// </summary>
/// <param name="period">The value to set for the Period property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithPeriod(int period)
{
this.period = period;
return this;
}
// Check to see if Period property is set
internal bool IsSetPeriod()
{
return this.period.HasValue;
}
/// <summary>
/// The metric statistics to return. For information about specific statistics returned by GetMetricStatistics, go to
/// <a href="http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/index.html?CHAP_TerminologyandKeyConcepts.html#Statistic">Statistics</a>
/// in the <i>Amazon CloudWatch Developer Guide</i>. Valid Values: <c>Average | Sum | SampleCount | Maximum | Minimum</c>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 5</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<string> Statistics
{
get { return this.statistics; }
set { this.statistics = value; }
}
/// <summary>
/// Adds elements to the Statistics collection
/// </summary>
/// <param name="statistics">The values to add to the Statistics collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithStatistics(params string[] statistics)
{
foreach (string element in statistics)
{
this.statistics.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Statistics collection
/// </summary>
/// <param name="statistics">The values to add to the Statistics collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithStatistics(IEnumerable<string> statistics)
{
foreach (string element in statistics)
{
this.statistics.Add(element);
}
return this;
}
// Check to see if Statistics property is set
internal bool IsSetStatistics()
{
return this.statistics.Count > 0;
}
/// <summary>
/// The unit for the metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Unit
{
get { return this.unit; }
set { this.unit = value; }
}
/// <summary>
/// Sets the Unit property
/// </summary>
/// <param name="unit">The value to set for the Unit property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetMetricStatisticsRequest WithUnit(string unit)
{
this.unit = unit;
return this;
}
// Check to see if Unit property is set
internal bool IsSetUnit()
{
return this.unit != null;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
//
// @module Android Native Plugin for Unity3D
// @author Osipov Stanislav (Stan's Assets)
// @support stans.assets@gmail.com
//
////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GoogleCloudManager : SA_Singleton<GoogleCloudManager> {
public const string STATE_DELETED = "key_deleted";
public const string STATE_UPDATED = "state_updated";
public const string STATE_LOADED = "state_loaded";
public const string STATE_RESOLVED = "state_resolved";
public const string STATE_CONFLICT = "state_conflict";
public const string ALL_STATES_LOADED = "all_states_loaded";
private int _maxStateSize = -1;
private int _maxNumKeys = -1;
private Dictionary<int, byte[]> _states = new Dictionary<int, byte[]>();
//--------------------------------------
// INITIALIZE
//--------------------------------------
void Awake() {
DontDestroyOnLoad(gameObject);
}
public void Create() {
Debug.Log ("GoogleCloudManager was created");
}
//--------------------------------------
// PUBLIC API CALL METHODS
//--------------------------------------
public void loadAllStates() {
AndroidNative.listStates ();
}
public void updateState(int stateKey, byte[] val) {
string b = "";
int len = val.Length;
for(int i = 0; i < len; i++) {
if(i != 0) {
b += ",";
}
b += val[i].ToString();
}
AndroidNative.updateState (stateKey, b);
}
public void resolveState(int stateKey, byte[] resolvedData, string resolvedVersion) {
string b = "";
int len = resolvedData.Length;
for(int i = 0; i < len; i++) {
if(i != 0) {
b += ",";
}
b += resolvedData[i].ToString();
}
AndroidNative.resolveState (stateKey, b, resolvedVersion);
}
public void deleteState(int stateKey) {
AndroidNative.deleteState (stateKey);
}
public void loadState(int stateKey) {
AndroidNative.loadState (stateKey);
}
//--------------------------------------
// PUBLIC METHODS
//--------------------------------------
public byte[] GetStateData(int stateKey) {
if(_states.ContainsKey(stateKey)) {
return _states [stateKey];
} else {
return null;
}
}
//--------------------------------------
// GET / SET
//--------------------------------------
public int maxStateSize {
get {
return _maxStateSize;
}
}
public int maxNumKeys {
get {
return _maxNumKeys;
}
}
public Dictionary<int, byte[]> states {
get {
return _states;
}
}
//--------------------------------------
// EVENTS
//--------------------------------------
private void OnAllStatesLoaded(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
GoogleCloudResult result = new GoogleCloudResult (storeData [0]);
if(storeData.Length > 1) {
_states.Clear ();
for(int i = 1; i < storeData.Length; i+=2) {
if(storeData[i] == AndroidNative.DATA_EOF) {
break;
}
PushStateData (storeData [i], ConvertStringToCloudData(storeData [i + 1]));
}
Debug.Log ("Loaded: " + _states.Count + " States");
}
dispatch (ALL_STATES_LOADED, result);
}
private void OnStateConflict(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
GoogleCloudResult result = new GoogleCloudResult ("0", storeData [0]);
if(result.isSuccess) {
result.stateData = ConvertStringToCloudData(storeData [1]);
result.serverConflictData = ConvertStringToCloudData(storeData [2]);
result.resolvedVersion = storeData [3];
PushStateData (storeData [0], result.stateData);
}
//set state data storeData [2]
dispatch (STATE_CONFLICT, result);
}
private void OnStateLoaded(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
GoogleCloudResult result = new GoogleCloudResult (storeData [0], storeData [1]);
result.stateData = ConvertStringToCloudData(storeData [2]);
PushStateData (storeData [1], result.stateData);
//set state data storeData [2]
dispatch (STATE_LOADED, result);
}
private void OnStateResolved(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
GoogleCloudResult result = new GoogleCloudResult (storeData [0], storeData [1]);
result.stateData = ConvertStringToCloudData(storeData [2]);
PushStateData (storeData [1], result.stateData);
//set state data storeData [2]
dispatch (STATE_RESOLVED, result);
}
private void OnStateUpdated(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
GoogleCloudResult result = new GoogleCloudResult (storeData [0], storeData [1]);
result.stateData = ConvertStringToCloudData(storeData [2]);
PushStateData (storeData [1], result.stateData);
//set state data storeData [2]
dispatch (STATE_UPDATED, result);
}
private void OnKeyDeleted(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
GoogleCloudResult result = new GoogleCloudResult (storeData [0], storeData [1]);
dispatch (STATE_DELETED, result);
}
private void OnCloudConnected(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
Debug.Log ("Google Cloud is connected max state size: " + storeData[0] + " max state num " + storeData[1]);
_maxNumKeys = System.Convert.ToInt32 (storeData[1]);
_maxStateSize = System.Convert.ToInt32 (storeData[0]);
}
//--------------------------------------
// PRIVATE METHODS
//--------------------------------------
private void PushStateData(string stateKey, byte[] data) {
PushStateData (System.Convert.ToInt32(stateKey), data);
}
private void PushStateData(int stateKey, byte[] data) {
if(_states.ContainsKey(stateKey)) {
_states [stateKey] = data;
} else {
_states.Add (stateKey, data);
}
}
private static byte[] ConvertStringToCloudData(string data) {
if(data == null) {
return null;
}
data = data.Replace(AndroidNative.DATA_EOF, string.Empty);
if(data.Equals(string.Empty)) {
return null;
}
string[] array;
array = data.Split("," [0]);
List<byte> l = new List<byte> ();
foreach(string s in array) {
Debug.Log(s);
l.Add (System.Convert.ToByte(s));
}
return l.ToArray ();
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Threading;
using System.Xml;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void LoggerBase_Exec_Non_Transacted_Query(SqlString ConnectionString, SqlString Query, SqlXml Parameters, SqlInt32 CommandTimeout, SqlBoolean Debug)
{
SqlCommand Command = new SqlCommand();
string QueryValue = Query.Value;
string ConnectionStringValue = ConnectionString.Value + ";Enlist=false;";
XmlDocument ParameterXML = new XmlDocument();
ParameterXML.Load(Parameters.CreateReader());
foreach (XmlNode Node in ParameterXML.ChildNodes)
{
foreach (XmlNode ChildNode in Node.ChildNodes)
{
if (ChildNode.Attributes == null) { continue; }
if (Debug.Value & ChildNode.Attributes["ParameterName"] != null)
{
SqlContext.Pipe.Send(string.Format("Processing parameter '{0}' with a value of '{1}'.", ChildNode.Attributes["ParameterName"].Value, ChildNode.InnerText));
}
if (ChildNode.Attributes["ParameterName"] != null)
{
SqlParameter NewParameter = Command.CreateParameter();
NewParameter.ParameterName = ChildNode.Attributes["ParameterName"].Value;
if (ChildNode.Attributes["DBType"] != null)
{
NewParameter.SqlDbType = (SqlDbType)Enum.Parse(typeof(SqlDbType), ChildNode.Attributes["DBType"].Value);
}
int size;
if (ChildNode.Attributes["Size"] != null)
{
if (Int32.TryParse(ChildNode.Attributes["Size"].Value, out size))
{
NewParameter.Size = size;
}
}
NewParameter.Value = ChildNode.InnerText;
Command.Parameters.Add(NewParameter);
}
}
}
//ParameterXML.
//var ParameterReader = Parameters.CreateReader();
//while (ParameterReader.Read())
//{
// if (ParameterReader.NodeType == XmlNodeType.Element)
// {
// if (Debug.Value)
// {
// SqlContext.Pipe.Send(string.Format("Processing parameter '{0}' with a value of '{1}'.", ParameterReader.GetAttribute("parameterName"), ParameterReader.Value));
// }
// SqlParameter NewParameter = Command.CreateParameter();
// NewParameter.ParameterName = ParameterReader.GetAttribute("parameterName");
// NewParameter.SqlDbType = (SqlDbType)Enum.Parse(typeof(SqlDbType), ParameterReader.GetAttribute("dbType"));
// int size;
// if (Int32.TryParse(ParameterReader.GetAttribute("size"), out size))
// {
// NewParameter.Size = size;
// }
// Command.Parameters.Add(NewParameter);
// }
//}
using (SqlConnection Connection = new SqlConnection(ConnectionStringValue))
{
Connection.Open();
Command.CommandType = CommandType.Text;
Command.CommandText = QueryValue;
Command.Connection = Connection;
if (Debug.Value)
{
SqlContext.Pipe.Send(string.Format("Connecting to {0} and sending query: {1}", Connection.Database, Command.CommandText));
foreach(SqlParameter P in Command.Parameters)
{
SqlContext.Pipe.Send(string.Format("Parameter: {0} Value: {1}",P.ParameterName, P.Value));
}
}
Command.ExecuteNonQuery();
Connection.Close();
}
}
}
public class ReadWriteFiles
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void WriteTextFile(SqlString text,
SqlString path,
SqlBoolean append,
out SqlInt32 exitCode,
out SqlString errorMessage)
{
// Parameters
// text: Contains information to be written.
// path: The complete file path to write to.
// append: Determines whether data is to be appended to the file.
// if the file exists and append is false, the file is overwritten.
// If the file exists and append is true, the data is appended to the file.
// Otherwise, a new file is created.
errorMessage = new SqlString(string.Empty);
try
{
// Check for null input.
if (!text.IsNull &&
!path.IsNull &&
!append.IsNull)
{
// Get the directory information for the specified path.
var dir = Path.GetDirectoryName(path.Value);
// Determine whether the specified path refers to an existing directory.
if (!Directory.Exists(dir))
// Create all the directories in the specified path.
Directory.CreateDirectory(dir);
// Initialize a new instance of the StreamWriter class
// for the specified file on the specified path.
// If the file exists, it can be either overwritten or appended to.
// If the file does not exist, create a new file.
using (var sw = new StreamWriter(path.Value, append.Value))
{
// Write specified text followed by a line terminator.
sw.WriteLine(text);
}
// Return true on success.
exitCode = new SqlInt32(0);
}
else
// Return null if any input is null.
exitCode = new SqlInt32(1);
}
catch (Exception ex)
{
// Return null on error.
//SqlContext.Pipe.Send(ex.Message);
errorMessage = new SqlString(ex.Message);
//return -1 #SqlBoolean.True;
exitCode = new SqlInt32(-1);
}
}
[SqlProcedure]
public static void ReadTextFile(SqlString path)
{
// Parameters
// path: The complete file path to read from.
try
{
// Check for null input.
if (!path.IsNull)
{
// Initialize a new instance of the StreamReader class for the specified path.
using (var sr = new StreamReader(path.Value))
{
// Create the record and specify the metadata for the column.
var rec = new SqlDataRecord(
new SqlMetaData("Line", SqlDbType.NVarChar, SqlMetaData.Max));
// Mark the beginning of the result-set.
SqlContext.Pipe.SendResultsStart(rec);
// Determine whether the end of the file.
while (sr.Peek() >= 0)
{
// Set value for the column.
rec.SetString(0, sr.ReadLine());
// Send the row back to the client.
SqlContext.Pipe.SendResultsRow(rec);
}
// Mark the end of the result-set.
SqlContext.Pipe.SendResultsEnd();
}
}
}
catch (Exception ex)
{
// Send exception message on error.
SqlContext.Pipe.Send(ex.Message);
}
}
};
public class WriteFilesWithMutex
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void WriteTextFile(SqlString text,
SqlString path,
SqlBoolean append,
SqlString mutexname,
out SqlInt32 exitCode,
out SqlString errorMessage)
{
errorMessage = new SqlString(string.Empty);
try
{
// Check for null input.
if (!text.IsNull &&
!path.IsNull &&
!append.IsNull)
{
// Get the directory information for the specified path.
var dir = Path.GetDirectoryName(path.Value);
// Determine whether the specified path refers to an existing directory.
if (!Directory.Exists(dir))
// Create all the directories in the specified path.
Directory.CreateDirectory(dir);
// Initialize a new instance of the StreamWriter class
// for the specified file on the specified path.
// If the file exists, it can be either overwritten or appended to.
// If the file does not exist, create a new file.
using (var mutex = new Mutex(false, mutexname.Value))
{
mutex.WaitOne();
using (var sw = new StreamWriter(path.Value, append.Value))
{
// Write specified text followed by a line terminator.
sw.WriteLine(text);
}
mutex.ReleaseMutex();
}
// Return true on success.
exitCode = new SqlInt32(0);
}
else
// Return null if any input is null.
exitCode = new SqlInt32(1);
}
catch (Exception ex)
{
// Return null on error.
//SqlContext.Pipe.Send(ex.Message);
errorMessage = new SqlString(ex.Message);
//return -1 #SqlBoolean.True;
exitCode = new SqlInt32(-1);
}
}
}
| |
// 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 System.Xml.Xsl.XsltOld
{
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Xml.XPath;
using System.Xml.Xsl.Runtime;
internal class NumberAction : ContainerAction
{
private const long msofnfcNil = 0x00000000; // no flags
private const long msofnfcTraditional = 0x00000001; // use traditional numbering
private const long msofnfcAlwaysFormat = 0x00000002; // if requested format is not supported, use Arabic (Western) style
private const int cchMaxFormat = 63; // max size of formatted result
private const int cchMaxFormatDecimal = 11; // max size of formatted decimal result (doesn't handle the case of a very large pwszSeparator or minlen)
internal class FormatInfo
{
public bool isSeparator; // False for alphanumeric strings of chars
public NumberingSequence numSequence; // Specifies numbering sequence
public int length; // Minimum length of decimal numbers (if necessary, pad to left with zeros)
public string formatString; // Format string for separator token
public FormatInfo(bool isSeparator, string formatString)
{
this.isSeparator = isSeparator;
this.formatString = formatString;
}
public FormatInfo() { }
}
private static FormatInfo s_defaultFormat = new FormatInfo(false, "0");
private static FormatInfo s_defaultSeparator = new FormatInfo(true, ".");
private class NumberingFormat : NumberFormatterBase
{
private NumberingSequence _seq;
private int _cMinLen;
private string _separator;
private int _sizeGroup;
internal NumberingFormat() { }
internal void setNumberingType(NumberingSequence seq) { _seq = seq; }
//void setLangID(LID langid) {_langid = langid;}
//internal void setTraditional(bool fTraditional) {_grfnfc = fTraditional ? msofnfcTraditional : 0;}
internal void setMinLen(int cMinLen) { _cMinLen = cMinLen; }
internal void setGroupingSeparator(string separator) { _separator = separator; }
internal void setGroupingSize(int sizeGroup)
{
if (0 <= sizeGroup && sizeGroup <= 9)
{
_sizeGroup = sizeGroup;
}
}
internal string FormatItem(object value)
{
double dblVal;
if (value is int)
{
dblVal = (int)value;
}
else
{
dblVal = XmlConvert.ToXPathDouble(value);
if (0.5 <= dblVal && !double.IsPositiveInfinity(dblVal))
{
dblVal = XmlConvert.XPathRound(dblVal);
}
else
{
// It is an error if the number is NaN, infinite or less than 0.5; an XSLT processor may signal the error;
// if it does not signal the error, it must recover by converting the number to a string as if by a call
// to the string function and inserting the resulting string into the result tree.
return XmlConvert.ToXPathString(value);
}
}
Debug.Assert(dblVal >= 1);
switch (_seq)
{
case NumberingSequence.Arabic:
break;
case NumberingSequence.UCLetter:
case NumberingSequence.LCLetter:
if (dblVal <= MaxAlphabeticValue)
{
StringBuilder sb = new StringBuilder();
ConvertToAlphabetic(sb, dblVal, _seq == NumberingSequence.UCLetter ? 'A' : 'a', 26);
return sb.ToString();
}
break;
case NumberingSequence.UCRoman:
case NumberingSequence.LCRoman:
if (dblVal <= MaxRomanValue)
{
StringBuilder sb = new StringBuilder();
ConvertToRoman(sb, dblVal, _seq == NumberingSequence.UCRoman);
return sb.ToString();
}
break;
}
return ConvertToArabic(dblVal, _cMinLen, _sizeGroup, _separator);
}
private static string ConvertToArabic(double val, int minLength, int groupSize, string groupSeparator)
{
string str;
if (groupSize != 0 && groupSeparator != null)
{
NumberFormatInfo NumberFormat = new NumberFormatInfo();
NumberFormat.NumberGroupSizes = new int[] { groupSize };
NumberFormat.NumberGroupSeparator = groupSeparator;
if (Math.Floor(val) == val)
{
NumberFormat.NumberDecimalDigits = 0;
}
str = val.ToString("N", NumberFormat);
}
else
{
str = Convert.ToString(val, CultureInfo.InvariantCulture);
}
if (str.Length >= minLength)
{
return str;
}
else
{
StringBuilder sb = new StringBuilder(minLength);
sb.Append('0', minLength - str.Length);
sb.Append(str);
return sb.ToString();
}
}
}
// States:
private const int OutputNumber = 2;
private string _level;
private string _countPattern;
private int _countKey = Compiler.InvalidQueryKey;
private string _from;
private int _fromKey = Compiler.InvalidQueryKey;
private string _value;
private int _valueKey = Compiler.InvalidQueryKey;
private Avt _formatAvt;
private Avt _langAvt;
private Avt _letterAvt;
private Avt _groupingSepAvt;
private Avt _groupingSizeAvt;
// Compile time precalculated AVTs
private List<FormatInfo> _formatTokens;
private string _lang;
private string _letter;
private string _groupingSep;
private string _groupingSize;
private bool _forwardCompatibility;
internal override bool CompileAttribute(Compiler compiler)
{
string name = compiler.Input.LocalName;
string value = compiler.Input.Value;
if (Ref.Equal(name, compiler.Atoms.Level))
{
if (value != "any" && value != "multiple" && value != "single")
{
throw XsltException.Create(SR.Xslt_InvalidAttrValue, "level", value);
}
_level = value;
}
else if (Ref.Equal(name, compiler.Atoms.Count))
{
_countPattern = value;
_countKey = compiler.AddQuery(value, /*allowVars:*/true, /*allowKey:*/true, /*pattern*/true);
}
else if (Ref.Equal(name, compiler.Atoms.From))
{
_from = value;
_fromKey = compiler.AddQuery(value, /*allowVars:*/true, /*allowKey:*/true, /*pattern*/true);
}
else if (Ref.Equal(name, compiler.Atoms.Value))
{
_value = value;
_valueKey = compiler.AddQuery(value);
}
else if (Ref.Equal(name, compiler.Atoms.Format))
{
_formatAvt = Avt.CompileAvt(compiler, value);
}
else if (Ref.Equal(name, compiler.Atoms.Lang))
{
_langAvt = Avt.CompileAvt(compiler, value);
}
else if (Ref.Equal(name, compiler.Atoms.LetterValue))
{
_letterAvt = Avt.CompileAvt(compiler, value);
}
else if (Ref.Equal(name, compiler.Atoms.GroupingSeparator))
{
_groupingSepAvt = Avt.CompileAvt(compiler, value);
}
else if (Ref.Equal(name, compiler.Atoms.GroupingSize))
{
_groupingSizeAvt = Avt.CompileAvt(compiler, value);
}
else
{
return false;
}
return true;
}
internal override void Compile(Compiler compiler)
{
CompileAttributes(compiler);
CheckEmpty(compiler);
_forwardCompatibility = compiler.ForwardCompatibility;
_formatTokens = ParseFormat(PrecalculateAvt(ref _formatAvt));
_letter = ParseLetter(PrecalculateAvt(ref _letterAvt));
_lang = PrecalculateAvt(ref _langAvt);
_groupingSep = PrecalculateAvt(ref _groupingSepAvt);
if (_groupingSep != null && _groupingSep.Length > 1)
{
throw XsltException.Create(SR.Xslt_CharAttribute, "grouping-separator");
}
_groupingSize = PrecalculateAvt(ref _groupingSizeAvt);
}
private int numberAny(Processor processor, ActionFrame frame)
{
int result = 0;
// Our current point will be our end point in this search
XPathNavigator endNode = frame.Node;
if (endNode.NodeType == XPathNodeType.Attribute || endNode.NodeType == XPathNodeType.Namespace)
{
endNode = endNode.Clone();
endNode.MoveToParent();
}
XPathNavigator startNode = endNode.Clone();
if (_fromKey != Compiler.InvalidQueryKey)
{
bool hitFrom = false;
// First try to find start by traversing up. This gives the best candidate or we hit root
do
{
if (processor.Matches(startNode, _fromKey))
{
hitFrom = true;
break;
}
} while (startNode.MoveToParent());
Debug.Assert(
processor.Matches(startNode, _fromKey) || // we hit 'from' or
startNode.NodeType == XPathNodeType.Root // we are at root
);
// from this point (matched parent | root) create descendent quiery:
// we have to reset 'result' on each 'from' node, because this point can' be not last from point;
XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true);
while (sel.MoveNext())
{
if (processor.Matches(sel.Current, _fromKey))
{
hitFrom = true;
result = 0;
}
else if (MatchCountKey(processor, frame.Node, sel.Current))
{
result++;
}
if (sel.Current.IsSamePosition(endNode))
{
break;
}
}
if (!hitFrom)
{
result = 0;
}
}
else
{
// without 'from' we startting from the root
startNode.MoveToRoot();
XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true);
// and count root node by itself
while (sel.MoveNext())
{
if (MatchCountKey(processor, frame.Node, sel.Current))
{
result++;
}
if (sel.Current.IsSamePosition(endNode))
{
break;
}
}
}
return result;
}
// check 'from' condition:
// if 'from' exist it has to be ancestor-or-self for the nav
private bool checkFrom(Processor processor, XPathNavigator nav)
{
if (_fromKey == Compiler.InvalidQueryKey)
{
return true;
}
do
{
if (processor.Matches(nav, _fromKey))
{
return true;
}
} while (nav.MoveToParent());
return false;
}
private bool moveToCount(XPathNavigator nav, Processor processor, XPathNavigator contextNode)
{
do
{
if (_fromKey != Compiler.InvalidQueryKey && processor.Matches(nav, _fromKey))
{
return false;
}
if (MatchCountKey(processor, contextNode, nav))
{
return true;
}
} while (nav.MoveToParent());
return false;
}
private int numberCount(XPathNavigator nav, Processor processor, XPathNavigator contextNode)
{
Debug.Assert(nav.NodeType != XPathNodeType.Attribute && nav.NodeType != XPathNodeType.Namespace);
Debug.Assert(MatchCountKey(processor, contextNode, nav));
XPathNavigator runner = nav.Clone();
int number = 1;
if (runner.MoveToParent())
{
runner.MoveToFirstChild();
while (!runner.IsSamePosition(nav))
{
if (MatchCountKey(processor, contextNode, runner))
{
number++;
}
if (!runner.MoveToNext())
{
Debug.Fail("We implementing preceding-sibling::node() and some how miss context node 'nav'");
break;
}
}
}
return number;
}
private static object SimplifyValue(object value)
{
// If result of xsl:number is not in correct range it should be returned as is.
// so we need intermidiate string value.
// If it's already a double we would like to keep it as double.
// So this function converts to string only if if result is nodeset or RTF
Debug.Assert(!(value is int));
if (Type.GetTypeCode(value.GetType()) == TypeCode.Object)
{
XPathNodeIterator nodeset = value as XPathNodeIterator;
if (nodeset != null)
{
if (nodeset.MoveNext())
{
return nodeset.Current.Value;
}
return string.Empty;
}
XPathNavigator nav = value as XPathNavigator;
if (nav != null)
{
return nav.Value;
}
}
return value;
}
internal override void Execute(Processor processor, ActionFrame frame)
{
Debug.Assert(processor != null && frame != null);
ArrayList list = processor.NumberList;
switch (frame.State)
{
case Initialized:
Debug.Assert(frame != null);
Debug.Assert(frame.NodeSet != null);
list.Clear();
if (_valueKey != Compiler.InvalidQueryKey)
{
list.Add(SimplifyValue(processor.Evaluate(frame, _valueKey)));
}
else if (_level == "any")
{
int number = numberAny(processor, frame);
if (number != 0)
{
list.Add(number);
}
}
else
{
bool multiple = (_level == "multiple");
XPathNavigator contextNode = frame.Node; // context of xsl:number element. We using this node in MatchCountKey()
XPathNavigator countNode = frame.Node.Clone(); // node we count for
if (countNode.NodeType == XPathNodeType.Attribute || countNode.NodeType == XPathNodeType.Namespace)
{
countNode.MoveToParent();
}
while (moveToCount(countNode, processor, contextNode))
{
list.Insert(0, numberCount(countNode, processor, contextNode));
if (!multiple || !countNode.MoveToParent())
{
break;
}
}
if (!checkFrom(processor, countNode))
{
list.Clear();
}
}
/*CalculatingFormat:*/
frame.StoredOutput = Format(list,
_formatAvt == null ? _formatTokens : ParseFormat(_formatAvt.Evaluate(processor, frame)),
_langAvt == null ? _lang : _langAvt.Evaluate(processor, frame),
_letterAvt == null ? _letter : ParseLetter(_letterAvt.Evaluate(processor, frame)),
_groupingSepAvt == null ? _groupingSep : _groupingSepAvt.Evaluate(processor, frame),
_groupingSizeAvt == null ? _groupingSize : _groupingSizeAvt.Evaluate(processor, frame)
);
goto case OutputNumber;
case OutputNumber:
Debug.Assert(frame.StoredOutput != null);
if (!processor.TextEvent(frame.StoredOutput))
{
frame.State = OutputNumber;
break;
}
frame.Finished();
break;
default:
Debug.Fail("Invalid Number Action execution state");
break;
}
}
private bool MatchCountKey(Processor processor, XPathNavigator contextNode, XPathNavigator nav)
{
if (_countKey != Compiler.InvalidQueryKey)
{
return processor.Matches(nav, _countKey);
}
if (contextNode.Name == nav.Name && BasicNodeType(contextNode.NodeType) == BasicNodeType(nav.NodeType))
{
return true;
}
return false;
}
private XPathNodeType BasicNodeType(XPathNodeType type)
{
if (type == XPathNodeType.SignificantWhitespace || type == XPathNodeType.Whitespace)
{
return XPathNodeType.Text;
}
else
{
return type;
}
}
// SDUB: perf.
// for each call to xsl:number Format() will build new NumberingFormat object.
// in case of no AVTs we can build this object at compile time and reuse it on execution time.
// even partial step in this derection will be usefull (when cFormats == 0)
private static string Format(ArrayList numberlist, List<FormatInfo> tokens, string lang, string letter, string groupingSep, string groupingSize)
{
StringBuilder result = new StringBuilder();
int cFormats = 0;
if (tokens != null)
{
cFormats = tokens.Count;
}
NumberingFormat numberingFormat = new NumberingFormat();
if (groupingSize != null)
{
try
{
numberingFormat.setGroupingSize(Convert.ToInt32(groupingSize, CultureInfo.InvariantCulture));
}
catch (System.FormatException) { }
catch (System.OverflowException) { }
}
if (groupingSep != null)
{
if (groupingSep.Length > 1)
{
// It is a breaking change to throw an exception, SQLBUDT 324367
//throw XsltException.Create(SR.Xslt_CharAttribute, "grouping-separator");
}
numberingFormat.setGroupingSeparator(groupingSep);
}
if (0 < cFormats)
{
FormatInfo prefix = tokens[0];
Debug.Assert(prefix == null || prefix.isSeparator);
FormatInfo sufix = null;
if (cFormats % 2 == 1)
{
sufix = tokens[cFormats - 1];
cFormats--;
}
FormatInfo periodicSeparator = 2 < cFormats ? tokens[cFormats - 2] : s_defaultSeparator;
FormatInfo periodicFormat = 0 < cFormats ? tokens[cFormats - 1] : s_defaultFormat;
if (prefix != null)
{
result.Append(prefix.formatString);
}
int numberlistCount = numberlist.Count;
for (int i = 0; i < numberlistCount; i++)
{
int formatIndex = i * 2;
bool haveFormat = formatIndex < cFormats;
if (0 < i)
{
FormatInfo thisSeparator = haveFormat ? tokens[formatIndex + 0] : periodicSeparator;
Debug.Assert(thisSeparator.isSeparator);
result.Append(thisSeparator.formatString);
}
FormatInfo thisFormat = haveFormat ? tokens[formatIndex + 1] : periodicFormat;
Debug.Assert(!thisFormat.isSeparator);
//numberingFormat.setletter(this.letter);
//numberingFormat.setLang(this.lang);
numberingFormat.setNumberingType(thisFormat.numSequence);
numberingFormat.setMinLen(thisFormat.length);
result.Append(numberingFormat.FormatItem(numberlist[i]));
}
if (sufix != null)
{
result.Append(sufix.formatString);
}
}
else
{
numberingFormat.setNumberingType(NumberingSequence.Arabic);
for (int i = 0; i < numberlist.Count; i++)
{
if (i != 0)
{
result.Append(".");
}
result.Append(numberingFormat.FormatItem(numberlist[i]));
}
}
return result.ToString();
}
/*
----------------------------------------------------------------------------
mapFormatToken()
Maps a token of alphanumeric characters to a numbering format ID and a
minimum length bound. Tokens specify the character(s) that begins a
Unicode
numbering sequence. For example, "i" specifies lower case roman numeral
numbering. Leading "zeros" specify a minimum length to be maintained by
padding, if necessary.
----------------------------------------------------------------------------
*/
private static void mapFormatToken(string wsToken, int startLen, int tokLen, out NumberingSequence seq, out int pminlen)
{
char wch = wsToken[startLen];
bool UseArabic = false;
pminlen = 1;
seq = NumberingSequence.Nil;
switch ((int)wch)
{
case 0x0030: // Digit zero
case 0x0966: // Hindi digit zero
case 0x0e50: // Thai digit zero
case 0xc77b: // Korean digit zero
case 0xff10: // Digit zero (double-byte)
do
{
// Leading zeros request padding. Track how much.
pminlen++;
} while ((--tokLen > 0) && (wch == wsToken[++startLen]));
if (wsToken[startLen] != (char)(wch + 1))
{
// If next character isn't "one", then use Arabic
UseArabic = true;
}
break;
}
if (!UseArabic)
{
// Map characters of token to number format ID
switch ((int)wsToken[startLen])
{
case 0x0031: seq = NumberingSequence.Arabic; break;
case 0x0041: seq = NumberingSequence.UCLetter; break;
case 0x0049: seq = NumberingSequence.UCRoman; break;
case 0x0061: seq = NumberingSequence.LCLetter; break;
case 0x0069: seq = NumberingSequence.LCRoman; break;
case 0x0410: seq = NumberingSequence.UCRus; break;
case 0x0430: seq = NumberingSequence.LCRus; break;
case 0x05d0: seq = NumberingSequence.Hebrew; break;
case 0x0623: seq = NumberingSequence.ArabicScript; break;
case 0x0905: seq = NumberingSequence.Hindi2; break;
case 0x0915: seq = NumberingSequence.Hindi1; break;
case 0x0967: seq = NumberingSequence.Hindi3; break;
case 0x0e01: seq = NumberingSequence.Thai1; break;
case 0x0e51: seq = NumberingSequence.Thai2; break;
case 0x30a2: seq = NumberingSequence.DAiueo; break;
case 0x30a4: seq = NumberingSequence.DIroha; break;
case 0x3131: seq = NumberingSequence.DChosung; break;
case 0x4e00: seq = NumberingSequence.FEDecimal; break;
case 0x58f1: seq = NumberingSequence.DbNum3; break;
case 0x58f9: seq = NumberingSequence.ChnCmplx; break;
case 0x5b50: seq = NumberingSequence.Zodiac2; break;
case 0xac00: seq = NumberingSequence.Ganada; break;
case 0xc77c: seq = NumberingSequence.KorDbNum1; break;
case 0xd558: seq = NumberingSequence.KorDbNum3; break;
case 0xff11: seq = NumberingSequence.DArabic; break;
case 0xff71: seq = NumberingSequence.Aiueo; break;
case 0xff72: seq = NumberingSequence.Iroha; break;
case 0x7532:
if (tokLen > 1 && wsToken[startLen + 1] == 0x5b50)
{
// 60-based Zodiak numbering begins with two characters
seq = NumberingSequence.Zodiac3;
tokLen--;
startLen++;
}
else
{
// 10-based Zodiak numbering begins with one character
seq = NumberingSequence.Zodiac1;
}
break;
default:
seq = NumberingSequence.Arabic;
break;
}
}
//if (tokLen != 1 || UseArabic) {
if (UseArabic)
{
// If remaining token length is not 1, then don't recognize
// sequence and default to Arabic with no zero padding.
seq = NumberingSequence.Arabic;
pminlen = 0;
}
}
/*
----------------------------------------------------------------------------
parseFormat()
Parse format string into format tokens (alphanumeric) and separators
(non-alphanumeric).
*/
private static List<FormatInfo> ParseFormat(string formatString)
{
if (formatString == null || formatString.Length == 0)
{
return null;
}
int length = 0;
bool lastAlphaNumeric = CharUtil.IsAlphaNumeric(formatString[length]);
List<FormatInfo> tokens = new List<FormatInfo>();
int count = 0;
if (lastAlphaNumeric)
{
// If the first one is alpha num add empty separator as a prefix.
tokens.Add(null);
}
while (length <= formatString.Length)
{
// Loop until a switch from format token to separator is detected (or vice-versa)
bool currentchar = length < formatString.Length ? CharUtil.IsAlphaNumeric(formatString[length]) : !lastAlphaNumeric;
if (lastAlphaNumeric != currentchar)
{
FormatInfo formatInfo = new FormatInfo();
if (lastAlphaNumeric)
{
// We just finished a format token. Map it to a numbering format ID and a min-length bound.
mapFormatToken(formatString, count, length - count, out formatInfo.numSequence, out formatInfo.length);
}
else
{
formatInfo.isSeparator = true;
// We just finished a separator. Save its length and a pointer to it.
formatInfo.formatString = formatString.Substring(count, length - count);
}
count = length;
length++;
// Begin parsing the next format token or separator
tokens.Add(formatInfo);
// Flip flag from format token to separator (or vice-versa)
lastAlphaNumeric = currentchar;
}
else
{
length++;
}
}
return tokens;
}
private string ParseLetter(string letter)
{
if (letter == null || letter == "traditional" || letter == "alphabetic")
{
return letter;
}
if (!_forwardCompatibility)
{
throw XsltException.Create(SR.Xslt_InvalidAttrValue, "letter-value", letter);
}
return null;
}
}
}
| |
/* Ben Scott * bescott@andrew.cmu.edu * 2015-11-11 * ItemSet */
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Type=System.Type;
using inv=PathwaysEngine.Inventory;
using adv=PathwaysEngine.Adventure;
using maps=PathwaysEngine.Adventure.Setting;
using lit=PathwaysEngine.Literature;
using stat=PathwaysEngine.Statistics;
using util=PathwaysEngine.Utilities;
namespace PathwaysEngine.Inventory {
/** `ItemSet` : **`class`**
*
* This class implements the `IItemSet` interface, and
* provides a way to deal with collections of items,
* iterate over them, & get particular types of `Item`s.
**/
public class ItemSet : IItemSet, lit::IDescribable {
public bool IsReadOnly { get { return false; } }
public int Count {
get { var n = 0;
foreach (var elem in Items.Values)
n += elem.Count;
return n;
}
}
public string Name {
get { return "Jeez! An ItemSEt!/"; } }
public lit::Description description {get;set;}
/** `Items` : **`Dictionary<Type,List<Item>>`**
*
* Mapping between the `Type`s of the `Item` values
* and the `Item`s themselves.
**/
public Dictionary<Type,List<Item>> Items {
get { return items; }
} Dictionary<Type,List<Item>> items;
public ICollection<Type> Keys {
get { return Items.Keys; } }
public ICollection<List<Item>> Values {
get { return Items.Values; } }
/** `Indexer[Type]` : **`List<Item>`**
*
* Indexer to get individual `List`s or lists of more
* derived `Item`s from the dictionary.
*
* - `type` : **`Type`**
* Type of the `Item`s to get from the set.
**/
public List<Item> this[Type type] {
get { return Items[type]; }
set { Items[type] = (List<Item>) value; } }
/** `ItemSet` : **`constructor`**
*
* Initializes the datastructure with every `Item` in
* the scene.
**/
public ItemSet()
: this(new Dictionary<Type,List<Item>>()
{{typeof(Item),new List<Item>()}}) { }
public ItemSet(List<Item> items) {
this.items = new Dictionary<Type,List<Item>>() {
{typeof(Item), items}};}
public ItemSet(Dictionary<Type,List<Item>> items) {
this.items = items;
if (!this.items.ContainsKey(typeof(Item)))
this.items[typeof(Item)] = new List<Item>(); }
/** `Add()` : **`function`**
*
* Override of the `ICollection<T>` function.
*
* - `type` : **`Type`**
*
* - `item` : **`Item`**
* Instance of `Item` to be added.
**/
public void Add(Type type,List<Item> list) {
Items[type].AddRange(list); }
public void Add(Item item) {
if (!Items.ContainsKey(item.GetType()))
Items[item.GetType()] = new List<Item>();
Items[item.GetType()].Add(item);
}
public void Add<T>(ICollection<T> list)
where T : Item {
if (list?.Count<1) return;
if (!Items.ContainsKey(typeof(T)))
Items[typeof(T)] = new List<Item>();
foreach (var elem in list)
Items[typeof(T)].Add(elem);
}
/** `Contains()` : **`bool`**
*
* Membership test for a particular `Item`.
*
* - `item` : **`Item`**
* Instance of `Item` to be added.
**/
public bool Contains(Item item) {
List<Item> temp;
return (TryGetValue<Item>(out temp)
&& temp!=null && temp.Contains(item));
}
/** `IndexOf()` : **`int`**
*
* Finds the first instance of `item` and returns its
* position in the set.
*
* - `item` : **`Item`**
* Instance of `Item` to be added.
**/
public int IndexOf(Item item) {
return items[typeof(Item)].IndexOf(item); }
/** `Remove()` : **`bool`**
*
* Removes the specified
*
* - `item` : **`Item`**
* Instance of `Item` to be added.
**/
public bool Remove(Item item) {
return Items[item.GetType()].Remove(item); }
/** `Remove()` : **`function`**
*
* Removes the specified
*
* - `item` : **`Item`**
* Instance of `Item` to be added.
**/
public bool Remove(List<Item> list) {
if (list==null) return false;
if (ContainsKey(list[0].GetType())) {
items[list[0].GetType()] = null;
return true;
} else return false;
}
public void Add(KeyValuePair<Type,List<Item>> kvp) {
items.Add(kvp.Key,kvp.Value); }
public void Clear() { items.Clear(); }
public bool Contains(KeyValuePair<Type,List<Item>> kvp) {
foreach (var elem in items)
if (elem.Key==kvp.Key && elem.Value==kvp.Value)
return true;
return false;
}
public bool ContainsKey(Type type) {
return items.ContainsKey(type); }
public bool ContainsValue(List<Item> list) {
return items.ContainsValue(list); }
public void CopyTo(Item[] list, int n) {
items[typeof(Item)].CopyTo(list,n); }
public bool Remove<T>() {
return Remove(typeof (T)); }
public bool Remove(Type type) {
return items.Remove(type); }
public bool Remove(KeyValuePair<Type,List<Item>> kvp) {
return items.Remove(kvp.Key); }
public bool TryGetValue<T>(out List<Item> list)
where T : Item {
foreach (var elem in items.Keys) {
if (elem==typeof (T)) {
list = items[typeof (T)];
return true;
}
} list = default(List<Item>); return false;
}
public bool TryGetValue(Type type, out List<Item> list) {
if (items.ContainsKey(type)) {
list = items[type]; return true; }
else { list = default(List<Item>); return false; }
}
IEnumerator IEnumerable.GetEnumerator() {
return (IEnumerator) GetEnumerator(); }
public IEnumerator<Item> GetEnumerator() {
return items[typeof(Item)].GetEnumerator(); }
public T GetItem<T>() where T : Item {
var temp = GetItems<T>();
foreach (var item in temp)
if (item is T) return (T) item;
return default (T);
}
/** `Log()` : **`string`**
*
* Specified by `ILoggable`, `Terminal` calls this
* function to get a special `string` to log.
**/
public string Log() {
var s = description.Template;
foreach (var item in this)
s += $"\n- {item}";
return s;
}
public List<T> GetItems<T>() where T : Item {
var list = new List<T>();
List<Item> temp;
if (items.TryGetValue(typeof (T),out temp)) {
foreach (var elem in temp)
list.Add((T) elem);
return list;
} return default (List<T>);
}
public class ItemSetEnum {
List<Item> items;
int position = -1;
public Item Current {
get {
try { return items[position]; }
catch (System.IndexOutOfRangeException) {
throw new System.Exception();
}
}
}
public ItemSetEnum(Item[] list) {
this.items = new List<Item>(list); }
public ItemSetEnum(List<Item> list) {
this.items = list; }
//public ItemSetEnum(List<List<Item>> lists) {
// this.items = new List<Item>(lists); }
public bool MoveNext() {
position++; return (position<items.Count); }
public void Reset() { position = -1; }
}
}
}
| |
// <copyright file="AppBuilder.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2013 Microsoft Open Technologies, Inc. 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
namespace Owin.Builder
{
// <summary>
// A standard implementation of IAppBuilder
// </summary>
internal class AppBuilder : IAppBuilder
{
private readonly IList<Tuple<Type, Delegate, object[]>> _middleware;
private readonly IDictionary<Tuple<Type, Type>, Delegate> _conversions;
private readonly IDictionary<string, object> _properties;
// <summary>
//
// </summary>
public AppBuilder()
{
_properties = new Dictionary<string, object>();
_conversions = new Dictionary<Tuple<Type, Type>, Delegate>();
_middleware = new List<Tuple<Type, Delegate, object[]>>();
_properties["builder.AddSignatureConversion"] = new Action<Delegate>(AddSignatureConversion);
}
// <summary>
//
// </summary>
// <param name="conversions"></param>
// <param name="properties"></param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design")]
public AppBuilder(
IDictionary<Tuple<Type, Type>, Delegate> conversions,
IDictionary<string, object> properties)
{
_properties = properties;
_conversions = conversions;
_middleware = new List<Tuple<Type, Delegate, object[]>>();
}
// <summary>
// Contains arbitrary properties which may added, examined, and modified by
// components during the startup sequence.
// </summary>
public IDictionary<string, object> Properties
{
get { return _properties; }
}
// <summary>
// Adds a middleware node to the OWIN function pipeline. The middleware are
// invoked in the order they are added: the first middleware passed to Use will
// be the outermost function, and the last middleware passed to Use will be the
// innermost.
// </summary>
// <param name="middleware">
// The middleware parameter determines which behavior is being chained into the
// pipeline.
//
// If the middleware given to Use is a Delegate, then it will be invoked with the "next app" in
// the chain as the first parameter. If the delegate takes more than the single argument,
// then the additional values must be provided to Use in the args array.
//
// If the middleware given to Use is a Type, then the public constructor will be
// invoked with the "next app" in the chain as the first parameter. The resulting object
// must have a public Invoke method. If the object has constructors which take more than
// the single "next app" argument, then additional values may be provided in the args array.
// </param>
// <param name="args">
// Any additional args passed to Use will be passed as additional values, following the "next app"
// parameter, when the OWIN call pipeline is build.
//
// They are passed as additional parameters if the middleware parameter is a Delegate, or as additional
// constructor arguments if the middle parameter is a Type.
// </param>
// <returns>
// The IAppBuilder itself is returned. This enables you to chain your use statements together.
// </returns>
public IAppBuilder Use(object middleware, params object[] args)
{
_middleware.Add(ToMiddlewareFactory(middleware, args));
return this;
}
// <summary>
// The New method creates a new instance of an IAppBuilder. This is needed to create
// a tree structure in your processing, rather than a linear pipeline. The new instance share the
// same Properties, but will be created with a new, empty middleware list.
//
// To create a tangent pipeline you would first call New, followed by several calls to Use on
// the new builder, ending with a call to Build on the new builder. The return value from Build
// will be the entry-point to your tangent pipeline. This entry-point may now be added to the
// main pipeline as an argument to a switching middleware, which will either call the tangent
// pipeline or the "next app", based on something in the request.
//
// That said - all of that work is typically hidden by a middleware like Map, which will do that
// for you.
// </summary>
// <returns>The new instance of the IAppBuilder implementation</returns>
public IAppBuilder New()
{
return new AppBuilder(_conversions, _properties);
}
// <summary>
// The Build is called at the point when all of the middleware should be chained
// together. This is typically done by the hosting component which created the app builder,
// and does not need to be called by the startup method if the IAppBuilder is passed in.
// </summary>
// <param name="returnType">
// The Type argument indicates which calling convention should be returned, and
// is typically typeof(<typeref name="Func<IDictionary<string,object>, Task>"/>) for the OWIN
// calling convention.
// </param>
// <returns>
// Returns an instance of the pipeline's entry point. This object may be safely cast to the
// type which was provided
// </returns>
public object Build(Type returnType)
{
return BuildInternal(returnType);
}
private void AddSignatureConversion(Delegate conversion)
{
if (conversion == null)
{
throw new ArgumentNullException("conversion");
}
Type parameterType = GetParameterType(conversion);
if (parameterType == null)
{
throw new ArgumentException("Conversion delegate must take one parameter", "conversion");
}
Tuple<Type, Type> key = Tuple.Create(conversion.Method.ReturnType, parameterType);
_conversions[key] = conversion;
}
private static Type GetParameterType(Delegate function)
{
ParameterInfo[] parameters = function.Method.GetParameters();
return parameters.Length == 1 ? parameters[0].ParameterType : null;
}
private object BuildInternal(Type signature)
{
object app;
if (!_properties.TryGetValue("builder.DefaultApp", out app))
{
app = new Func<IDictionary<string, object>, Task>(new NotFound().Invoke);
}
foreach (Tuple<Type, Delegate, object[]> middleware in _middleware.Reverse())
{
Type neededSignature = middleware.Item1;
Delegate middlewareDelegate = middleware.Item2;
object[] middlewareArgs = middleware.Item3;
app = Convert(neededSignature, app);
object[] invokeParameters = new[] { app }.Concat(middlewareArgs).ToArray();
app = middlewareDelegate.DynamicInvoke(invokeParameters);
app = Convert(neededSignature, app);
}
return Convert(signature, app);
}
private object Convert(Type signature, object app)
{
if (app == null)
{
return null;
}
object oneHop = ConvertOneHop(signature, app);
if (oneHop != null)
{
return oneHop;
}
object multiHop = ConvertMultiHop(signature, app);
if (multiHop != null)
{
return multiHop;
}
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture, "No conversion available between {0} and {1}", app.GetType(), signature),
"signature");
}
private object ConvertMultiHop(Type signature, object app)
{
foreach (KeyValuePair<Tuple<Type, Type>, Delegate> conversion in _conversions)
{
object preConversion = ConvertOneHop(conversion.Key.Item2, app);
if (preConversion == null)
{
continue;
}
object intermediate = conversion.Value.DynamicInvoke(preConversion);
if (intermediate == null)
{
continue;
}
object postConversion = ConvertOneHop(signature, intermediate);
if (postConversion == null)
{
continue;
}
return postConversion;
}
return null;
}
private object ConvertOneHop(Type signature, object app)
{
if (signature.IsInstanceOfType(app))
{
return app;
}
if (typeof(Delegate).IsAssignableFrom(signature))
{
Delegate memberDelegate = ToMemberDelegate(signature, app);
if (memberDelegate != null)
{
return memberDelegate;
}
}
foreach (KeyValuePair<Tuple<Type, Type>, Delegate> conversion in _conversions)
{
Type returnType = conversion.Key.Item1;
Type parameterType = conversion.Key.Item2;
if (parameterType.IsInstanceOfType(app) &&
signature.IsAssignableFrom(returnType))
{
return conversion.Value.DynamicInvoke(app);
}
}
return null;
}
private static Delegate ToMemberDelegate(Type signature, object app)
{
MethodInfo signatureMethod = signature.GetMethod("Invoke");
ParameterInfo[] signatureParameters = signatureMethod.GetParameters();
MethodInfo[] methods = app.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
if (method.Name != "Invoke")
{
continue;
}
ParameterInfo[] methodParameters = method.GetParameters();
if (methodParameters.Length != signatureParameters.Length)
{
continue;
}
if (methodParameters
.Zip(signatureParameters, (methodParameter, signatureParameter) => methodParameter.ParameterType.IsAssignableFrom(signatureParameter.ParameterType))
.Any(compatible => compatible == false))
{
continue;
}
if (!signatureMethod.ReturnType.IsAssignableFrom(method.ReturnType))
{
continue;
}
return Delegate.CreateDelegate(signature, app, method);
}
return null;
}
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "False positive")]
private static Tuple<Type, Delegate, object[]> ToMiddlewareFactory(object middlewareObject, object[] args)
{
if (middlewareObject == null)
{
throw new ArgumentNullException("middlewareObject");
}
Delegate middlewareDelegate = middlewareObject as Delegate;
if (middlewareDelegate != null)
{
return Tuple.Create(GetParameterType(middlewareDelegate), middlewareDelegate, args);
}
Tuple<Type, Delegate, object[]> factory = ToInstanceMiddlewareFactory(middlewareObject, args);
if (factory != null)
{
return factory;
}
factory = ToGeneratorMiddlewareFactory(middlewareObject, args);
if (factory != null)
{
return factory;
}
if (middlewareObject is Type)
{
return ToConstructorMiddlewareFactory(middlewareObject, args, ref middlewareDelegate);
}
throw new NotSupportedException((middlewareObject ?? string.Empty).ToString());
}
// Instance pattern: public void Initialize(AppFunc next, string arg1, string arg2), public Task Invoke(IDictionary<...> env)
private static Tuple<Type, Delegate, object[]> ToInstanceMiddlewareFactory(object middlewareObject, object[] args)
{
MethodInfo[] methods = middlewareObject.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
if (method.Name != "Initialize")
{
continue;
}
ParameterInfo[] parameters = method.GetParameters();
Type[] parameterTypes = parameters.Select(p => p.ParameterType).ToArray();
if (parameterTypes.Length != args.Length + 1)
{
continue;
}
if (!parameterTypes
.Skip(1)
.Zip(args, TestArgForParameter)
.All(x => x))
{
continue;
}
// DynamicInvoke can't handle a middleware with multiple args, just push the args in via closure.
Func<object, object> func = app =>
{
object[] invokeParameters = new[] { app }.Concat(args).ToArray();
method.Invoke(middlewareObject, invokeParameters);
return middlewareObject;
};
return Tuple.Create<Type, Delegate, object[]>(parameters[0].ParameterType, func, new object[0]);
}
return null;
}
// Delegate nesting pattern: public AppFunc Invoke(AppFunc app, string arg1, string arg2)
private static Tuple<Type, Delegate, object[]> ToGeneratorMiddlewareFactory(object middlewareObject, object[] args)
{
MethodInfo[] methods = middlewareObject.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
if (method.Name != "Invoke")
{
continue;
}
ParameterInfo[] parameters = method.GetParameters();
Type[] parameterTypes = parameters.Select(p => p.ParameterType).ToArray();
if (parameterTypes.Length != args.Length + 1)
{
continue;
}
if (!parameterTypes
.Skip(1)
.Zip(args, TestArgForParameter)
.All(x => x))
{
continue;
}
IEnumerable<Type> genericFuncTypes = parameterTypes.Concat(new[] { method.ReturnType });
Type funcType = Expression.GetFuncType(genericFuncTypes.ToArray());
Delegate middlewareDelegate = Delegate.CreateDelegate(funcType, middlewareObject, method);
return Tuple.Create(parameters[0].ParameterType, middlewareDelegate, args);
}
return null;
}
// Type Constructor pattern: public Delta(AppFunc app, string arg1, string arg2)
private static Tuple<Type, Delegate, object[]> ToConstructorMiddlewareFactory(object middlewareObject, object[] args, ref Delegate middlewareDelegate)
{
Type middlewareType = middlewareObject as Type;
ConstructorInfo[] constructors = middlewareType.GetConstructors();
foreach (ConstructorInfo constructor in constructors)
{
ParameterInfo[] parameters = constructor.GetParameters();
Type[] parameterTypes = parameters.Select(p => p.ParameterType).ToArray();
if (parameterTypes.Length != args.Length + 1)
{
continue;
}
if (!parameterTypes
.Skip(1)
.Zip(args, TestArgForParameter)
.All(x => x))
{
continue;
}
ParameterExpression[] parameterExpressions = parameters.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray();
NewExpression callConstructor = Expression.New(constructor, parameterExpressions);
middlewareDelegate = Expression.Lambda(callConstructor, parameterExpressions).Compile();
return Tuple.Create(parameters[0].ParameterType, middlewareDelegate, args);
}
throw new MissingMethodException(middlewareType.FullName, "ctor(" + (args.Length + 1) + ")");
}
private static bool TestArgForParameter(Type parameterType, object arg)
{
return (arg == null && !parameterType.IsValueType) ||
parameterType.IsInstanceOfType(arg);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Azure.Messaging.ServiceBus.Tests.Sender
{
public class SenderLiveTests : ServiceBusLiveTestBase
{
[Test]
public async Task SendConnStringWithSharedKey()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
[Test]
public async Task SendConnStringWithSignature()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions();
var audience = ServiceBusConnection.BuildConnectionResource(options.TransportType, TestEnvironment.FullyQualifiedNamespace, scope.QueueName);
var connectionString = TestEnvironment.BuildConnectionStringWithSharedAccessSignature(scope.QueueName, audience);
await using var sender = new ServiceBusClient(connectionString, options).CreateSender(scope.QueueName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
[Test]
public async Task SendToken()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.FullyQualifiedNamespace, TestEnvironment.Credential);
var sender = client.CreateSender(scope.QueueName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
[Test]
public async Task SendConnectionTopic()
{
await using (var scope = await ServiceBusScope.CreateWithTopic(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions
{
TransportType = ServiceBusTransportType.AmqpWebSockets,
WebProxy = WebRequest.DefaultWebProxy,
RetryOptions = new ServiceBusRetryOptions()
{
Mode = ServiceBusRetryMode.Exponential
}
};
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString, options);
ServiceBusSender sender = client.CreateSender(scope.TopicName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
[Test]
public async Task SendTopicSession()
{
await using (var scope = await ServiceBusScope.CreateWithTopic(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions
{
TransportType = ServiceBusTransportType.AmqpWebSockets,
WebProxy = WebRequest.DefaultWebProxy,
RetryOptions = new ServiceBusRetryOptions()
{
Mode = ServiceBusRetryMode.Exponential
}
};
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString, options);
ServiceBusSender sender = client.CreateSender(scope.TopicName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage("sessionId"));
}
}
[Test]
public async Task CanSendAMessageBatch()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
ServiceBusMessageBatch messageBatch = ServiceBusTestUtilities.AddMessages(batch, 3);
await sender.SendMessagesAsync(messageBatch);
}
}
[Test]
public async Task SendingEmptyBatchDoesNotThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task CanSendAnEmptyBodyMessageBatch()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
batch.TryAddMessage(new ServiceBusMessage(Array.Empty<byte>()));
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task CannotSendLargerThanMaximumSize()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
// Actual limit is set by the service; query it from the batch.
ServiceBusMessage message = new ServiceBusMessage(new byte[batch.MaxSizeInBytes + 10]);
Assert.That(async () => await sender.SendMessageAsync(message), Throws.InstanceOf<ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessageSizeExceeded));
}
}
[Test]
public async Task TryAddReturnsFalseIfSizeExceed()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
// Actual limit is set by the service; query it from the batch. Because this will be used for the
// message body, leave some padding for the conversion and batch envelope.
var padding = 500;
var size = (batch.MaxSizeInBytes - padding);
Assert.That(() => batch.TryAddMessage(new ServiceBusMessage(new byte[size])), Is.True, "A message was rejected by the batch; all messages should be accepted.");
Assert.That(() => batch.TryAddMessage(new ServiceBusMessage(new byte[padding + 1])), Is.False, "A message was rejected by the batch; message size exceed.");
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task ClientProperties()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
Assert.AreEqual(scope.QueueName, sender.EntityPath);
Assert.AreEqual(TestEnvironment.FullyQualifiedNamespace, sender.FullyQualifiedNamespace);
}
}
[Test]
public async Task Schedule()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var seq = await sender.ScheduleMessageAsync(ServiceBusTestUtilities.GetMessage(), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
await sender.CancelScheduledMessageAsync(seq);
msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
}
[Test]
public async Task ScheduleMultipleArray()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
await sender.CancelScheduledMessagesAsync(sequenceNumbers: sequenceNums);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty array
await sender.CancelScheduledMessagesAsync(sequenceNumbers: Array.Empty<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task ScheduleMultipleList()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
await sender.CancelScheduledMessagesAsync(sequenceNumbers: new List<long>(sequenceNums));
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty list
await sender.CancelScheduledMessagesAsync(sequenceNumbers: new List<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task ScheduleMultipleEnumerable()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
// use an enumerable
await sender.CancelScheduledMessagesAsync(sequenceNumbers: GetEnumerable());
IEnumerable<long> GetEnumerable()
{
foreach (long seq in sequenceNums)
{
yield return seq;
}
}
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty enumerable
await sender.CancelScheduledMessagesAsync(sequenceNumbers: Enumerable.Empty<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task CloseSenderShouldNotCloseConnection()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNum = await sender.ScheduleMessageAsync(ServiceBusTestUtilities.GetMessage(), scheduleTime);
await sender.DisposeAsync(); // shouldn't close connection, but should close send link
Assert.That(async () => await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage()), Throws.InstanceOf<ObjectDisposedException>());
Assert.That(async () => await sender.ScheduleMessageAsync(ServiceBusTestUtilities.GetMessage(), default), Throws.InstanceOf<ObjectDisposedException>());
Assert.That(async () => await sender.CancelScheduledMessageAsync(sequenceNum), Throws.InstanceOf<ObjectDisposedException>());
// receive should still work
await using var receiver = client.CreateReceiver(scope.QueueName);
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(sequenceNum);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
}
[Test]
public async Task CreateSenderWithoutParentReference()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
for (int i = 0; i < 10; i++)
{
await Task.Delay(1000);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
}
[Test]
public async Task SendSessionMessageToNonSessionfulEntityShouldNotThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
var sender = client.CreateSender(scope.QueueName);
// this is apparently supported. The session is ignored by the service but can be used
// as additional app data. Not recommended.
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage("sessionId"));
var receiver = client.CreateReceiver(scope.QueueName);
var msg = await receiver.ReceiveMessageAsync();
Assert.AreEqual("sessionId", msg.SessionId);
}
}
[Test]
public async Task SendNonSessionMessageToSessionfulEntityShouldThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: true))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
Assert.That(
async () => await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage()),
Throws.InstanceOf<InvalidOperationException>());
}
}
[Test]
public async Task CanSendReceivedMessage()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var client = new ServiceBusClient(
TestEnvironment.FullyQualifiedNamespace,
TestEnvironment.Credential);
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
var messageCt = 10;
IEnumerable<ServiceBusMessage> messages = ServiceBusTestUtilities.GetMessages(messageCt);
await sender.SendMessagesAsync(messages);
var receiver = client.CreateReceiver(scope.QueueName, new ServiceBusReceiverOptions()
{
ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete
});
var remainingMessages = messageCt;
IList<ServiceBusReceivedMessage> receivedMessages = new List<ServiceBusReceivedMessage>();
while (remainingMessages > 0)
{
foreach (var msg in await receiver.ReceiveMessagesAsync(messageCt))
{
remainingMessages--;
receivedMessages.Add(msg);
}
}
foreach (ServiceBusReceivedMessage msg in receivedMessages)
{
await sender.SendMessageAsync(new ServiceBusMessage(msg));
}
var messageEnum = receivedMessages.GetEnumerator();
remainingMessages = messageCt;
while (remainingMessages > 0)
{
foreach (var msg in await receiver.ReceiveMessagesAsync(remainingMessages))
{
remainingMessages--;
messageEnum.MoveNext();
Assert.AreEqual(messageEnum.Current.MessageId, msg.MessageId);
}
}
Assert.AreEqual(0, remainingMessages);
}
}
[Test]
public async Task CreateBatchThrowsIftheEntityDoesNotExist()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var connectionString = TestEnvironment.BuildConnectionStringForEntity("FakeEntity");
await using var client = new ServiceBusClient(connectionString);
ServiceBusSender sender = client.CreateSender("FakeEntity");
Assert.That(async () => await sender.CreateMessageBatchAsync(), Throws.InstanceOf<ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound));
}
}
[Test]
public async Task CreateBatchReactsToClosingTheClient()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
using var batch = await sender.CreateMessageBatchAsync();
// Close the client and attempt to create another batch.
await client.DisposeAsync();
Assert.That(async () => await sender.CreateMessageBatchAsync(),
Throws.InstanceOf<ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
}
}
[Test]
public async Task SendMessagesReactsToClosingTheClient()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
using var batch = ServiceBusTestUtilities.AddMessages((await sender.CreateMessageBatchAsync()), 5);
await sender.SendMessagesAsync(batch);
// Close the client and attempt to send another message batch.
using var anotherBatch = ServiceBusTestUtilities.AddMessages((await sender.CreateMessageBatchAsync()), 5);
await client.DisposeAsync();
Assert.That(async () => await sender.SendMessagesAsync(anotherBatch),
Throws.InstanceOf<ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
}
}
[Test]
public async Task ScheduleMessagesReactsToClosingTheClient()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
// Close the client and attempt to schedule another set of messages.
await client.DisposeAsync();
Assert.That(async () => await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime),
Throws.InstanceOf<ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
}
}
[Test]
public async Task CancelScheduledMessagesReactsToClosingTheClient()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var sequenceNumbers = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await sender.CancelScheduledMessagesAsync(sequenceNumbers);
// Close the client and attempt to cancel another set of scheduled messages.
sequenceNumbers = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await client.DisposeAsync();
Assert.That(async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers),
Throws.InstanceOf<ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
}
}
[Test]
public async Task CancellingSendDoesNotBlockSubsequentSends()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(20));
Assert.That(
async () => await sender.SendMessagesAsync(ServiceBusTestUtilities.GetMessages(300), cancellationTokenSource.Token),
Throws.InstanceOf<TaskCanceledException>());
var start = DateTime.UtcNow;
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
var end = DateTime.UtcNow;
Assert.Less(end - start, TimeSpan.FromSeconds(5));
}
}
}
}
| |
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using WPAppStudio.Helpers;
namespace WPAppStudio.Controls
{
public class CustomHtmlTextBlock : Control
{
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(
"Text",
typeof (string),
typeof (CustomHtmlTextBlock),
new PropertyMetadata("CustomHtmlTextBlock", OnTextPropertyChanged));
private TextBlock _measureBlock;
private StackPanel _stackPanel;
public CustomHtmlTextBlock()
{
// Get the style from generic.xaml
DefaultStyleKey = typeof (CustomHtmlTextBlock);
}
public string Text
{
get { return (string) GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (CustomHtmlTextBlock) d;
var value = (string) e.NewValue;
source.ParseText(value);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_stackPanel = GetTemplateChild("StackPanel") as StackPanel;
ParseText(Text);
}
private void ParseTextHide(string value)
{
if (_stackPanel == null)
{
return;
}
// Clear previous TextBlocks
_stackPanel.Children.Clear();
// Calculate max char count
int maxTexCount = GetMaxTextSize();
if (maxTexCount == 0)
maxTexCount = value.Length;
if (value.Length < maxTexCount)
{
TextBlock textBlock = GetTextBlock();
textBlock.Text = value;
_stackPanel.Children.Add(textBlock);
}
else
{
int n = value.Length/maxTexCount;
int start = 0;
// Add textblocks
for (int i = 0; i < n; i++)
{
TextBlock textBlock = GetTextBlock();
textBlock.Text = value.Substring(start, maxTexCount);
_stackPanel.Children.Add(textBlock);
start = maxTexCount;
}
// Pickup the leftover text
if (value.Length%maxTexCount > 0)
{
TextBlock textBlock = GetTextBlock();
textBlock.Text = value.Substring(maxTexCount*n, value.Length - maxTexCount*n);
_stackPanel.Children.Add(textBlock);
}
}
}
private void ParseText(string value)
{
var reader = new StringReader(value);
if (_stackPanel == null)
{
return;
}
// Clear previous TextBlocks
_stackPanel.Children.Clear();
// Calculate max char count
int maxTexCount = GetMaxTextSize();
if (maxTexCount == 0)
maxTexCount = value.Length;
if (value.Length < maxTexCount)
{
TextBlock textBlock = GetTextBlock();
textBlock.Text = value;
_stackPanel.Children.Add(textBlock);
}
else
{
while (reader.Peek() > 0)
{
string line = reader.ReadLine();
ParseLine(line);
}
}
}
private void ParseLine(string line)
{
int lineCount = 0;
int maxLineCount = GetMaxLineCount();
string tempLine = line;
var sbLine = new StringBuilder();
while (lineCount < maxLineCount)
{
int charactersFitted = MeasureString(tempLine, (int) Width);
string leftSide = tempLine.Substring(0, charactersFitted);
sbLine.Append(leftSide);
tempLine = tempLine.Substring(charactersFitted, tempLine.Length - (charactersFitted));
lineCount++;
}
TextBlock textBlock = GetTextBlock();
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Text = sbLine.ToString();
var wb = new WebBrowser {Height = 10*(textBlock.ActualWidth/320)};
wb.NavigateToString(WebBrowserHelper.WrapHtml(line, Application.Current.RootVisual.RenderSize.Width));
_stackPanel.Children.Add(wb);
if (tempLine.Length > 0)
ParseLine(tempLine);
}
private int MeasureString(string text, int desWidth)
{
int charactersFitted;
var sb = new StringBuilder();
//get original size
Size size = MeasureString(text);
if (size.Width > desWidth)
{
string[] words = text.Split(' ');
sb.Append(words[0]);
for (int i = 1; i < words.Length; i++)
{
sb.Append(" " + words[i]);
int nWidth = (int) MeasureString(sb.ToString()).Width;
if (nWidth > desWidth)
{
sb.Remove(sb.Length - words[i].Length, words[i].Length);
break;
}
}
charactersFitted = sb.Length;
}
else
{
charactersFitted = text.Length;
}
return charactersFitted;
}
private Size MeasureString(string text)
{
if (_measureBlock == null)
{
_measureBlock = GetTextBlock();
}
_measureBlock.Text = text;
return new Size(_measureBlock.ActualWidth, _measureBlock.ActualHeight);
}
private int GetMaxTextSize()
{
// Get average char size
Size size = MeasureText(" ");
// Get number of char that fit in the line
var charLineCount = (int) (Width/size.Width);
// Get line count
var lineCount = (int) (2048/size.Height);
return charLineCount*lineCount/2;
}
private int GetMaxLineCount()
{
Size size = MeasureText(" ");
// Get line count
int lineCount = (int) (2048/size.Height) - 5;
return lineCount;
}
private TextBlock GetTextBlock()
{
var textBlock = new TextBlock
{
TextWrapping = TextWrapping.Wrap,
FontSize = FontSize,
FontFamily = FontFamily,
FontStyle = FontStyle,
FontWeight = FontWeight,
Foreground = Foreground,
Margin = new Thickness(0, 0, MeasureText(" ").Width, 0)
};
return textBlock;
}
private Size MeasureText(string value)
{
TextBlock textBlock = GetTextBlockOnly();
textBlock.Text = value;
return new Size(textBlock.ActualWidth, textBlock.ActualHeight);
}
private TextBlock GetTextBlockOnly()
{
var textBlock = new TextBlock
{
TextWrapping = TextWrapping.Wrap,
FontSize = FontSize,
FontFamily = FontFamily,
FontWeight = FontWeight
};
return textBlock;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using AutoMapper.Configuration;
using AutoMapper.Features;
namespace AutoMapper
{
/// <summary>
/// Common mapping configuration options between generic and non-generic mapping configuration
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <typeparam name="TMappingExpression">Concrete return type for fluent interface</typeparam>
public interface IProjectionExpressionBase<TSource, TDestination, out TMappingExpression> where TMappingExpression : IProjectionExpressionBase<TSource, TDestination, TMappingExpression>
{
Features<IMappingFeature> Features { get; }
/// <summary>
/// For self-referential types, limit recurse depth.
/// Enables PreserveReferences.
/// </summary>
/// <param name="depth">Number of levels to limit to</param>
/// <returns>Itself</returns>
TMappingExpression MaxDepth(int depth);
/// <summary>
/// Value transformers, typically configured through explicit or extension methods.
/// </summary>
List<ValueTransformerConfiguration> ValueTransformers { get; }
/// <summary>
/// Specify which member list to validate
/// </summary>
/// <param name="memberList">Member list to validate</param>
/// <returns>Itself</returns>
TMappingExpression ValidateMemberList(MemberList memberList);
/// <summary>
/// Supply a custom instantiation expression for the destination type
/// </summary>
/// <param name="ctor">Expression to create the destination type given the source object</param>
/// <returns>Itself</returns>
TMappingExpression ConstructUsing(Expression<Func<TSource, TDestination>> ctor);
/// <summary>
/// Customize configuration for individual constructor parameter
/// </summary>
/// <param name="ctorParamName">Constructor parameter name</param>
/// <param name="paramOptions">Options</param>
/// <returns>Itself</returns>
TMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions);
/// <summary>
/// Skip member mapping and use a custom expression to convert to the destination type
/// </summary>
/// <param name="mappingExpression">Callback to convert from source type to destination type</param>
void ConvertUsing(Expression<Func<TSource, TDestination>> mappingExpression);
}
/// <summary>
/// Common mapping configuration options between generic and non-generic mapping configuration
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <typeparam name="TMappingExpression">Concrete return type for fluent interface</typeparam>
public interface IMappingExpressionBase<TSource, TDestination, out TMappingExpression> : IProjectionExpressionBase<TSource, TDestination, TMappingExpression>
where TMappingExpression : IMappingExpressionBase<TSource, TDestination, TMappingExpression>
{
/// <summary>
/// Disable constructor validation. During mapping this map is used against an existing destination object and never constructed itself.
/// </summary>
/// <returns>Itself</returns>
TMappingExpression DisableCtorValidation();
/// <summary>
/// Construct the destination object using the service locator
/// </summary>
/// <returns>Itself</returns>
TMappingExpression ConstructUsingServiceLocator();
/// <summary>
/// Preserve object identity. Useful for circular references.
/// </summary>
/// <returns>Itself</returns>
TMappingExpression PreserveReferences();
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
TMappingExpression BeforeMap(Action<TSource, TDestination> beforeFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
TMappingExpression BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction);
/// <summary>
/// Execute a custom mapping action before member mapping
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
TMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>;
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
TMappingExpression AfterMap(Action<TSource, TDestination> afterFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
TMappingExpression AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction);
/// <summary>
/// Execute a custom mapping action after member mapping
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
TMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>;
/// <summary>
/// Include this configuration in all derived types' maps. Works by scanning all type maps for matches during configuration.
/// </summary>
/// <returns>Itself</returns>
TMappingExpression IncludeAllDerived();
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <param name="derivedSourceType">Derived source type</param>
/// <param name="derivedDestinationType">Derived destination type</param>
/// <returns>Itself</returns>
TMappingExpression Include(Type derivedSourceType, Type derivedDestinationType);
/// <summary>
/// Include the base type map's configuration in this map
/// </summary>
/// <param name="sourceBase">Base source type</param>
/// <param name="destinationBase">Base destination type</param>
/// <returns></returns>
TMappingExpression IncludeBase(Type sourceBase, Type destinationBase);
/// <summary>
/// Customize configuration for an individual source member. Member name not known until runtime
/// </summary>
/// <param name="sourceMemberName">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
TMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Ignores all <typeparamref name="TDestination"/> properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter)
/// </summary>
/// <returns>Itself</returns>
TMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter();
/// <summary>
/// When using ReverseMap, ignores all <typeparamref name="TSource"/> properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: <typeparamref name="TDestination"/> properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used)
/// </summary>
/// <returns>Itself</returns>
TMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
/// <summary>
/// Supply a custom instantiation function for the destination type, based on the entire resolution context
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="ctor">Callback to create the destination type given the current resolution context</param>
/// <returns>Itself</returns>
TMappingExpression ConstructUsing(Func<TSource, ResolutionContext, TDestination> ctor);
/// <summary>
/// Override the destination type mapping for looking up configuration and instantiation
/// </summary>
/// <param name="typeOverride"></param>
void As(Type typeOverride);
/// <summary>
/// Create at runtime a proxy type implementing the destination interface.
/// </summary>
void AsProxy();
/// <summary>
/// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
/// Use this method if you need to specify the converter type at runtime
/// </summary>
/// <param name="typeConverterType">Type converter type</param>
void ConvertUsing(Type typeConverterType);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="mappingFunction">Callback to convert from source type to destination type, including destination object</param>
void ConvertUsing(Func<TSource, TDestination, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="mappingFunction">Callback to convert from source type to destination type, with source, destination and context</param>
void ConvertUsing(Func<TSource, TDestination, ResolutionContext, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom type converter instance to convert to the destination type
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="converter">Type converter instance</param>
void ConvertUsing(ITypeConverter<TSource, TDestination> converter);
/// <summary>
/// Skip member mapping and use a custom type converter instance to convert to the destination type
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <typeparam name="TTypeConverter">Type converter type</typeparam>
void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;
}
/// <summary>
/// Custom mapping action
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
public interface IMappingAction<in TSource, in TDestination>
{
/// <summary>
/// Implementors can modify both the source and destination objects
/// </summary>
/// <param name="source">Source object</param>
/// <param name="destination">Destination object</param>
/// <param name="context">Resolution context</param>
void Process(TSource source, TDestination destination, ResolutionContext context);
}
/// <summary>
/// Converts source type to destination type instead of normal member mapping
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
public interface ITypeConverter<in TSource, TDestination>
{
/// <summary>
/// Performs conversion from source to destination type
/// </summary>
/// <param name="source">Source object</param>
/// <param name="destination">Destination object</param>
/// <param name="context">Resolution context</param>
/// <returns>Destination object</returns>
TDestination Convert(TSource source, TDestination destination, ResolutionContext context);
}
}
| |
// 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.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public class MutexTests : RemoteExecutorTestBase
{
private const int FailedWaitTimeout = 30000;
[Fact]
public void Ctor_ConstructWaitRelease()
{
using (Mutex m = new Mutex())
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(false))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(true))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
m.ReleaseMutex();
}
}
[Fact]
public void Ctor_InvalidName()
{
AssertExtensions.Throws<ArgumentException>("name", null, () => new Mutex(false, new string('a', 1000)));
}
[Fact]
public void Ctor_ValidName()
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (Mutex m1 = new Mutex(false, name, out createdNew))
{
Assert.True(createdNew);
using (Mutex m2 = new Mutex(false, name, out createdNew))
{
Assert.False(createdNew);
}
}
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore s = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name));
}
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWinRT))] // Can't create global objects in appcontainer
[SkipOnTargetFramework(
TargetFrameworkMonikers.NetFramework,
"The fix necessary for this test (PR https://github.com/dotnet/coreclr/pull/12381) is not in the .NET Framework.")]
public void Ctor_ImpersonateAnonymousAndTryCreateGlobalMutexTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
if (!ImpersonateAnonymousToken(GetCurrentThread()))
{
// Impersonation is not allowed in the current context, this test is inappropriate in such a case
return;
}
Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N")));
Assert.True(RevertToSelf());
});
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsWinRT))] // Can't create global objects in appcontainer
[PlatformSpecific(TestPlatforms.Windows)]
public void Ctor_TryCreateGlobalMutexTest_Uwp()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N"))));
}
[Fact]
public void OpenExisting()
{
string name = Guid.NewGuid().ToString("N");
Mutex resultHandle;
Assert.False(Mutex.TryOpenExisting(name, out resultHandle));
using (Mutex m1 = new Mutex(false, name))
{
using (Mutex m2 = Mutex.OpenExisting(name))
{
Assert.True(m1.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m1.ReleaseMutex();
Assert.True(m2.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m2.ReleaseMutex();
}
Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
[Fact]
public void OpenExisting_InvalidNames()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null));
AssertExtensions.Throws<ArgumentException>("name", null, () => Mutex.OpenExisting(string.Empty));
AssertExtensions.Throws<ArgumentException>("name", null, () => Mutex.OpenExisting(new string('a', 10000)));
}
[Fact]
public void OpenExisting_UnavailableName()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore sema = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
}
private static IEnumerable<string> GetNamePrefixes()
{
yield return string.Empty;
yield return "Local\\";
// Creating global sync objects is not allowed in UWP apps
if (!PlatformDetection.IsUap)
{
yield return "Global\\";
}
}
public static IEnumerable<object[]> AbandonExisting_MemberData()
{
var nameGuidStr = Guid.NewGuid().ToString("N");
for (int waitType = 0; waitType < 2; ++waitType) // 0 == WaitOne, 1 == WaitAny
{
yield return new object[] { null, waitType };
foreach (var namePrefix in GetNamePrefixes())
{
yield return new object[] { namePrefix + nameGuidStr, waitType };
}
}
}
[Theory]
[MemberData(nameof(AbandonExisting_MemberData))]
public void AbandonExisting(string name, int waitType)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
using (var m = new Mutex(false, name))
{
Task t = Task.Factory.StartNew(() =>
{
Assert.True(m.WaitOne(FailedWaitTimeout));
// don't release the mutex; abandon it on this thread
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
Assert.True(t.Wait(FailedWaitTimeout));
switch (waitType)
{
case 0: // WaitOne
Assert.Throws<AbandonedMutexException>(() => m.WaitOne(FailedWaitTimeout));
break;
case 1: // WaitAny
AbandonedMutexException ame = Assert.Throws<AbandonedMutexException>(() => WaitHandle.WaitAny(new[] { m }, FailedWaitTimeout));
Assert.Equal(0, ame.MutexIndex);
Assert.Equal(m, ame.Mutex);
break;
}
}
});
}
public static IEnumerable<object[]> CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData()
{
var nameGuidStr = Guid.NewGuid().ToString("N");
foreach (var namePrefix in GetNamePrefixes())
{
yield return new object[] { namePrefix + nameGuidStr };
}
}
[Theory]
[MemberData(nameof(CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData))]
public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
string mutexName = prefix + Guid.NewGuid().ToString("N");
string fileName = GetTestFilePath();
Func<string, string, int> otherProcess = (m, f) =>
{
using (var mutex = Mutex.OpenExisting(m))
{
mutex.WaitOne();
try
{ File.WriteAllText(f, "0"); }
finally { mutex.ReleaseMutex(); }
IncrementValueInFileNTimes(mutex, f, 10);
}
return SuccessExitCode;
};
using (var mutex = new Mutex(false, mutexName))
using (var remote = RemoteInvoke(otherProcess, mutexName, fileName))
{
SpinWait.SpinUntil(() => File.Exists(fileName));
IncrementValueInFileNTimes(mutex, fileName, 10);
}
Assert.Equal(20, int.Parse(File.ReadAllText(fileName)));
});
}
private static void IncrementValueInFileNTimes(Mutex mutex, string fileName, int n)
{
for (int i = 0; i < n; i++)
{
mutex.WaitOne();
try
{
int current = int.Parse(File.ReadAllText(fileName));
Thread.Sleep(10);
File.WriteAllText(fileName, (current + 1).ToString());
}
finally { mutex.ReleaseMutex(); }
}
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentThread();
[DllImport("advapi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ImpersonateAnonymousToken(IntPtr threadHandle);
[DllImport("advapi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RevertToSelf();
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElastiCache.Model
{
/// <summary>
/// Container for the parameters to the ModifyCacheCluster operation.
/// The <i>ModifyCacheCluster</i> action modifies the settings for a cache cluster. You
/// can use this action to change one or more cluster configuration parameters by specifying
/// the parameters and the new values.
/// </summary>
public partial class ModifyCacheClusterRequest : AmazonElastiCacheRequest
{
private bool? _applyImmediately;
private bool? _autoMinorVersionUpgrade;
private AZMode _azMode;
private string _cacheClusterId;
private List<string> _cacheNodeIdsToRemove = new List<string>();
private string _cacheParameterGroupName;
private List<string> _cacheSecurityGroupNames = new List<string>();
private string _engineVersion;
private List<string> _newAvailabilityZones = new List<string>();
private string _notificationTopicArn;
private string _notificationTopicStatus;
private int? _numCacheNodes;
private string _preferredMaintenanceWindow;
private List<string> _securityGroupIds = new List<string>();
private int? _snapshotRetentionLimit;
private string _snapshotWindow;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public ModifyCacheClusterRequest() { }
/// <summary>
/// Instantiates ModifyCacheClusterRequest with the parameterized properties
/// </summary>
/// <param name="cacheClusterId">The cache cluster identifier. This value is stored as a lowercase string.</param>
public ModifyCacheClusterRequest(string cacheClusterId)
{
_cacheClusterId = cacheClusterId;
}
/// <summary>
/// Gets and sets the property ApplyImmediately.
/// <para>
/// If <code>true</code>, this parameter causes the modifications in this request and
/// any pending modifications to be applied, asynchronously and as soon as possible, regardless
/// of the <i>PreferredMaintenanceWindow</i> setting for the cache cluster.
/// </para>
///
/// <para>
/// If <code>false</code>, then changes to the cache cluster are applied on the next maintenance
/// reboot, or the next failure reboot, whichever occurs first.
/// </para>
/// <important>If you perform a <code>ModifyCacheCluster</code> before a pending modification
/// is applied, the pending modification is replaced by the newer modification.</important>
///
/// <para>
/// Valid values: <code>true</code> | <code>false</code>
/// </para>
///
/// <para>
/// Default: <code>false</code>
/// </para>
/// </summary>
public bool ApplyImmediately
{
get { return this._applyImmediately.GetValueOrDefault(); }
set { this._applyImmediately = value; }
}
// Check to see if ApplyImmediately property is set
internal bool IsSetApplyImmediately()
{
return this._applyImmediately.HasValue;
}
/// <summary>
/// Gets and sets the property AutoMinorVersionUpgrade.
/// <para>
/// This parameter is currently disabled.
/// </para>
/// </summary>
public bool AutoMinorVersionUpgrade
{
get { return this._autoMinorVersionUpgrade.GetValueOrDefault(); }
set { this._autoMinorVersionUpgrade = value; }
}
// Check to see if AutoMinorVersionUpgrade property is set
internal bool IsSetAutoMinorVersionUpgrade()
{
return this._autoMinorVersionUpgrade.HasValue;
}
/// <summary>
/// Gets and sets the property AZMode.
/// <para>
/// Specifies whether the new nodes in this Memcached cache cluster are all created in
/// a single Availability Zone or created across multiple Availability Zones.
/// </para>
///
/// <para>
/// Valid values: <code>single-az</code> | <code>cross-az</code>.
/// </para>
///
/// <para>
/// This option is only supported for Memcached cache clusters.
/// </para>
/// <note>
/// <para>
/// You cannot specify <code>single-az</code> if the Memcached cache cluster already has
/// cache nodes in different Availability Zones. If <code>cross-az</code> is specified,
/// existing Memcached nodes remain in their current Availability Zone.
/// </para>
///
/// <para>
/// Only newly created nodes will be located in different Availability Zones. For instructions
/// on how to move existing Memcached nodes to different Availability Zones, see the <b>Availability
/// Zone Considerations</b> section of <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheNode.Memcached.html">Cache
/// Node Considerations for Memcached</a>.
/// </para>
/// </note>
/// </summary>
public AZMode AZMode
{
get { return this._azMode; }
set { this._azMode = value; }
}
// Check to see if AZMode property is set
internal bool IsSetAZMode()
{
return this._azMode != null;
}
/// <summary>
/// Gets and sets the property CacheClusterId.
/// <para>
/// The cache cluster identifier. This value is stored as a lowercase string.
/// </para>
/// </summary>
public string CacheClusterId
{
get { return this._cacheClusterId; }
set { this._cacheClusterId = value; }
}
// Check to see if CacheClusterId property is set
internal bool IsSetCacheClusterId()
{
return this._cacheClusterId != null;
}
/// <summary>
/// Gets and sets the property CacheNodeIdsToRemove.
/// <para>
/// A list of cache node IDs to be removed. A node ID is a numeric identifier (0001, 0002,
/// etc.). This parameter is only valid when <i>NumCacheNodes</i> is less than the existing
/// number of cache nodes. The number of cache node IDs supplied in this parameter must
/// match the difference between the existing number of cache nodes in the cluster or
/// pending cache nodes, whichever is greater, and the value of <i>NumCacheNodes</i> in
/// the request.
/// </para>
///
/// <para>
/// For example: If you have 3 active cache nodes, 7 pending cache nodes, and the number
/// of cache nodes in this <code>ModifyCacheCluser</code> call is 5, you must list 2 (7
/// - 5) cache node IDs to remove.
/// </para>
/// </summary>
public List<string> CacheNodeIdsToRemove
{
get { return this._cacheNodeIdsToRemove; }
set { this._cacheNodeIdsToRemove = value; }
}
// Check to see if CacheNodeIdsToRemove property is set
internal bool IsSetCacheNodeIdsToRemove()
{
return this._cacheNodeIdsToRemove != null && this._cacheNodeIdsToRemove.Count > 0;
}
/// <summary>
/// Gets and sets the property CacheParameterGroupName.
/// <para>
/// The name of the cache parameter group to apply to this cache cluster. This change
/// is asynchronously applied as soon as possible for parameters when the <i>ApplyImmediately</i>
/// parameter is specified as <i>true</i> for this request.
/// </para>
/// </summary>
public string CacheParameterGroupName
{
get { return this._cacheParameterGroupName; }
set { this._cacheParameterGroupName = value; }
}
// Check to see if CacheParameterGroupName property is set
internal bool IsSetCacheParameterGroupName()
{
return this._cacheParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property CacheSecurityGroupNames.
/// <para>
/// A list of cache security group names to authorize on this cache cluster. This change
/// is asynchronously applied as soon as possible.
/// </para>
///
/// <para>
/// This parameter can be used only with clusters that are created outside of an Amazon
/// Virtual Private Cloud (VPC).
/// </para>
///
/// <para>
/// Constraints: Must contain no more than 255 alphanumeric characters. Must not be "Default".
/// </para>
/// </summary>
public List<string> CacheSecurityGroupNames
{
get { return this._cacheSecurityGroupNames; }
set { this._cacheSecurityGroupNames = value; }
}
// Check to see if CacheSecurityGroupNames property is set
internal bool IsSetCacheSecurityGroupNames()
{
return this._cacheSecurityGroupNames != null && this._cacheSecurityGroupNames.Count > 0;
}
/// <summary>
/// Gets and sets the property EngineVersion.
/// <para>
/// The upgraded version of the cache engine to be run on the cache nodes.
/// </para>
/// </summary>
public string EngineVersion
{
get { return this._engineVersion; }
set { this._engineVersion = value; }
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this._engineVersion != null;
}
/// <summary>
/// Gets and sets the property NewAvailabilityZones.
/// <para>
/// The list of Availability Zones where the new Memcached cache nodes will be created.
/// </para>
///
/// <para>
/// This parameter is only valid when <i>NumCacheNodes</i> in the request is greater than
/// the sum of the number of active cache nodes and the number of cache nodes pending
/// creation (which may be zero). The number of Availability Zones supplied in this list
/// must match the cache nodes being added in this request.
/// </para>
///
/// <para>
/// This option is only supported on Memcached clusters.
/// </para>
///
/// <para>
/// Scenarios: <ul> <li> <b>Scenario 1:</b> You have 3 active nodes and wish to add 2
/// nodes. Specify <code>NumCacheNodes=5</code> (3 + 2) and optionally specify two Availability
/// Zones for the two new nodes.</li> <li> <b>Scenario 2:</b> You have 3 active nodes
/// and 2 nodes pending creation (from the scenario 1 call) and want to add 1 more node.
/// Specify <code>NumCacheNodes=6</code> ((3 + 2) + 1)</li> and optionally specify an
/// Availability Zone for the new node. <li> <b>Scenario 3:</b> You want to cancel all
/// pending actions. Specify <code>NumCacheNodes=3</code> to cancel all pending actions.</li>
/// </ul>
/// </para>
///
/// <para>
/// The Availability Zone placement of nodes pending creation cannot be modified. If you
/// wish to cancel any nodes pending creation, add 0 nodes by setting <code>NumCacheNodes</code>
/// to the number of current nodes.
/// </para>
///
/// <para>
/// If <code>cross-az</code> is specified, existing Memcached nodes remain in their current
/// Availability Zone. Only newly created nodes can be located in different Availability
/// Zones. For guidance on how to move existing Memcached nodes to different Availability
/// Zones, see the <b>Availability Zone Considerations</b> section of <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheNode.Memcached.html">Cache
/// Node Considerations for Memcached</a>.
/// </para>
///
/// <para>
/// <b>Impact of new add/remove requests upon pending requests</b>
/// </para>
/// <table> <tr> <th>Scenarios</th> <th>Pending action</th> <th>New Request</th> <th>Results</th>
/// </tr> <tr> <td>Scenario-1</td> <td>Delete</td> <td>Delete</td> <td>The new delete,
/// pending or immediate, replaces the pending delete.</td> </tr> <tr> <td>Scenario-2</td>
/// <td>Delete</td> <td>Create</td> <td>The new create, pending or immediate, replaces
/// the pending delete.</td> </tr> <tr> <td>Scenario-3</td> <td>Create</td> <td>Delete</td>
/// <td>The new delete, pending or immediate, replaces the pending create.</td> </tr>
/// <tr> <td>Scenario-4</td> <td>Create</td> <td>Create</td> <td>The new create is added
/// to the pending create.<br/> <b>Important:</b><br/>If the new create request is <b>Apply
/// Immediately - Yes</b>, all creates are performed immediately. If the new create request
/// is <b>Apply Immediately - No</b>, all creates are pending.</td> </tr> </table>
/// <para>
/// Example: <code>NewAvailabilityZones.member.1=us-west-2a&NewAvailabilityZones.member.2=us-west-2b&NewAvailabilityZones.member.3=us-west-2c</code>
/// </para>
/// </summary>
public List<string> NewAvailabilityZones
{
get { return this._newAvailabilityZones; }
set { this._newAvailabilityZones = value; }
}
// Check to see if NewAvailabilityZones property is set
internal bool IsSetNewAvailabilityZones()
{
return this._newAvailabilityZones != null && this._newAvailabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property NotificationTopicArn.
/// <para>
/// The Amazon Resource Name (ARN) of the Amazon SNS topic to which notifications will
/// be sent.
/// </para>
/// <note>The Amazon SNS topic owner must be same as the cache cluster owner. </note>
/// </summary>
public string NotificationTopicArn
{
get { return this._notificationTopicArn; }
set { this._notificationTopicArn = value; }
}
// Check to see if NotificationTopicArn property is set
internal bool IsSetNotificationTopicArn()
{
return this._notificationTopicArn != null;
}
/// <summary>
/// Gets and sets the property NotificationTopicStatus.
/// <para>
/// The status of the Amazon SNS notification topic. Notifications are sent only if the
/// status is <i>active</i>.
/// </para>
///
/// <para>
/// Valid values: <code>active</code> | <code>inactive</code>
/// </para>
/// </summary>
public string NotificationTopicStatus
{
get { return this._notificationTopicStatus; }
set { this._notificationTopicStatus = value; }
}
// Check to see if NotificationTopicStatus property is set
internal bool IsSetNotificationTopicStatus()
{
return this._notificationTopicStatus != null;
}
/// <summary>
/// Gets and sets the property NumCacheNodes.
/// <para>
/// The number of cache nodes that the cache cluster should have. If the value for <code>NumCacheNodes</code>
/// is greater than the sum of the number of current cache nodes and the number of cache
/// nodes pending creation (which may be zero), then more nodes will be added. If the
/// value is less than the number of existing cache nodes, then nodes will be removed.
/// If the value is equal to the number of current cache nodes, then any pending add or
/// remove requests are canceled.
/// </para>
///
/// <para>
/// If you are removing cache nodes, you must use the <code>CacheNodeIdsToRemove</code>
/// parameter to provide the IDs of the specific cache nodes to remove.
/// </para>
///
/// <para>
/// For clusters running Redis, this value must be 1. For clusters running Memcached,
/// this value must be between 1 and 20.
/// </para>
///
/// <para>
/// <b>Note:</b>Adding or removing Memcached cache nodes can be applied immediately or
/// as a pending action. See <code>ApplyImmediately</code>. A pending action to modify
/// the number of cache nodes in a cluster during its maintenance window, whether by adding
/// or removing nodes in accordance with the scale out architecture, is not queued. The
/// customer's latest request to add or remove nodes to the cluster overrides any previous
/// pending actions to modify the number of cache nodes in the cluster. For example, a
/// request to remove 2 nodes would override a previous pending action to remove 3 nodes.
/// Similarly, a request to add 2 nodes would override a previous pending action to remove
/// 3 nodes and vice versa. As Memcached cache nodes may now be provisioned in different
/// Availability Zones with flexible cache node placement, a request to add nodes does
/// not automatically override a previous pending action to add nodes. The customer can
/// modify the previous pending action to add more nodes or explicitly cancel the pending
/// request and retry the new request. To cancel pending actions to modify the number
/// of cache nodes in a cluster, use the <code>ModifyCacheCluster</code> request and set
/// <i>NumCacheNodes</i> equal to the number of cache nodes currently in the cache cluster.
/// </para>
/// </summary>
public int NumCacheNodes
{
get { return this._numCacheNodes.GetValueOrDefault(); }
set { this._numCacheNodes = value; }
}
// Check to see if NumCacheNodes property is set
internal bool IsSetNumCacheNodes()
{
return this._numCacheNodes.HasValue;
}
/// <summary>
/// Gets and sets the property PreferredMaintenanceWindow.
/// <para>
/// Specifies the weekly time range during which maintenance on the cache cluster is performed.
/// It is specified as a range in the format ddd:hh24:mi-ddd:hh24:mi (24H Clock UTC).
/// The minimum maintenance window is a 60 minute period. Valid values for <code>ddd</code>
/// are:
/// </para>
/// <ul> <li><code>sun</code></li> <li><code>mon</code></li> <li><code>tue</code></li>
/// <li><code>wed</code></li> <li><code>thu</code></li> <li><code>fri</code></li> <li><code>sat</code></li>
/// </ul>
/// <para>
/// Example: <code>sun:05:00-sun:09:00</code>
/// </para>
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this._preferredMaintenanceWindow; }
set { this._preferredMaintenanceWindow = value; }
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this._preferredMaintenanceWindow != null;
}
/// <summary>
/// Gets and sets the property SecurityGroupIds.
/// <para>
/// Specifies the VPC Security Groups associated with the cache cluster.
/// </para>
///
/// <para>
/// This parameter can be used only with clusters that are created in an Amazon Virtual
/// Private Cloud (VPC).
/// </para>
/// </summary>
public List<string> SecurityGroupIds
{
get { return this._securityGroupIds; }
set { this._securityGroupIds = value; }
}
// Check to see if SecurityGroupIds property is set
internal bool IsSetSecurityGroupIds()
{
return this._securityGroupIds != null && this._securityGroupIds.Count > 0;
}
/// <summary>
/// Gets and sets the property SnapshotRetentionLimit.
/// <para>
/// The number of days for which ElastiCache will retain automatic cache cluster snapshots
/// before deleting them. For example, if you set <i>SnapshotRetentionLimit</i> to 5,
/// then a snapshot that was taken today will be retained for 5 days before being deleted.
/// </para>
///
/// <para>
/// <b>Important</b>If the value of SnapshotRetentionLimit is set to zero (0), backups
/// are turned off.
/// </para>
/// </summary>
public int SnapshotRetentionLimit
{
get { return this._snapshotRetentionLimit.GetValueOrDefault(); }
set { this._snapshotRetentionLimit = value; }
}
// Check to see if SnapshotRetentionLimit property is set
internal bool IsSetSnapshotRetentionLimit()
{
return this._snapshotRetentionLimit.HasValue;
}
/// <summary>
/// Gets and sets the property SnapshotWindow.
/// <para>
/// The daily time range (in UTC) during which ElastiCache will begin taking a daily snapshot
/// of your cache cluster.
/// </para>
/// </summary>
public string SnapshotWindow
{
get { return this._snapshotWindow; }
set { this._snapshotWindow = value; }
}
// Check to see if SnapshotWindow property is set
internal bool IsSetSnapshotWindow()
{
return this._snapshotWindow != null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using ForwardingLoggerRecord = Microsoft.Build.Logging.ForwardingLoggerRecord;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Shared;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Instance
{
/// <summary>
/// Tests for ProjectInstance public members
/// </summary>
public class ProjectInstance_Tests
{
/// <summary>
/// Verify that a cloned off project instance can see environment variables
/// </summary>
[Fact]
public void CreateProjectInstancePassesEnvironment()
{
Project p = new Project();
ProjectInstance i = p.CreateProjectInstance();
Assert.True(i.GetPropertyValue("username") != null);
}
/// <summary>
/// Read off properties
/// </summary>
[Fact]
public void PropertiesAccessors()
{
ProjectInstance p = GetSampleProjectInstance();
Assert.Equal("v1", p.GetPropertyValue("p1"));
Assert.Equal("v2X", p.GetPropertyValue("p2"));
}
/// <summary>
/// Read off items
/// </summary>
[Fact]
public void ItemsAccessors()
{
ProjectInstance p = GetSampleProjectInstance();
IList<ProjectItemInstance> items = Helpers.MakeList(p.GetItems("i"));
Assert.Equal(3, items.Count);
Assert.Equal("i", items[0].ItemType);
Assert.Equal("i0", items[0].EvaluatedInclude);
Assert.Equal(String.Empty, items[0].GetMetadataValue("m"));
Assert.Null(items[0].GetMetadata("m"));
Assert.Equal("i1", items[1].EvaluatedInclude);
Assert.Equal("m1", items[1].GetMetadataValue("m"));
Assert.Equal("m1", items[1].GetMetadata("m").EvaluatedValue);
Assert.Equal("v1", items[2].EvaluatedInclude);
}
/// <summary>
/// Add item
/// </summary>
[Fact]
public void AddItemWithoutMetadata()
{
ProjectInstance p = GetEmptyProjectInstance();
ProjectItemInstance returned = p.AddItem("i", "i1");
Assert.Equal("i", returned.ItemType);
Assert.Equal("i1", returned.EvaluatedInclude);
Assert.False(returned.Metadata.GetEnumerator().MoveNext());
foreach (ProjectItemInstance item in p.Items)
{
Assert.Equal("i1", item.EvaluatedInclude);
Assert.False(item.Metadata.GetEnumerator().MoveNext());
}
}
/// <summary>
/// Add item
/// </summary>
[Fact]
public void AddItemWithoutMetadata_Escaped()
{
ProjectInstance p = GetEmptyProjectInstance();
ProjectItemInstance returned = p.AddItem("i", "i%3b1");
Assert.Equal("i", returned.ItemType);
Assert.Equal("i;1", returned.EvaluatedInclude);
Assert.False(returned.Metadata.GetEnumerator().MoveNext());
foreach (ProjectItemInstance item in p.Items)
{
Assert.Equal("i;1", item.EvaluatedInclude);
Assert.False(item.Metadata.GetEnumerator().MoveNext());
}
}
/// <summary>
/// Add item with metadata
/// </summary>
[Fact]
public void AddItemWithMetadata()
{
ProjectInstance p = GetEmptyProjectInstance();
var metadata = new List<KeyValuePair<string, string>>();
metadata.Add(new KeyValuePair<string, string>("m", "m1"));
metadata.Add(new KeyValuePair<string, string>("n", "n1"));
metadata.Add(new KeyValuePair<string, string>("o", "o%40"));
ProjectItemInstance returned = p.AddItem("i", "i1", metadata);
Assert.True(object.ReferenceEquals(returned, Helpers.MakeList(p.GetItems("i"))[0]));
foreach (ProjectItemInstance item in p.Items)
{
Assert.Same(returned, item);
Assert.Equal("i1", item.EvaluatedInclude);
var metadataOut = Helpers.MakeList(item.Metadata);
Assert.Equal(3, metadataOut.Count);
Assert.Equal("m1", item.GetMetadataValue("m"));
Assert.Equal("n1", item.GetMetadataValue("n"));
Assert.Equal("o@", item.GetMetadataValue("o"));
}
}
/// <summary>
/// Add item null item type
/// </summary>
[Fact]
public void AddItemInvalidNullItemType()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectInstance p = GetEmptyProjectInstance();
p.AddItem(null, "i1");
}
);
}
/// <summary>
/// Add item empty item type
/// </summary>
[Fact]
public void AddItemInvalidEmptyItemType()
{
Assert.Throws<ArgumentException>(() =>
{
ProjectInstance p = GetEmptyProjectInstance();
p.AddItem(String.Empty, "i1");
}
);
}
/// <summary>
/// Add item null include
/// </summary>
[Fact]
public void AddItemInvalidNullInclude()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectInstance p = GetEmptyProjectInstance();
p.AddItem("i", null);
}
);
}
/// <summary>
/// Add item null metadata
/// </summary>
[Fact]
public void AddItemNullMetadata()
{
ProjectInstance p = GetEmptyProjectInstance();
ProjectItemInstance item = p.AddItem("i", "i1", null);
Assert.False(item.Metadata.GetEnumerator().MoveNext());
}
/// <summary>
/// It's okay to set properties that are also global properties, masking their value
/// </summary>
[Fact]
public void SetGlobalPropertyOnInstance()
{
Dictionary<string, string> globals = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "p", "p1" } };
Project p = new Project(ProjectRootElement.Create(), globals, null);
ProjectInstance instance = p.CreateProjectInstance();
instance.SetProperty("p", "p2");
Assert.Equal("p2", instance.GetPropertyValue("p"));
// And clearing it should not expose the original global property value
instance.SetProperty("p", "");
Assert.Equal("", instance.GetPropertyValue("p"));
}
/// <summary>
/// ProjectInstance itself is cloned properly
/// </summary>
[Fact]
public void CloneProjectItself()
{
ProjectInstance first = GetSampleProjectInstance();
ProjectInstance second = first.DeepCopy();
Assert.False(Object.ReferenceEquals(first, second));
}
/// <summary>
/// Properties are cloned properly
/// </summary>
[Fact]
public void CloneProperties()
{
ProjectInstance first = GetSampleProjectInstance();
ProjectInstance second = first.DeepCopy();
Assert.False(Object.ReferenceEquals(first.GetProperty("p1"), second.GetProperty("p1")));
ProjectPropertyInstance newProperty = first.SetProperty("p1", "v1b");
Assert.True(Object.ReferenceEquals(newProperty, first.GetProperty("p1")));
Assert.Equal("v1b", first.GetPropertyValue("p1"));
Assert.Equal("v1", second.GetPropertyValue("p1"));
}
/// <summary>
/// Passing an item list into another list should copy the metadata too
/// </summary>
[Fact]
public void ItemEvaluationCopiesMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>m1</m>
<n>n%3b%3b</n>
</i>
<j Include='@(i)'/>
</ItemGroup>
</Project>";
ProjectInstance project = GetProjectInstance(content);
Assert.Single(Helpers.MakeList(project.GetItems("j")));
Assert.Equal("i1", Helpers.MakeList(project.GetItems("j"))[0].EvaluatedInclude);
Assert.Equal("m1", Helpers.MakeList(project.GetItems("j"))[0].GetMetadataValue("m"));
Assert.Equal("n;;", Helpers.MakeList(project.GetItems("j"))[0].GetMetadataValue("n"));
}
/// <summary>
/// Wildcards are expanded in item groups inside targets, and the evaluatedinclude
/// is not the wildcard itself!
/// </summary>
[Fact]
[Trait("Category", "serialize")]
public void WildcardsInsideTargets()
{
string directory = null;
string file1 = null;
string file2 = null;
string file3 = null;
try
{
directory = Path.Combine(Path.GetTempPath(), "WildcardsInsideTargets");
Directory.CreateDirectory(directory);
file1 = Path.Combine(directory, "a.exe");
file2 = Path.Combine(directory, "b.exe");
file3 = Path.Combine(directory, "c.bat");
File.WriteAllText(file1, String.Empty);
File.WriteAllText(file2, String.Empty);
File.WriteAllText(file3, String.Empty);
string path = Path.Combine(directory, "*.exe");
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<ItemGroup>
<i Include='" + path + @"'/>
</ItemGroup>
</Target>
</Project>";
ProjectInstance projectInstance = GetProjectInstance(content);
projectInstance.Build();
Assert.Equal(2, Helpers.MakeList(projectInstance.GetItems("i")).Count);
Assert.Equal(file1, Helpers.MakeList(projectInstance.GetItems("i"))[0].EvaluatedInclude);
Assert.Equal(file2, Helpers.MakeList(projectInstance.GetItems("i"))[1].EvaluatedInclude);
}
finally
{
File.Delete(file1);
File.Delete(file2);
File.Delete(file3);
FileUtilities.DeleteWithoutTrailingBackslash(directory);
}
}
/// <summary>
/// Items are cloned properly
/// </summary>
[Fact]
public void CloneItems()
{
ProjectInstance first = GetSampleProjectInstance();
ProjectInstance second = first.DeepCopy();
Assert.False(Object.ReferenceEquals(Helpers.MakeList(first.GetItems("i"))[0], Helpers.MakeList(second.GetItems("i"))[0]));
first.AddItem("i", "i3");
Assert.Equal(4, Helpers.MakeList(first.GetItems("i")).Count);
Assert.Equal(3, Helpers.MakeList(second.GetItems("i")).Count);
}
/// <summary>
/// Null target in array should give ArgumentNullException
/// </summary>
[Fact]
public void BuildNullTargetInArray()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create());
instance.Build(new string[] { null }, null);
}
);
}
/// <summary>
/// Null logger in array should give ArgumentNullException
/// </summary>
[Fact]
public void BuildNullLoggerInArray()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create());
instance.Build("t", new ILogger[] { null });
}
);
}
/// <summary>
/// Null remote logger in array should give ArgumentNullException
/// </summary>
[Fact]
public void BuildNullRemoteLoggerInArray()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create());
instance.Build("t", null, new ForwardingLoggerRecord[] { null });
}
);
}
/// <summary>
/// Null target name should imply the default target
/// </summary>
[Fact]
[Trait("Category", "serialize")]
public void BuildNullTargetNameIsDefaultTarget()
{
ProjectRootElement xml = ProjectRootElement.Create();
xml.AddTarget("t").AddTask("Message").SetParameter("Text", "[OK]");
ProjectInstance instance = new ProjectInstance(xml);
MockLogger logger = new MockLogger();
string target = null;
instance.Build(target, new ILogger[] { logger });
logger.AssertLogContains("[OK]");
}
/// <summary>
/// Build system should correctly reset itself between builds of
/// project instances.
/// </summary>
[Fact]
[Trait("Category", "serialize")]
public void BuildProjectInstancesConsecutively()
{
ProjectInstance instance1 = new Project().CreateProjectInstance();
BuildRequestData buildRequestData1 = new BuildRequestData(instance1, new string[] { });
BuildManager.DefaultBuildManager.Build(new BuildParameters(), buildRequestData1);
new Project().CreateProjectInstance();
BuildRequestData buildRequestData2 = new BuildRequestData(instance1, new string[] { });
BuildManager.DefaultBuildManager.Build(new BuildParameters(), buildRequestData2);
}
/// <summary>
/// Verifies that the built-in metadata for specialized ProjectInstances is present when items are the simplest (no macros or wildcards).
/// </summary>
[Fact]
public void CreateProjectInstanceWithItemsContainingProjects()
{
const string CapturedMetadataName = "DefiningProjectFullPath";
var pc = new ProjectCollection();
var projA = ProjectRootElement.Create(pc);
var projB = ProjectRootElement.Create(pc);
projA.FullPath = Path.Combine(Path.GetTempPath(), "a.proj");
projB.FullPath = Path.Combine(Path.GetTempPath(), "b.proj");
projB.AddImport("a.proj");
projA.AddItem("Compile", "aItem.cs");
projB.AddItem("Compile", "bItem.cs");
var projBEval = new Project(projB, null, null, pc);
var projBInstance = projBEval.CreateProjectInstance();
var projBInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "bItem.cs").Single();
var projAInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "aItem.cs").Single();
Assert.Equal(projB.FullPath, projBInstanceItem.GetMetadataValue(CapturedMetadataName));
Assert.Equal(projA.FullPath, projAInstanceItem.GetMetadataValue(CapturedMetadataName));
// Although GetMetadataValue returns non-null, GetMetadata returns null...
Assert.Null(projAInstanceItem.GetMetadata(CapturedMetadataName));
// .. Just like built-in metadata does: (this segment just demonstrates similar functionality -- it's not meant to test built-in metadata)
Assert.NotNull(projAInstanceItem.GetMetadataValue("Identity"));
Assert.Null(projAInstanceItem.GetMetadata("Identity"));
Assert.True(projAInstanceItem.HasMetadata(CapturedMetadataName));
Assert.False(projAInstanceItem.Metadata.Any());
Assert.Contains(CapturedMetadataName, projAInstanceItem.MetadataNames);
Assert.Equal(projAInstanceItem.MetadataCount, projAInstanceItem.MetadataNames.Count);
}
/// <summary>
/// Verifies that the built-in metadata for specialized ProjectInstances is present when items are based on wildcards in the construction model.
/// </summary>
[Fact]
public void DefiningProjectItemBuiltInMetadataFromWildcards()
{
const string CapturedMetadataName = "DefiningProjectFullPath";
var pc = new ProjectCollection();
var projA = ProjectRootElement.Create(pc);
var projB = ProjectRootElement.Create(pc);
string tempDir = Path.GetTempFileName();
File.Delete(tempDir);
Directory.CreateDirectory(tempDir);
File.Create(Path.Combine(tempDir, "aItem.cs")).Dispose();
projA.FullPath = Path.Combine(tempDir, "a.proj");
projB.FullPath = Path.Combine(tempDir, "b.proj");
projB.AddImport("a.proj");
projA.AddItem("Compile", "*.cs");
projB.AddItem("CompileB", "@(Compile)");
var projBEval = new Project(projB, null, null, pc);
var projBInstance = projBEval.CreateProjectInstance();
var projAInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "aItem.cs").Single();
var projBInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("CompileB", "aItem.cs").Single();
Assert.Equal(projA.FullPath, projAInstanceItem.GetMetadataValue(CapturedMetadataName));
Assert.Equal(projB.FullPath, projBInstanceItem.GetMetadataValue(CapturedMetadataName));
Assert.True(projAInstanceItem.HasMetadata(CapturedMetadataName));
Assert.False(projAInstanceItem.Metadata.Any());
Assert.Contains(CapturedMetadataName, projAInstanceItem.MetadataNames);
Assert.Equal(projAInstanceItem.MetadataCount, projAInstanceItem.MetadataNames.Count);
}
/// <summary>
/// Validate that the DefiningProject* metadata is set to the correct project based on a variety
/// of means of item creation.
/// </summary>
[Fact]
public void TestDefiningProjectMetadata()
{
string projectA = Path.Combine(ObjectModelHelpers.TempProjectDir, "a.proj");
string projectB = Path.Combine(ObjectModelHelpers.TempProjectDir, "b.proj");
string includeFileA = Path.Combine(ObjectModelHelpers.TempProjectDir, "aaa4.cs");
string includeFileB = Path.Combine(ObjectModelHelpers.TempProjectDir, "bbb4.cs");
string contentsA =
@"<?xml version=`1.0` encoding=`utf-8`?>
<Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`Validate` xmlns=`msbuildnamespace`>
<ItemGroup>
<A Include=`aaaa.cs` />
<A2 Include=`aaa2.cs` />
<A2 Include=`aaa3.cs`>
<Foo>Bar</Foo>
</A2>
</ItemGroup>
<Import Project=`b.proj` />
<ItemGroup>
<E Include=`@(C)` />
<F Include=`@(C);@(C2)` />
<G Include=`@(C->'%(Filename)')` />
<H Include=`@(C2->WithMetadataValue('Foo', 'Bar'))` />
<U Include=`*4.cs` />
</ItemGroup>
<Target Name=`AddFromMainProject`>
<ItemGroup>
<B Include=`bbbb.cs` />
<I Include=`@(C)` />
<J Include=`@(C);@(C2)` />
<K Include=`@(C->'%(Filename)')` />
<L Include=`@(C2->WithMetadataValue('Foo', 'Bar'))` />
<V Include=`*4.cs` />
</ItemGroup>
</Target>
<Target Name=`Validate` DependsOnTargets=`AddFromMainProject;AddFromImport`>
<Warning Text=`A is wrong: EXPECTED: [a] ACTUAL: [%(A.DefiningProjectName)]` Condition=`'%(A.DefiningProjectName)' != 'a'` />
<Warning Text=`B is wrong: EXPECTED: [a] ACTUAL: [%(B.DefiningProjectName)]` Condition=`'%(B.DefiningProjectName)' != 'a'` />
<Warning Text=`C is wrong: EXPECTED: [b] ACTUAL: [%(C.DefiningProjectName)]` Condition=`'%(C.DefiningProjectName)' != 'b'` />
<Warning Text=`D is wrong: EXPECTED: [b] ACTUAL: [%(D.DefiningProjectName)]` Condition=`'%(D.DefiningProjectName)' != 'b'` />
<Warning Text=`E is wrong: EXPECTED: [a] ACTUAL: [%(E.DefiningProjectName)]` Condition=`'%(E.DefiningProjectName)' != 'a'` />
<Warning Text=`F is wrong: EXPECTED: [a] ACTUAL: [%(F.DefiningProjectName)]` Condition=`'%(F.DefiningProjectName)' != 'a'` />
<Warning Text=`G is wrong: EXPECTED: [a] ACTUAL: [%(G.DefiningProjectName)]` Condition=`'%(G.DefiningProjectName)' != 'a'` />
<Warning Text=`H is wrong: EXPECTED: [a] ACTUAL: [%(H.DefiningProjectName)]` Condition=`'%(H.DefiningProjectName)' != 'a'` />
<Warning Text=`I is wrong: EXPECTED: [a] ACTUAL: [%(I.DefiningProjectName)]` Condition=`'%(I.DefiningProjectName)' != 'a'` />
<Warning Text=`J is wrong: EXPECTED: [a] ACTUAL: [%(J.DefiningProjectName)]` Condition=`'%(J.DefiningProjectName)' != 'a'` />
<Warning Text=`K is wrong: EXPECTED: [a] ACTUAL: [%(K.DefiningProjectName)]` Condition=`'%(K.DefiningProjectName)' != 'a'` />
<Warning Text=`L is wrong: EXPECTED: [a] ACTUAL: [%(L.DefiningProjectName)]` Condition=`'%(L.DefiningProjectName)' != 'a'` />
<Warning Text=`M is wrong: EXPECTED: [b] ACTUAL: [%(M.DefiningProjectName)]` Condition=`'%(M.DefiningProjectName)' != 'b'` />
<Warning Text=`N is wrong: EXPECTED: [b] ACTUAL: [%(N.DefiningProjectName)]` Condition=`'%(N.DefiningProjectName)' != 'b'` />
<Warning Text=`O is wrong: EXPECTED: [b] ACTUAL: [%(O.DefiningProjectName)]` Condition=`'%(O.DefiningProjectName)' != 'b'` />
<Warning Text=`P is wrong: EXPECTED: [b] ACTUAL: [%(P.DefiningProjectName)]` Condition=`'%(P.DefiningProjectName)' != 'b'` />
<Warning Text=`Q is wrong: EXPECTED: [b] ACTUAL: [%(Q.DefiningProjectName)]` Condition=`'%(Q.DefiningProjectName)' != 'b'` />
<Warning Text=`R is wrong: EXPECTED: [b] ACTUAL: [%(R.DefiningProjectName)]` Condition=`'%(R.DefiningProjectName)' != 'b'` />
<Warning Text=`S is wrong: EXPECTED: [b] ACTUAL: [%(S.DefiningProjectName)]` Condition=`'%(S.DefiningProjectName)' != 'b'` />
<Warning Text=`T is wrong: EXPECTED: [b] ACTUAL: [%(T.DefiningProjectName)]` Condition=`'%(T.DefiningProjectName)' != 'b'` />
<Warning Text=`U is wrong: EXPECTED: [a] ACTUAL: [%(U.DefiningProjectName)]` Condition=`'%(U.DefiningProjectName)' != 'a'` />
<Warning Text=`V is wrong: EXPECTED: [a] ACTUAL: [%(V.DefiningProjectName)]` Condition=`'%(V.DefiningProjectName)' != 'a'` />
<Warning Text=`W is wrong: EXPECTED: [b] ACTUAL: [%(W.DefiningProjectName)]` Condition=`'%(W.DefiningProjectName)' != 'b'` />
<Warning Text=`X is wrong: EXPECTED: [b] ACTUAL: [%(X.DefiningProjectName)]` Condition=`'%(X.DefiningProjectName)' != 'b'` />
</Target>
</Project>";
string contentsB =
@"<?xml version=`1.0` encoding=`utf-8`?>
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<C Include=`cccc.cs` />
<C2 Include=`ccc2.cs` />
<C2 Include=`ccc3.cs`>
<Foo>Bar</Foo>
</C2>
<M Include=`@(A)` />
<N Include=`@(A);@(A2)` />
<O Include=`@(A->'%(Filename)')` />
<P Include=`@(A2->WithMetadataValue('Foo', 'Bar'))` />
<W Include=`*4.cs` />
</ItemGroup>
<Target Name=`AddFromImport`>
<ItemGroup>
<D Include=`dddd.cs` />
<Q Include=`@(A)` />
<R Include=`@(A);@(A2)` />
<S Include=`@(A->'%(Filename)')` />
<T Include=`@(A2->WithMetadataValue('Foo', 'Bar'))` />
<X Include=`*4.cs` />
</ItemGroup>
</Target>
</Project>";
try
{
File.WriteAllText(projectA, ObjectModelHelpers.CleanupFileContents(contentsA));
File.WriteAllText(projectB, ObjectModelHelpers.CleanupFileContents(contentsB));
File.WriteAllText(includeFileA, "aaaaaaa");
File.WriteAllText(includeFileB, "bbbbbbb");
MockLogger logger = ObjectModelHelpers.BuildTempProjectFileExpectSuccess("a.proj");
logger.AssertNoWarnings();
}
finally
{
if (File.Exists(projectA))
{
File.Delete(projectA);
}
if (File.Exists(projectB))
{
File.Delete(projectB);
}
if (File.Exists(includeFileA))
{
File.Delete(includeFileA);
}
if (File.Exists(includeFileB))
{
File.Delete(includeFileB);
}
}
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetProperty()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.SetProperty("a", "b"); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_RemoveProperty()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.RemoveProperty("p1"); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_RemoveItem()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.RemoveItem(Helpers.GetFirst(instance.Items)); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_AddItem()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.AddItem("a", "b"); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_AddItemWithMetadata()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.AddItem("a", "b", new List<KeyValuePair<string, string>>()); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_Build()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.Build(); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetEvaluatedInclude()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).EvaluatedInclude = "x"; });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetEvaluatedIncludeEscaped()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { ((ITaskItem2)Helpers.GetFirst(instance.Items)).EvaluatedIncludeEscaped = "x"; });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetItemSpec()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { ((ITaskItem2)Helpers.GetFirst(instance.Items)).ItemSpec = "x"; });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetMetadataOnItem1()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { ((ITaskItem2)Helpers.GetFirst(instance.Items)).SetMetadataValueLiteral("a", "b"); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetMetadataOnItem2()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).SetMetadata(new List<KeyValuePair<string, string>>()); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetMetadataOnItem3()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).SetMetadata("a", "b"); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_RemoveMetadataFromItem()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).RemoveMetadata("n"); });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetEvaluatedValueOnProperty()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Properties).EvaluatedValue = "v2"; });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetEvaluatedValueOnPropertyFromProject()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("p1").EvaluatedValue = "v2"; });
}
/// <summary>
/// Test operation fails on immutable project instance
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetNewProperty()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.SetProperty("newproperty", "v2"); });
}
/// <summary>
/// Setting global properties should fail if the project is immutable, even though the property
/// was originally created as mutable
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetGlobalProperty()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.SetProperty("g", "gv2"); });
}
/// <summary>
/// Setting environment originating properties should fail if the project is immutable, even though the property
/// was originally created as mutable
/// </summary>
[Fact]
public void ImmutableProjectInstance_SetEnvironmentProperty()
{
var instance = GetSampleProjectInstance(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.SetProperty("username", "someone_else_here"); });
}
/// <summary>
/// Cloning inherits unless otherwise specified
/// </summary>
[Fact]
public void ImmutableProjectInstance_CloneMutableFromImmutable()
{
var protoInstance = GetSampleProjectInstance(true /* immutable */);
var instance = protoInstance.DeepCopy(false /* mutable */);
// These should not throw
instance.SetProperty("p", "pnew");
instance.AddItem("i", "ii");
Helpers.GetFirst(instance.Items).EvaluatedInclude = "new";
instance.SetProperty("g", "gnew");
instance.SetProperty("username", "someone_else_here");
}
/// <summary>
/// Cloning inherits unless otherwise specified
/// </summary>
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void ImmutableProjectInstance_CloneImmutableFromMutable()
{
var protoInstance = GetSampleProjectInstance(false /* mutable */);
var instance = protoInstance.DeepCopy(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("g").EvaluatedValue = "v2"; });
Helpers.VerifyAssertThrowsInvalidOperation(
delegate
{
instance.GetProperty(NativeMethodsShared.IsWindows ? "username" : "USER").EvaluatedValue =
"someone_else_here";
});
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Properties).EvaluatedValue = "v2"; });
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; });
}
/// <summary>
/// Cloning inherits unless otherwise specified
/// </summary>
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void ImmutableProjectInstance_CloneImmutableFromImmutable()
{
var protoInstance = GetSampleProjectInstance(true /* immutable */);
var instance = protoInstance.DeepCopy(/* inherit */);
// Should not have bothered cloning
Assert.True(Object.ReferenceEquals(protoInstance, instance));
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("g").EvaluatedValue = "v2"; });
Helpers.VerifyAssertThrowsInvalidOperation(
delegate
{
instance.GetProperty(NativeMethodsShared.IsWindows ? "username" : "USER").EvaluatedValue =
"someone_else_here";
});
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Properties).EvaluatedValue = "v2"; });
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; });
}
/// <summary>
/// Cloning inherits unless otherwise specified
/// </summary>
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void ImmutableProjectInstance_CloneImmutableFromImmutable2()
{
var protoInstance = GetSampleProjectInstance(true /* immutable */);
var instance = protoInstance.DeepCopy(true /* immutable */);
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("g").EvaluatedValue = "v2"; });
Helpers.VerifyAssertThrowsInvalidOperation(
delegate
{
instance.GetProperty(NativeMethodsShared.IsWindows ? "username" : "USER").EvaluatedValue =
"someone_else_here";
});
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Properties).EvaluatedValue = "v2"; });
Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; });
}
/// <summary>
/// Cloning inherits unless otherwise specified
/// </summary>
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void ImmutableProjectInstance_CloneMutableFromMutable()
{
var protoInstance = GetSampleProjectInstance(false /* mutable */);
var instance = protoInstance.DeepCopy(/* inherit */);
// These should not throw
instance.SetProperty("p", "pnew");
instance.AddItem("i", "ii");
Helpers.GetFirst(instance.Items).EvaluatedInclude = "new";
instance.SetProperty("g", "gnew");
instance.SetProperty("username", "someone_else_here");
}
/// <summary>
/// Cloning inherits unless otherwise specified
/// </summary>
[Fact]
public void ImmutableProjectInstance_CloneMutableFromMutable2()
{
var protoInstance = GetSampleProjectInstance(false /* mutable */);
var instance = protoInstance.DeepCopy(false /* mutable */);
// These should not throw
instance.SetProperty("p", "pnew");
instance.AddItem("i", "ii");
Helpers.GetFirst(instance.Items).EvaluatedInclude = "new";
instance.SetProperty("g", "gnew");
instance.SetProperty("username", "someone_else_here");
}
/// <summary>
/// Create a ProjectInstance with some items and properties and targets
/// </summary>
private static ProjectInstance GetSampleProjectInstance(bool isImmutable = false)
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<n>n1</n>
</i>
</ItemDefinitionGroup>
<PropertyGroup>
<p1>v1</p1>
<p2>v2</p2>
<p2>$(p2)X$(p)</p2>
</PropertyGroup>
<ItemGroup>
<i Include='i0'/>
<i Include='i1'>
<m>m1</m>
</i>
<i Include='$(p1)'/>
</ItemGroup>
<Target Name='t'>
<t1 a='a1' b='b1' ContinueOnError='coe' Condition='c'/>
<t2/>
</Target>
<Target Name='tt'/>
</Project>
";
ProjectInstance p = GetProjectInstance(content, isImmutable);
return p;
}
/// <summary>
/// Create a ProjectInstance from provided project content
/// </summary>
private static ProjectInstance GetProjectInstance(string content, bool immutable = false)
{
var globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
globalProperties["g"] = "gv";
Project project = new Project(XmlReader.Create(new StringReader(content)), globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion);
ProjectInstance instance = immutable ? project.CreateProjectInstance(ProjectInstanceSettings.Immutable) : project.CreateProjectInstance();
return instance;
}
/// <summary>
/// Create a ProjectInstance that's empty
/// </summary>
private static ProjectInstance GetEmptyProjectInstance()
{
ProjectRootElement xml = ProjectRootElement.Create();
Project project = new Project(xml);
ProjectInstance instance = project.CreateProjectInstance();
return instance;
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
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
*/
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Security.Permissions;
using FluorineFx.Reflection.Lightweight;
using log4net;
using FluorineFx.AMF3;
using FluorineFx.Configuration;
using FluorineFx.Exceptions;
namespace FluorineFx.IO.Bytecode.Lightweight
{
delegate object CreateInstanceInvoker();
delegate object ReadDataInvoker(AMFReader reader, ClassDefinition classDefinition);
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
class AMF0ReflectionOptimizer : IReflectionOptimizer
{
private static readonly ILog log = LogManager.GetLogger(typeof(AMF0ReflectionOptimizer));
private CreateInstanceInvoker _createInstanceMethod;
private ReadDataInvoker _readDataMethod;
#if !(MONO) && !(NET_2_0) && !(NET_3_5) && !(SILVERLIGHT)
PermissionSet _ps;
#endif
public AMF0ReflectionOptimizer(Type type, AMFReader reader, object instance)
{
_createInstanceMethod = CreateCreateInstanceMethod(type);
_readDataMethod = CreateReadDataMethod(type, reader, instance);
#if !(MONO) && !(NET_2_0) && !(NET_3_5) && !(SILVERLIGHT)
_ps = new PermissionSet(PermissionState.None);
_ps.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
#endif
}
private CreateInstanceInvoker CreateCreateInstanceMethod(System.Type type)
{
DynamicMethod method = new DynamicMethod(string.Empty, typeof(object), null, type, true);
ILGenerator il = method.GetILGenerator();
ConstructorInfo constructor = type.GetConstructor(EmitHelper.AnyVisibilityInstance, null, CallingConventions.HasThis, System.Type.EmptyTypes, null);
il.Emit(OpCodes.Newobj, constructor);
il.Emit(OpCodes.Ret);
return (CreateInstanceInvoker)method.CreateDelegate(typeof(CreateInstanceInvoker));
}
protected virtual ReadDataInvoker CreateReadDataMethod(Type type, AMFReader reader, object instance)
{
#if !(MONO) && !(NET_2_0) && !(NET_3_5) && !(SILVERLIGHT)
bool canSkipChecks = _ps.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
#else
bool canSkipChecks = SecurityManager.IsGranted(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
#endif
DynamicMethod method = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(AMFReader), typeof(ClassDefinition) }, this.GetType(), canSkipChecks);
ILGenerator il = method.GetILGenerator();
LocalBuilder instanceLocal = il.DeclareLocal(type);//[0] instance
LocalBuilder typeCodeLocal = il.DeclareLocal(typeof(byte));//[1] uint8 typeCode
LocalBuilder keyLocal = il.DeclareLocal(typeof(string));//[2] string key
LocalBuilder objTmp = il.DeclareLocal(typeof(object));//[3] temp object store
LocalBuilder intTmp1 = il.DeclareLocal(typeof(int));//[4] temp int store, length
LocalBuilder intTmp2 = il.DeclareLocal(typeof(int));//[5] temp int store, index
LocalBuilder objTmp2 = il.DeclareLocal(typeof(object));//[6] temp object store
LocalBuilder typeTmp = il.DeclareLocal(typeof(Type));//[7] temp Type store
EmitHelper emit = new EmitHelper(il);
ConstructorInfo typeConstructor = type.GetConstructor(EmitHelper.AnyVisibilityInstance, null, CallingConventions.HasThis, System.Type.EmptyTypes, null);
MethodInfo miAddReference = typeof(AMFReader).GetMethod("AddReference");
MethodInfo miReadString = typeof(AMFReader).GetMethod("ReadString");
MethodInfo miReadByte = typeof(AMFReader).GetMethod("ReadByte");
emit
//object instance = new object();
.newobj(typeConstructor) //Create the new instance and push the object reference onto the evaluation stack
.stloc_0 //Pop from the top of the evaluation stack and store it in a the local variable list at index 0
//reader.AddReference(instance);
.ldarg_0 //Push the argument indexed at 1 onto the evaluation stack 'reader'
.ldloc_0 //Loads the local variable at index 0 onto the evaluation stack 'instance'
.callvirt(miAddReference) //Arguments are popped from the stack, the method call is performed, return value is pushed onto the stack
//typeCode = 0;
.ldc_i4_0 //Push the integer value of 0 onto the evaluation stack as an int32
.stloc_1 //Pop and store it in a the local variable list at index 1
//string key = null;
.ldnull //Push a null reference onto the evaluation stack
.stloc_2 //Pop and store it in a the local variable list at index 2 'key'
.end()
;
string key = reader.ReadString();
for (byte typeCode = reader.ReadByte(); typeCode != AMF0TypeCode.EndOfObject; typeCode = reader.ReadByte())
{
emit
.ldarg_0
.callvirt(miReadString)
.stloc_2
.ldarg_0
.callvirt(miReadByte)
.stloc_1
.end()
;
object value = reader.ReadData(typeCode);
reader.SetMember(instance, key, value);
MemberInfo[] memberInfos = type.GetMember(key);
if (memberInfos != null && memberInfos.Length > 0)
GeneratePropertySet(emit, typeCode, memberInfos[0]);
else
{
//Log this error (do not throw exception), otherwise our current AMF stream becomes unreliable
log.Warn(__Res.GetString(__Res.Optimizer_Warning));
string msg = __Res.GetString(__Res.Reflection_MemberNotFound, string.Format("{0}.{1}", type.FullName, key));
log.Warn(msg);
//reader.ReadAMF3Data(typeCode);
emit
.ldarg_0 //Push 'reader'
.ldloc_1 //Push 'typeCode'
.callvirt(typeof(AMFReader).GetMethod("ReadData", new Type[] { typeof(byte) }))
.pop
.end()
;
}
key = reader.ReadString();
}
Label labelExit = emit.DefineLabel();
ConstructorInfo exceptionConstructor = typeof(UnexpectedAMF).GetConstructor(EmitHelper.AnyVisibilityInstance, null, CallingConventions.HasThis, Type.EmptyTypes, null);
//key = reader.ReadString();
emit
.ldarg_0 //Push 'reader'
.callvirt(miReadString)
.stloc_2 //Pop 'key'
//typeCode = reader.ReadByte();
.ldarg_0 //Push 'reader'
.callvirt(miReadByte)
.stloc_1 //Pop 'typeCode'
.ldloc_1
.ldc_i4_s(AMF0TypeCode.EndOfObject)
.ceq
.brtrue_s(labelExit)
//if( typeCode != AMF0TypeCode.EndOfObject ) throw new UnexpectedAMF();
.newobj(exceptionConstructor)
.@throw
.end()
;
emit
.MarkLabel(labelExit)
//return instance;
.ldloc_0 //Load the local variable at index 0 onto the evaluation stack
.ret() //Return
;
return (ReadDataInvoker)method.CreateDelegate(typeof(ReadDataInvoker));
}
protected bool DoTypeCheck()
{
return FluorineConfiguration.Instance.OptimizerSettings.TypeCheck;
}
private void GeneratePropertySet(EmitHelper emit, int typeCode, MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo.MemberType == MemberTypes.Property)
{
PropertyInfo propertyInfo = memberInfo.DeclaringType.GetProperty(memberInfo.Name);
memberType = propertyInfo.PropertyType;
}
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = memberInfo.DeclaringType.GetField(memberInfo.Name);
memberType = fieldInfo.FieldType;
}
if (memberType == null)
throw new ArgumentNullException(memberInfo.Name);
//The primitive types are: Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Double, Single
//We handle here Decimal types too
if (memberType.IsPrimitive || memberType == typeof(decimal))
{
TypeCode primitiveTypeCode = Type.GetTypeCode(memberType);
switch (primitiveTypeCode)
{
case TypeCode.Byte:
case TypeCode.Decimal:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
{
#region Primitive numeric
Label labelNotNumber = emit.ILGenerator.DefineLabel();
Label labelExit = emit.ILGenerator.DefineLabel();
//if( typeCode == AMF0TypeCode.Number )
emit
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.Number)
.ceq
.brfalse_s(labelNotNumber)
//instance.{0} = ({1})reader.ReadDouble();
.ldloc_0 //Push 'instance'
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadDouble"))
.GeneratePrimitiveCast(primitiveTypeCode)
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelNotNumber)
.GenerateThrowUnexpectedAMFException(memberInfo)
.MarkLabel(labelExit)
//.nop
.end()
;
#endregion Primitive numeric
}
break;
case TypeCode.Boolean:
{
#region Primitive boolean
Label labelNotBoolean = emit.ILGenerator.DefineLabel();
Label labelExit = emit.ILGenerator.DefineLabel();
//if( typeCode == AMF0TypeCode.Boolean )
emit
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.Boolean)
.ceq
.brfalse_s(labelNotBoolean)
//instance.{0} = ({1})reader.ReadBoolean();
.ldloc_0 //Push 'instance'
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadBoolean"))
.GeneratePrimitiveCast(primitiveTypeCode)
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelNotBoolean)
.GenerateThrowUnexpectedAMFException(memberInfo)
.MarkLabel(labelExit)
.end()
;
#endregion Primitive boolean
}
break;
case TypeCode.Char:
{
#region Primitive Char
{
Label labelNotString = emit.ILGenerator.DefineLabel();
Label labelExit = emit.ILGenerator.DefineLabel();
//if( typeCode == AMF0TypeCode.String )
emit
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.String)
.ceq
.brfalse_s(labelNotString)
//instance.member = reader.ReadString()[0];
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadString"))
.stloc_2
.ldloc_2 //Push 'key'
.brfalse_s(labelNotString) // Branch if 'key' is null
.ldloc_2 //Push strTmp
.ldsfld(typeof(string).GetField("Empty"))
.call(typeof(string).GetMethod("op_Inequality", new Type[] { typeof(string), typeof(string) }))
.brfalse_s(labelNotString)
.ldloc_0 //Push 'instance'
.ldloc_2 //Push 'key'
.ldc_i4_0 //Push char index 0
.callvirt(typeof(string).GetMethod("get_Chars", new Type[] { typeof(Int32) }))
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelNotString)
.GenerateThrowUnexpectedAMFException(memberInfo)
.MarkLabel(labelExit)
.end()
;
}
#endregion Primitive Char
}
break;
}
return;
}
if (memberType.IsEnum)
{
#region Enum
Label labelNotStringOrNumber = emit.ILGenerator.DefineLabel();
Label labelExit = emit.ILGenerator.DefineLabel();
Label labelReadDouble = emit.ILGenerator.DefineLabel();
//if( typeCode == AMF0TypeCode.String || typeCode == AMF0TypeCode.Number )
emit
.ldloc_1 //Push 'typeCode'
.brfalse_s(labelReadDouble) //Branch if 0 (AMF0TypeCode.Number)
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.String)
.ceq
.brfalse_s(labelNotStringOrNumber)
//we have a string
.ldloc_0 //Push 'instance'
.ldtoken(memberType)
.call(typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }))
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadString"))
.ldc_i4_1
.call(typeof(Enum).GetMethod("Parse", new Type[] { typeof(Type), typeof(string), typeof(bool) }))
.unbox_any(memberType)
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelReadDouble)
//we have a number
.ldloc_0 //Push 'instance'
.ldtoken(memberType)
.call(typeof(Type).GetMethod("GetTypeFromHandle"))
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadDouble"))
.conv_i4
.call(typeof(Enum).GetMethod("ToObject", new Type[] { typeof(Type), typeof(Int32) }))
.unbox_any(memberType)
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelNotStringOrNumber)
.GenerateThrowUnexpectedAMFException(memberInfo)
.MarkLabel(labelExit)
.end()
;
return;
#endregion Enum
}
if (memberType == typeof(DateTime))
{
#region DateTime
Label labelNotDate = emit.ILGenerator.DefineLabel();
Label labelExit = emit.ILGenerator.DefineLabel();
//if( typeCode == AMF0TypeCode.DateTime )
emit
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.DateTime)
.ceq
.brfalse_s(labelNotDate)
.ldloc_0 //Push 'instance'
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadDateTime"))
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelNotDate)
.GenerateThrowUnexpectedAMFException(memberInfo)
.MarkLabel(labelExit)
.end()
;
return;
#endregion DateTime
}
if (memberType == typeof(string))
{
#region String
Label labelNotStringOrNull = emit.ILGenerator.DefineLabel();
Label labelSetNull = emit.ILGenerator.DefineLabel();
Label labelExit = emit.ILGenerator.DefineLabel();
Label labelReadString = emit.ILGenerator.DefineLabel();
Label labelReadLongString = emit.ILGenerator.DefineLabel();
emit
//if( typeCode == AMF0TypeCode.String || typeCode == AMF0TypeCode.LongString || typeCode == AMF0TypeCode.Null || typeCode == AMF0TypeCode.Undefined )
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.String)
.ceq
.brtrue_s(labelReadString)
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.LongString)
.ceq
.brtrue_s(labelReadLongString)
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.Null)
.ceq
.brtrue_s(labelSetNull)
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.Undefined)
.ceq
.brtrue_s(labelSetNull)
.br_s(labelNotStringOrNull)
.MarkLabel(labelReadString)
.ldloc_0 //Push 'instance'
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadString"))
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelReadLongString)
.ldloc_0 //Push 'instance'
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadLongString"))
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelSetNull)
.ldloc_0 //Push 'instance'
.ldc_i4_0
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelNotStringOrNull)
.GenerateThrowUnexpectedAMFException(memberInfo)
.MarkLabel(labelExit)
.end()
;
return;
#endregion String
}
if (memberType == typeof(Guid))
{
#region Guid
Label labelNotString = emit.ILGenerator.DefineLabel();
Label labelExit = emit.ILGenerator.DefineLabel();
emit
//if( typeCode == AMF0TypeCode.String )
.ldloc_1 //Push 'typeCode'
.ldc_i4(AMF0TypeCode.String)
.ceq
.brfalse_s(labelNotString)
.ldloc_0 //Push 'instance'
.ldarg_0 //Push 'reader'
.callvirt(typeof(AMFReader).GetMethod("ReadString"))
.newobj(typeof(Guid).GetConstructor(EmitHelper.AnyVisibilityInstance, null, CallingConventions.HasThis, new Type[] { typeof(string) }, null))
.GenerateSetMember(memberInfo)
.br_s(labelExit)
.MarkLabel(labelNotString)
.GenerateThrowUnexpectedAMFException(memberInfo)
.MarkLabel(labelExit)
.end()
;
return;
#endregion Guid
}
if (memberType.IsValueType)
{
//structs are not handled
throw new FluorineException("Struct value types are not supported");
}
//instance.member = (type)TypeHelper.ChangeType(reader.ReadData(typeCode), typeof(member));
emit
.ldloc_0 //Push 'instance'
.ldarg_0 //Push 'reader'
.ldloc_1 //Push 'typeCode'
.callvirt(typeof(AMFReader).GetMethod("ReadData", new Type[] { typeof(byte) }))
.ldtoken(memberType)
.call(typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }))
.call(typeof(TypeHelper).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type) }))
.CastFromObject(memberType)
.GenerateSetMember(memberInfo)
.end()
;
}
#region IReflectionOptimizer Members
public object CreateInstance()
{
return _createInstanceMethod();
}
public virtual object ReadData(AMFReader reader, ClassDefinition classDefinition)
{
return _readDataMethod(reader, classDefinition);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Hypergrid
{
public class InstantMessageServerConnector : ServiceConnector
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private IInstantMessage m_IMService;
public InstantMessageServerConnector(IConfigSource config, IHttpServer server) :
this(config, server, (IInstantMessageSimConnector)null)
{
}
public InstantMessageServerConnector(IConfigSource config, IHttpServer server, string configName) :
this(config, server)
{
}
public InstantMessageServerConnector(IConfigSource config, IHttpServer server, IInstantMessageSimConnector simConnector) :
base(config, server, String.Empty)
{
IConfig gridConfig = config.Configs["HGInstantMessageService"];
if (gridConfig != null)
{
string serviceDll = gridConfig.GetString("LocalServiceModule", string.Empty);
Object[] args = new Object[] { config, simConnector };
m_IMService = ServerUtils.LoadPlugin<IInstantMessage>(serviceDll, args);
}
if (m_IMService == null)
throw new Exception("InstantMessage server connector cannot proceed because of missing service");
server.AddXmlRPCHandler("grid_instant_message", ProcessInstantMessage, false);
}
public IInstantMessage GetService()
{
return m_IMService;
}
protected virtual XmlRpcResponse ProcessInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool successful = false;
try
{
// various rational defaults
UUID fromAgentID = UUID.Zero;
UUID toAgentID = UUID.Zero;
UUID imSessionID = UUID.Zero;
uint timestamp = 0;
string fromAgentName = "";
string message = "";
byte dialog = (byte)0;
bool fromGroup = false;
byte offline = (byte)0;
uint ParentEstateID = 0;
Vector3 Position = Vector3.Zero;
UUID RegionID = UUID.Zero;
byte[] binaryBucket = new byte[0];
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
//m_log.Info("Processing IM");
Hashtable requestData = (Hashtable)request.Params[0];
// Check if it's got all the data
if (requestData.ContainsKey("from_agent_id")
&& requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
&& requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
&& requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
&& requestData.ContainsKey("from_group")
&& requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
&& requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
&& requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
&& requestData.ContainsKey("binary_bucket"))
{
// Do the easy way of validating the UUIDs
UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
UUID.TryParse((string)requestData["region_id"], out RegionID);
try
{
timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"];
if (message == null)
message = string.Empty;
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"];
if (string.IsNullOrEmpty(requestData1))
{
dialog = 0;
}
else
{
byte[] dialogdata = Convert.FromBase64String(requestData1);
dialog = dialogdata[0];
}
if ((string)requestData["from_group"] == "TRUE")
fromGroup = true;
string requestData2 = (string)requestData["offline"];
if (String.IsNullOrEmpty(requestData2))
{
offline = 0;
}
else
{
byte[] offlinedata = Convert.FromBase64String(requestData2);
offline = offlinedata[0];
}
try
{
ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
float.TryParse((string)requestData["position_x"], out pos_x);
float.TryParse((string)requestData["position_y"], out pos_y);
float.TryParse((string)requestData["position_z"], out pos_z);
Position = new Vector3(pos_x, pos_y, pos_z);
string requestData3 = (string)requestData["binary_bucket"];
if (string.IsNullOrEmpty(requestData3))
{
binaryBucket = new byte[0];
}
else
{
binaryBucket = Convert.FromBase64String(requestData3);
}
// Create a New GridInstantMessageObject the the data
GridInstantMessage gim = new GridInstantMessage();
gim.fromAgentID = fromAgentID.Guid;
gim.fromAgentName = fromAgentName;
gim.fromGroup = fromGroup;
gim.imSessionID = imSessionID.Guid;
gim.RegionID = RegionID.Guid;
gim.timestamp = timestamp;
gim.toAgentID = toAgentID.Guid;
gim.message = message;
gim.dialog = dialog;
gim.offline = offline;
gim.ParentEstateID = ParentEstateID;
gim.Position = Position;
gim.binaryBucket = binaryBucket;
successful = m_IMService.IncomingInstantMessage(gim);
}
}
catch (Exception e)
{
m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
successful = false;
}
//Send response back to region calling if it was successful
// calling region uses this to know when to look up a user's location again.
XmlRpcResponse resp = new XmlRpcResponse();
Hashtable respdata = new Hashtable();
if (successful)
respdata["success"] = "TRUE";
else
respdata["success"] = "FALSE";
resp.Value = respdata;
return resp;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using SpyUO.Packets;
namespace SpyUO
{
public class Display : Form, ICounterDisplay
{
public const string Title = "SpyUO 1.10";
[STAThread]
public static void Main()
{
CheckForIllegalCrossThreadCalls = false;
try
{
SetupClientsConfig( "Clients.cfg" );
SetupItemsTable( "Items.cfg" );
Application.Run( new Display() );
}
catch ( Exception e )
{
MessageBox.Show( e.ToString(), "Application error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
private static void SetupClientsConfig( string file )
{
try
{
PacketPump.ClientsConfig.AddToTable( file );
}
catch ( Exception e )
{
throw new Exception( "Error reading " + file, e );
}
}
private static void SetupItemsTable( string file )
{
try
{
PacketRecorder.InitItemsTable( file );
}
catch ( Exception e )
{
throw new Exception( "Error reading " + file, e );
}
}
private System.Windows.Forms.ListView lvPackets;
private System.Windows.Forms.ColumnHeader chType;
private System.Windows.Forms.ColumnHeader chMessage;
private System.Windows.Forms.ColumnHeader chPacket;
private System.Windows.Forms.ColumnHeader chTime;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem miProcess;
private System.Windows.Forms.MenuItem miStart;
private System.Windows.Forms.MenuItem miAttach;
private System.Windows.Forms.MenuItem miDetach;
private System.Windows.Forms.MenuItem miExitSeparator;
private System.Windows.Forms.MenuItem miExit;
private System.Windows.Forms.OpenFileDialog ofdStart;
private System.Windows.Forms.MenuItem miOptions;
private System.Windows.Forms.MenuItem miFilter;
private System.Windows.Forms.MenuItem miOnTop;
private System.Windows.Forms.MenuItem miAutoScrolling;
private System.Windows.Forms.ColumnHeader chRelTime;
private System.Windows.Forms.MenuItem miLogs;
private System.Windows.Forms.MenuItem miClear;
private System.Windows.Forms.MenuItem miPause;
private System.Windows.Forms.MenuItem miSaveAs;
private System.Windows.Forms.SaveFileDialog sfdSaveAs;
private System.Windows.Forms.MenuItem miHelp;
private System.Windows.Forms.MenuItem miAbout;
private System.Windows.Forms.ColumnHeader chDifTime;
private System.Windows.Forms.ColumnHeader chASCII;
private System.Windows.Forms.MenuItem miTools;
private System.Windows.Forms.SaveFileDialog sfdExtractItems;
private System.Windows.Forms.MenuItem miExtractItems;
private System.Windows.Forms.MenuItem miExtractGump;
private System.Windows.Forms.SaveFileDialog sfdExtractGump;
private System.Windows.Forms.MenuItem miSaveHexAs;
private System.Windows.Forms.ColumnHeader chLength;
private System.Windows.Forms.MenuItem miLoad;
private System.Windows.Forms.OpenFileDialog ofdLoad;
private System.Windows.Forms.MenuItem miExtractGumpSphere;
private System.Windows.Forms.SaveFileDialog sfdExtractGumpSphere;
private System.Windows.Forms.MenuItem miSetBaseTime;
private System.Windows.Forms.MenuItem miHide;
private System.Windows.Forms.MenuItem miShowHidden;
private System.Windows.Forms.MenuItem miExtractBooks;
private System.Windows.Forms.SaveFileDialog sfdExtractBook;
private System.Windows.Forms.MenuItem miSaveBin;
private System.Windows.Forms.SaveFileDialog sfdSaveBin;
private System.Windows.Forms.MenuItem miLoadBin;
private System.Windows.Forms.OpenFileDialog ofdLoadBin;
private MenuItem miExtractItem;
private ContextMenuStrip mainContextMenu;
private MenuItem miLootAnalyzer;
private MenuItem miLootAnalyze;
private MenuItem miLootSave;
private MenuItem miVendorAnalyzer;
private MenuItem miVendorAnalyze;
private SaveFileDialog sfdSaveVendor;
private IContainer components;
protected override void Dispose( bool disposing )
{
if ( disposing )
{
if ( components != null )
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Metodo necessario per il supporto della finestra di progettazione. Non modificare
/// il contenuto del metodo con l'editor di codice.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( Display ) );
this.lvPackets = new System.Windows.Forms.ListView();
this.chType = new System.Windows.Forms.ColumnHeader();
this.chMessage = new System.Windows.Forms.ColumnHeader();
this.chTime = new System.Windows.Forms.ColumnHeader();
this.chRelTime = new System.Windows.Forms.ColumnHeader();
this.chDifTime = new System.Windows.Forms.ColumnHeader();
this.chPacket = new System.Windows.Forms.ColumnHeader();
this.chASCII = new System.Windows.Forms.ColumnHeader();
this.chLength = new System.Windows.Forms.ColumnHeader();
this.mainContextMenu = new System.Windows.Forms.ContextMenuStrip( this.components );
this.mainMenu = new System.Windows.Forms.MainMenu( this.components );
this.miProcess = new System.Windows.Forms.MenuItem();
this.miStart = new System.Windows.Forms.MenuItem();
this.miAttach = new System.Windows.Forms.MenuItem();
this.miDetach = new System.Windows.Forms.MenuItem();
this.miExitSeparator = new System.Windows.Forms.MenuItem();
this.miExit = new System.Windows.Forms.MenuItem();
this.miLogs = new System.Windows.Forms.MenuItem();
this.miLoad = new System.Windows.Forms.MenuItem();
this.miSaveAs = new System.Windows.Forms.MenuItem();
this.miSaveHexAs = new System.Windows.Forms.MenuItem();
this.miLoadBin = new System.Windows.Forms.MenuItem();
this.miSaveBin = new System.Windows.Forms.MenuItem();
this.miPause = new System.Windows.Forms.MenuItem();
this.miClear = new System.Windows.Forms.MenuItem();
this.miSetBaseTime = new System.Windows.Forms.MenuItem();
this.miHide = new System.Windows.Forms.MenuItem();
this.miShowHidden = new System.Windows.Forms.MenuItem();
this.miOptions = new System.Windows.Forms.MenuItem();
this.miFilter = new System.Windows.Forms.MenuItem();
this.miOnTop = new System.Windows.Forms.MenuItem();
this.miAutoScrolling = new System.Windows.Forms.MenuItem();
this.miTools = new System.Windows.Forms.MenuItem();
this.miExtractItems = new System.Windows.Forms.MenuItem();
this.miExtractBooks = new System.Windows.Forms.MenuItem();
this.miExtractItem = new System.Windows.Forms.MenuItem();
this.miExtractGump = new System.Windows.Forms.MenuItem();
this.miExtractGumpSphere = new System.Windows.Forms.MenuItem();
this.miLootAnalyzer = new System.Windows.Forms.MenuItem();
this.miLootAnalyze = new System.Windows.Forms.MenuItem();
this.miLootSave = new System.Windows.Forms.MenuItem();
this.miVendorAnalyzer = new System.Windows.Forms.MenuItem();
this.miVendorAnalyze = new System.Windows.Forms.MenuItem();
this.miHelp = new System.Windows.Forms.MenuItem();
this.miAbout = new System.Windows.Forms.MenuItem();
this.ofdStart = new System.Windows.Forms.OpenFileDialog();
this.sfdSaveAs = new System.Windows.Forms.SaveFileDialog();
this.sfdExtractItems = new System.Windows.Forms.SaveFileDialog();
this.sfdExtractGump = new System.Windows.Forms.SaveFileDialog();
this.ofdLoad = new System.Windows.Forms.OpenFileDialog();
this.sfdExtractGumpSphere = new System.Windows.Forms.SaveFileDialog();
this.sfdExtractBook = new System.Windows.Forms.SaveFileDialog();
this.sfdSaveBin = new System.Windows.Forms.SaveFileDialog();
this.ofdLoadBin = new System.Windows.Forms.OpenFileDialog();
this.sfdSaveVendor = new System.Windows.Forms.SaveFileDialog();
this.SuspendLayout();
//
// lvPackets
//
this.lvPackets.Columns.AddRange( new System.Windows.Forms.ColumnHeader[] {
this.chType,
this.chMessage,
this.chTime,
this.chRelTime,
this.chDifTime,
this.chPacket,
this.chASCII,
this.chLength} );
this.lvPackets.ContextMenuStrip = this.mainContextMenu;
this.lvPackets.Dock = System.Windows.Forms.DockStyle.Fill;
this.lvPackets.Font = new System.Drawing.Font( "Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ( (byte) ( 0 ) ) );
this.lvPackets.FullRowSelect = true;
this.lvPackets.GridLines = true;
this.lvPackets.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lvPackets.Location = new System.Drawing.Point( 0, 0 );
this.lvPackets.MultiSelect = false;
this.lvPackets.Name = "lvPackets";
this.lvPackets.Size = new System.Drawing.Size( 829, 592 );
this.lvPackets.TabIndex = 0;
this.lvPackets.UseCompatibleStateImageBehavior = false;
this.lvPackets.View = System.Windows.Forms.View.Details;
this.lvPackets.ItemActivate += new System.EventHandler( this.lvPackets_ItemActivate );
this.lvPackets.SelectedIndexChanged += new System.EventHandler( this.lvPackets_SelectedIndexChanged );
//
// chType
//
this.chType.Text = "Type";
this.chType.Width = 130;
//
// chMessage
//
this.chMessage.Text = "Message";
this.chMessage.Width = 533;
//
// chTime
//
this.chTime.Text = "Time";
this.chTime.Width = 75;
//
// chRelTime
//
this.chRelTime.Text = "Rel time";
//
// chDifTime
//
this.chDifTime.Text = "Dif time";
//
// chPacket
//
this.chPacket.Text = "Packet";
this.chPacket.Width = 250;
//
// chASCII
//
this.chASCII.Text = "ASCII";
this.chASCII.Width = 250;
//
// chLength
//
this.chLength.Text = "Length";
this.chLength.Width = 50;
//
// mainContextMenu
//
this.mainContextMenu.Name = "mainContextMenu";
this.mainContextMenu.Size = new System.Drawing.Size( 61, 4 );
this.mainContextMenu.Opening += new System.ComponentModel.CancelEventHandler( this.mainContextMenu_Opening );
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] {
this.miProcess,
this.miLogs,
this.miOptions,
this.miTools,
this.miHelp} );
//
// miProcess
//
this.miProcess.Index = 0;
this.miProcess.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] {
this.miStart,
this.miAttach,
this.miDetach,
this.miExitSeparator,
this.miExit} );
this.miProcess.Text = "&Process";
//
// miStart
//
this.miStart.Index = 0;
this.miStart.Text = "&Start...";
this.miStart.Click += new System.EventHandler( this.miStart_Click );
//
// miAttach
//
this.miAttach.Index = 1;
this.miAttach.Text = "&Attach...";
this.miAttach.Click += new System.EventHandler( this.miAttach_Click );
//
// miDetach
//
this.miDetach.Enabled = false;
this.miDetach.Index = 2;
this.miDetach.Text = "&Detach";
this.miDetach.Click += new System.EventHandler( this.miDetach_Click );
//
// miExitSeparator
//
this.miExitSeparator.Index = 3;
this.miExitSeparator.Text = "-";
//
// miExit
//
this.miExit.Index = 4;
this.miExit.Text = "&Exit";
this.miExit.Click += new System.EventHandler( this.miExit_Click );
//
// miLogs
//
this.miLogs.Index = 1;
this.miLogs.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] {
this.miLoad,
this.miSaveAs,
this.miSaveHexAs,
this.miLoadBin,
this.miSaveBin,
this.miPause,
this.miClear,
this.miSetBaseTime,
this.miHide,
this.miShowHidden} );
this.miLogs.Text = "&Logs";
//
// miLoad
//
this.miLoad.Index = 0;
this.miLoad.Text = "&Load...";
this.miLoad.Click += new System.EventHandler( this.miLoad_Click );
//
// miSaveAs
//
this.miSaveAs.Index = 1;
this.miSaveAs.Text = "&Save as...";
this.miSaveAs.Click += new System.EventHandler( this.miSaveAs_Click );
//
// miSaveHexAs
//
this.miSaveHexAs.Index = 2;
this.miSaveHexAs.Text = "Save &hex as...";
this.miSaveHexAs.Click += new System.EventHandler( this.miSaveHexAs_Click );
//
// miLoadBin
//
this.miLoadBin.Index = 3;
this.miLoadBin.Text = "Load b&in...";
this.miLoadBin.Click += new System.EventHandler( this.miLoadBin_Click );
//
// miSaveBin
//
this.miSaveBin.Index = 4;
this.miSaveBin.Text = "Save bi&n as...";
this.miSaveBin.Click += new System.EventHandler( this.miSaveBin_Click );
//
// miPause
//
this.miPause.Enabled = false;
this.miPause.Index = 5;
this.miPause.Text = "&Pause";
this.miPause.Click += new System.EventHandler( this.miPause_Click );
//
// miClear
//
this.miClear.Index = 6;
this.miClear.Text = "&Clear";
this.miClear.Click += new System.EventHandler( this.miClear_Click );
//
// miSetBaseTime
//
this.miSetBaseTime.Enabled = false;
this.miSetBaseTime.Index = 7;
this.miSetBaseTime.Text = "Set &base time";
this.miSetBaseTime.Click += new System.EventHandler( this.miSetBaseTime_Click );
//
// miHide
//
this.miHide.Enabled = false;
this.miHide.Index = 8;
this.miHide.Shortcut = System.Windows.Forms.Shortcut.Del;
this.miHide.Text = "&Hide";
this.miHide.Click += new System.EventHandler( this.miHide_Click );
//
// miShowHidden
//
this.miShowHidden.Enabled = false;
this.miShowHidden.Index = 9;
this.miShowHidden.Text = "Show hi&dden";
this.miShowHidden.Click += new System.EventHandler( this.miShowHidden_Click );
//
// miOptions
//
this.miOptions.Index = 2;
this.miOptions.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] {
this.miFilter,
this.miOnTop,
this.miAutoScrolling} );
this.miOptions.Text = "&Options";
//
// miFilter
//
this.miFilter.Index = 0;
this.miFilter.Text = "&Filter...";
this.miFilter.Click += new System.EventHandler( this.miFilter_Click );
//
// miOnTop
//
this.miOnTop.Index = 1;
this.miOnTop.Text = "Always on &top";
this.miOnTop.Click += new System.EventHandler( this.miOnTop_Click );
//
// miAutoScrolling
//
this.miAutoScrolling.Index = 2;
this.miAutoScrolling.Text = "Auto &scrolling";
this.miAutoScrolling.Click += new System.EventHandler( this.miAutoScrolling_Click );
//
// miTools
//
this.miTools.Index = 3;
this.miTools.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] {
this.miExtractItems,
this.miExtractBooks,
this.miExtractItem,
this.miExtractGump,
this.miExtractGumpSphere,
this.miLootAnalyzer,
this.miVendorAnalyzer} );
this.miTools.Text = "&Tools";
//
// miExtractItems
//
this.miExtractItems.Index = 0;
this.miExtractItems.Text = "Extract &items...";
this.miExtractItems.Click += new System.EventHandler( this.miExtractItems_Click );
//
// miExtractBooks
//
this.miExtractBooks.Index = 1;
this.miExtractBooks.Text = "Extract &book...";
this.miExtractBooks.Click += new System.EventHandler( this.miExtractBooks_Click );
//
// miExtractItem
//
this.miExtractItem.Enabled = false;
this.miExtractItem.Index = 2;
this.miExtractItem.Text = "Extract item (RunUO)";
this.miExtractItem.Click += new System.EventHandler( this.miExtractItem_Click );
//
// miExtractGump
//
this.miExtractGump.Enabled = false;
this.miExtractGump.Index = 3;
this.miExtractGump.Text = "Extract &gump (RunUO)...";
this.miExtractGump.Click += new System.EventHandler( this.miExtractGump_Click );
//
// miExtractGumpSphere
//
this.miExtractGumpSphere.Enabled = false;
this.miExtractGumpSphere.Index = 4;
this.miExtractGumpSphere.Text = "Extract gump (&Sphere)...";
this.miExtractGumpSphere.Click += new System.EventHandler( this.miExtractGumpSphere_Click );
//
// miLootAnalyzer
//
this.miLootAnalyzer.Index = 5;
this.miLootAnalyzer.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] {
this.miLootAnalyze,
this.miLootSave} );
this.miLootAnalyzer.Text = "Loot Analyzer";
//
// miLootAnalyze
//
this.miLootAnalyze.Index = 0;
this.miLootAnalyze.Shortcut = System.Windows.Forms.Shortcut.CtrlA;
this.miLootAnalyze.Text = "Analyze";
this.miLootAnalyze.Click += new System.EventHandler( this.miLootAnalyze_Click );
//
// miLootSave
//
this.miLootSave.Index = 1;
this.miLootSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
this.miLootSave.Text = "Save";
this.miLootSave.Click += new System.EventHandler( this.miLootSave_Click );
//
// miVendorAnalyzer
//
this.miVendorAnalyzer.Index = 6;
this.miVendorAnalyzer.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] {
this.miVendorAnalyze} );
this.miVendorAnalyzer.Text = "Vendor Analyzer";
//
// miVendorAnalyze
//
this.miVendorAnalyze.Index = 0;
this.miVendorAnalyze.Text = "Analyze";
this.miVendorAnalyze.Click += new System.EventHandler( this.miVendorAnalyze_Click );
//
// miHelp
//
this.miHelp.Index = 4;
this.miHelp.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] {
this.miAbout} );
this.miHelp.Text = "&Help";
//
// miAbout
//
this.miAbout.Index = 0;
this.miAbout.Text = "&About...";
this.miAbout.Click += new System.EventHandler( this.miAbout_Click );
//
// ofdStart
//
this.ofdStart.Filter = "Exe files (*.exe)|*.exe";
//
// sfdSaveAs
//
this.sfdSaveAs.FileName = "SpyUO.log";
this.sfdSaveAs.Filter = "Log files (*.log)|*.log";
//
// sfdExtractItems
//
this.sfdExtractItems.FileName = "SpyUO.cfg";
this.sfdExtractItems.Filter = "Cfg files (*.cfg)|*.cfg";
this.sfdExtractItems.Title = "Extract to";
//
// sfdExtractGump
//
this.sfdExtractGump.FileName = "SpyUOGump.cs";
this.sfdExtractGump.Filter = "C# files (*.cs)|*.cs";
this.sfdExtractGump.Title = "Extract to";
//
// ofdLoad
//
this.ofdLoad.FileName = "SpyUO.log";
this.ofdLoad.Filter = "All files (*.*)|*.*";
//
// sfdExtractGumpSphere
//
this.sfdExtractGumpSphere.FileName = "SpyUOGump.scp";
this.sfdExtractGumpSphere.Filter = "Scp files (*.scp)|*.scp";
//
// sfdExtractBook
//
this.sfdExtractBook.FileName = "SpyUOBook.cs";
this.sfdExtractBook.Filter = "C# files (*.cs)|*.cs";
this.sfdExtractBook.Title = "Extract to";
//
// sfdSaveBin
//
this.sfdSaveBin.FileName = "SpyUO.bin";
this.sfdSaveBin.Filter = "Bin files (*.bin)|*.bin";
//
// ofdLoadBin
//
this.ofdLoadBin.FileName = "SpyUO.bin";
this.ofdLoadBin.Filter = "Bin files (*.bin)|*.bin";
this.ofdLoadBin.Multiselect = true;
//
// sfdSaveVendor
//
this.sfdSaveVendor.Filter = "Text files (*.txt)|*.txt";
this.sfdSaveVendor.Title = "Save Vendor Info";
//
// Display
//
this.AutoScaleBaseSize = new System.Drawing.Size( 5, 13 );
this.ClientSize = new System.Drawing.Size( 829, 592 );
this.Controls.Add( this.lvPackets );
this.Icon = ( (System.Drawing.Icon) ( resources.GetObject( "$this.Icon" ) ) );
this.Menu = this.mainMenu;
this.MinimumSize = new System.Drawing.Size( 320, 240 );
this.Name = "Display";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler( this.Display_FormClosing );
this.ResumeLayout( false );
}
#endregion
private PacketFilter m_PacketFilter;
private PacketRecorder m_PacketRecorder;
private PacketPump m_PacketPump;
private bool m_FilterShowAll;
private bool m_AutoScrolling;
private DateTime m_BaseTime;
private DateTime m_LastTime;
private LootFilterForm m_LootFilterForm;
private PacketPump PacketPump
{
get
{
return m_PacketPump;
}
set
{
if ( m_PacketPump != null )
{
m_PacketPump.Dispose();
Detached();
}
m_PacketPump = value;
if ( m_PacketPump != null )
{
Attached();
m_PacketPump.OnPacketPumpTerminated += new PacketPumpTerminatedHandler( PacketPumpTerminated );
}
}
}
public Display()
{
InitializeComponent();
UpdateTitle( "" );
m_LastTime = DateTime.MinValue;
m_BaseTime = DateTime.Now;
m_FilterShowAll = false;
m_PacketFilter = new PacketFilter();
m_PacketRecorder = new PacketRecorder( this );
m_PacketRecorder.OnPacket += new OnPacket( OnPacket );
Application.ApplicationExit += new EventHandler( OnExit );
}
public void UpdateTitle( string affix )
{
Text = Title + (m_PacketPump != null ? " " + affix : "");
}
private void OnPacket( TimePacket packet )
{
if ( m_PacketFilter.Filter( packet ) )
AddPacket( packet );
}
private void AddPacket( TimePacket packet )
{
PacketListViewItem item = new PacketListViewItem( packet, m_BaseTime, m_LastTime );
lvPackets.Items.Add( item );
if ( m_AutoScrolling )
lvPackets.EnsureVisible( lvPackets.Items.Count - 1 );
m_LastTime = packet.Time;
}
private void UpdatePackets()
{
miSetBaseTime.Enabled = false;
miHide.Enabled = false;
miShowHidden.Enabled = false;
miExtractGump.Enabled = false;
miExtractGumpSphere.Enabled = false;
m_LastTime = DateTime.MinValue;
lvPackets.BeginUpdate();
lvPackets.Items.Clear();
foreach ( TimePacket packet in m_PacketRecorder.Packets )
{
if ( m_PacketFilter.Filter( packet ) )
AddPacket( packet );
}
lvPackets.EndUpdate();
}
private void Attached()
{
miStart.Enabled = false;
miAttach.Enabled = false;
miDetach.Enabled = true;
miPause.Enabled = true;
miPause.Checked = false;
}
private void Detached()
{
miStart.Enabled = true;
miAttach.Enabled = true;
miDetach.Enabled = false;
miPause.Enabled = false;
miPause.Checked = false;
}
private void PacketPumpTerminated()
{
PacketPump = null;
}
private void OnExit( object sender, System.EventArgs e )
{
if ( PacketPump != null )
PacketPump = null;
if ( m_PacketRecorder != null )
m_PacketRecorder.Dispose();
}
private void miStart_Click( object sender, System.EventArgs e )
{
DialogResult result = ofdStart.ShowDialog(this);
if (result == DialogResult.OK )
{
try
{
PacketPump pump = new PacketPump( this, new PacketPumpPacketHandler( m_PacketRecorder.PacketPumpDequeue ) );
pump.Start( ofdStart.FileName );
PacketPump = pump;
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Packet pump error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
}
private void miAttach_Click( object sender, System.EventArgs e )
{
SelectProcess selProc = new SelectProcess();
selProc.TopMost = TopMost;
if ( selProc.ShowDialog() == DialogResult.OK )
{
Process process = selProc.GetSelectedProcess();
if ( process != null )
{
try
{
PacketPump pump = new PacketPump( this, new PacketPumpPacketHandler( m_PacketRecorder.PacketPumpDequeue ) );
pump.Start( process );
PacketPump = pump;
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Packet pump error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
}
}
private void miDetach_Click( object sender, System.EventArgs e )
{
PacketPump = null;
}
private void miExit_Click( object sender, System.EventArgs e )
{
Application.Exit();
}
private void miFilter_Click( object sender, System.EventArgs e )
{
Filter filter = new Filter( m_PacketFilter, m_FilterShowAll );
filter.TopMost = TopMost;
if ( filter.ShowDialog() == DialogResult.OK )
{
m_FilterShowAll = filter.ShowAll;
UpdatePackets();
}
}
private void miOnTop_Click( object sender, System.EventArgs e )
{
TopMost = !miOnTop.Checked;
miOnTop.Checked = TopMost;
}
private void miAutoScrolling_Click( object sender, System.EventArgs e )
{
m_AutoScrolling = !m_AutoScrolling;
miAutoScrolling.Checked = m_AutoScrolling;
}
private void miSetBaseTime_Click( object sender, System.EventArgs e )
{
ListView.SelectedListViewItemCollection sel = lvPackets.SelectedItems;
if ( sel.Count > 0 )
{
PacketListViewItem item = (PacketListViewItem)sel[0];
m_BaseTime = item.TimePacket.Time;
foreach ( PacketListViewItem plvi in lvPackets.Items )
plvi.UpdateRelTime( m_BaseTime );
}
}
private void miHide_Click( object sender, System.EventArgs e )
{
if ( lvPackets.SelectedIndices.Count > 0 )
{
int index = lvPackets.SelectedIndices[0];
lvPackets.Items.RemoveAt( index );
if ( index < lvPackets.Items.Count )
{
PacketListViewItem item = (PacketListViewItem)lvPackets.Items[index];
if ( index == 0 )
item.UpdateDifTime( DateTime.MinValue );
else
item.UpdateDifTime( ((PacketListViewItem)lvPackets.Items[index - 1]).TimePacket.Time );
}
miShowHidden.Enabled = true;
}
}
private void miShowHidden_Click( object sender, System.EventArgs e )
{
UpdatePackets();
}
private void lvPackets_ItemActivate( object sender, System.EventArgs e )
{
ListView.SelectedListViewItemCollection sel = lvPackets.SelectedItems;
if ( sel.Count > 0 )
{
PacketListViewItem item = (PacketListViewItem)sel[0];
PacketDetails pDetails = new PacketDetails( item );
pDetails.Show();
}
}
private void miClear_Click( object sender, System.EventArgs e )
{
m_PacketRecorder.Clear();
UpdatePackets();
}
private void miPause_Click( object sender, System.EventArgs e )
{
if ( PacketPump != null )
PacketPump.TogglePause();
miPause.Checked = !miPause.Checked;
}
private void miLoad_Click( object sender, System.EventArgs e )
{
if ( ofdLoad.ShowDialog() == DialogResult.OK )
{
StreamReader reader = null;
try
{
reader = File.OpenText( ofdLoad.FileName );
m_PacketRecorder.Load( reader );
UpdatePackets();
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Load error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( reader != null )
reader.Close();
}
}
}
private void miSaveAs_Click( object sender, System.EventArgs e )
{
if ( sfdSaveAs.ShowDialog() == DialogResult.OK )
{
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdSaveAs.FileName );
Save( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
public void Save( StreamWriter writer )
{
writer.WriteLine( "Logs created on {0} by SpyUO", DateTime.Now );
writer.WriteLine();
writer.WriteLine();
foreach ( ListViewItem item in lvPackets.Items )
{
for ( int i = 0; i < lvPackets.Columns.Count; i++ )
writer.WriteLine( "{0} - {1}", lvPackets.Columns[i].Text, item.SubItems[i].Text );
writer.WriteLine();
}
}
private void miSaveHexAs_Click( object sender, System.EventArgs e )
{
if ( sfdSaveAs.ShowDialog() == DialogResult.OK )
{
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdSaveAs.FileName );
SaveHex( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
public void SaveHex( StreamWriter writer )
{
writer.WriteLine( "Logs created on {0} by SpyUO", DateTime.Now );
writer.WriteLine();
writer.WriteLine();
foreach ( PacketListViewItem item in lvPackets.Items )
{
TimePacket tPacket = item.TimePacket;
Packet packet = tPacket.Packet;
byte[] data = packet.Data;
writer.WriteLine( " {0} - {1} (command: 0x{2:X}, length: 0x{3:X})",
packet.Send ? "Send" : "Recv", tPacket.Time.ToString( @"H\:mm\:ss.ff" ), packet.PacketID, data.Length );
for ( int l = 0; l < data.Length; l += 0x10 )
{
writer.Write( "{0:X4}:", l );
for ( int i = l; i < l + 0x10; i++ )
writer.Write( " {0}", i < data.Length ? data[i].ToString( "X2" ) : "--" );
writer.Write( "\t" );
for ( int i = l; i < l + 0x10; i++ )
{
if ( i >= data.Length )
break;
byte b = data[i];
char c;
if ( b >= 0x20 && b < 0x80 )
c = (char)b;
else
c = '.';
writer.Write( c );
}
writer.WriteLine();
}
writer.WriteLine();
}
}
private void miSaveBin_Click( object sender, System.EventArgs e )
{
if ( sfdSaveBin.ShowDialog() == DialogResult.OK )
{
FileStream stream = null;
BinaryWriter writer = null;
try
{
stream = File.Create( sfdSaveBin.FileName );
writer = new BinaryWriter( stream );
SaveBin( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
if ( stream != null )
stream.Close();
}
}
}
public void SaveBin( BinaryWriter writer )
{
writer.Write( (int) 0 ); // version
writer.Write( (int) m_PacketRecorder.Packets.Count );
foreach ( TimePacket tPacket in m_PacketRecorder.Packets )
{
Packet packet = tPacket.Packet;
byte[] data = packet.Data;
writer.Write( (bool) packet.Send );
writer.Write( (long) tPacket.Time.Ticks );
if ( packet.PacketID == 0x80 ) // AccountLogin
data = new byte[] { 0x80 };
else if ( packet.PacketID == 0x91 ) // GameLogin
data = new byte[] { 0x91 };
writer.Write( (int) data.Length );
writer.Write( (byte[]) data );
}
}
private void miLoadBin_Click( object sender, System.EventArgs e )
{
if ( ofdLoadBin.ShowDialog() == DialogResult.OK )
{
FileStream stream = null;
BinaryReader reader = null;
try
{
m_PacketRecorder.Clear();
foreach ( string file in ofdLoadBin.FileNames )
{
stream = File.OpenRead( ofdLoadBin.FileName );
reader = new BinaryReader( stream );
m_PacketRecorder.LoadBin( reader );
}
UpdatePackets();
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Load error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( reader != null )
reader.Close();
if ( stream != null )
stream.Close();
}
}
}
private void miAbout_Click( object sender, System.EventArgs e )
{
About about = new About();
about.TopMost = TopMost;
about.ShowDialog();
}
private void miExtractItems_Click( object sender, System.EventArgs e )
{
if ( sfdExtractItems.ShowDialog() == DialogResult.OK )
{
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractItems.FileName );
m_PacketRecorder.ExtractItems( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
private void lvPackets_SelectedIndexChanged( object sender, System.EventArgs e )
{
if ( lvPackets.SelectedItems.Count > 0 )
{
miSetBaseTime.Enabled = true;
miHide.Enabled = true;
PacketListViewItem lvi = (PacketListViewItem)lvPackets.SelectedItems[0];
Packet packet = lvi.TimePacket.Packet;
if ( packet is BaseGump )
{
miExtractGump.Enabled = true;
miExtractGumpSphere.Enabled = true;
}
else
{
miExtractGump.Enabled = false;
miExtractGumpSphere.Enabled = false;
}
if ( packet is WorldItem )
{
miExtractItem.Enabled = true;
}
else
{
miExtractItem.Enabled = false;
}
mainContextMenu.Items.Clear();
packet.AddContextMenuItems( mainContextMenu.Items );
}
else
{
miSetBaseTime.Enabled = false;
miHide.Enabled = false;
miExtractGump.Enabled = false;
miExtractGumpSphere.Enabled = false;
miExtractItem.Enabled = false;
}
}
private void miExtractItem_Click( object sender, System.EventArgs e )
{
if ( sfdExtractGump.ShowDialog() == DialogResult.OK )
{
PacketListViewItem lvi = (PacketListViewItem) lvPackets.SelectedItems[ 0 ];
WorldItem item = (WorldItem) lvi.TimePacket.Packet;
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractGump.FileName );
item.WriteRunUOClass( writer, Path.GetFileNameWithoutExtension( sfdExtractGump.FileName ) );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
private void miExtractGump_Click( object sender, System.EventArgs e )
{
if ( sfdExtractGump.ShowDialog() == DialogResult.OK )
{
PacketListViewItem lvi = (PacketListViewItem)lvPackets.SelectedItems[0];
BaseGump gump = (BaseGump)lvi.TimePacket.Packet;
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractGump.FileName );
gump.WriteRunUOClass( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
private void miExtractGumpSphere_Click( object sender, System.EventArgs e )
{
if ( sfdExtractGumpSphere.ShowDialog() == DialogResult.OK )
{
PacketListViewItem lvi = (PacketListViewItem)lvPackets.SelectedItems[0];
BaseGump gump = (BaseGump)lvi.TimePacket.Packet;
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractGumpSphere.FileName );
gump.WriteSphereGump( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
private delegate void TitleUpdater( string affix );
public void DisplayCounter( int sentPackets, int sentPacketsSize, int recvPackets, int recvPacketsSize )
{
string title = string.Format( "(Packets/sec) s:{0} r:{1} T:{2} - (Bytes/sec) s:{3} r:{4} T:{5}",
sentPackets, recvPackets, sentPackets + recvPackets, sentPacketsSize, recvPacketsSize, sentPacketsSize + recvPacketsSize );
if ( Handle != IntPtr.Zero )
BeginInvoke( new TitleUpdater( UpdateTitle ), new object[] { title } );
}
private void miExtractBooks_Click( object sender, System.EventArgs e )
{
SelectBook selection = new SelectBook( new ArrayList( m_PacketRecorder.Books.Values ) );
if ( selection.ShowDialog() == DialogResult.OK )
{
BookInfo book = selection.GetSelectedBook();
if ( book != null && sfdExtractBook.ShowDialog() == DialogResult.OK )
{
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractBook.FileName );
book.WriteRunUOClass( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
}
#region Loot Analyzer
private LootAnalyzer m_Analyzer;
private void miLootAnalyze_Click( object sender, EventArgs e )
{
if ( m_Analyzer == null )
m_Analyzer = new LootAnalyzer();
if ( m_LootFilterForm == null )
m_LootFilterForm = new LootFilterForm( m_Analyzer.Filter );
foreach ( TimePacket p in m_PacketRecorder.Packets )
m_Analyzer.AnalyzePacket( p.Packet );
MessageBox.Show( "Analyzing Complete", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information );
}
private void miLootSave_Click( object sender, EventArgs e )
{
if ( m_Analyzer == null )
m_Analyzer = new LootAnalyzer();
if ( m_LootFilterForm == null )
m_LootFilterForm = new LootFilterForm( m_Analyzer.Filter );
if ( m_LootFilterForm.ShowDialog() == DialogResult.OK )
{
try
{
m_Analyzer.PrintReport( m_LootFilterForm.FileName );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
}
#endregion
#region Vendor Analyzer
private VendorAnalyzer m_VendorAnalyzer;
private void miVendorAnalyze_Click( object sender, EventArgs e )
{
if ( m_VendorAnalyzer == null )
m_VendorAnalyzer = new VendorAnalyzer();
foreach ( TimePacket p in m_PacketRecorder.Packets )
m_VendorAnalyzer.AnalyzePacket( p.Packet );
if ( sfdSaveVendor.ShowDialog() == DialogResult.OK )
{
try
{
m_VendorAnalyzer.PrintReport( sfdSaveVendor.FileName );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
}
#endregion
private void mainContextMenu_Opening( object sender, CancelEventArgs e )
{
if ( mainContextMenu.Items.Count == 0 )
e.Cancel = true;
}
private void Display_FormClosing( object sender, FormClosingEventArgs e )
{
PacketPump = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using iSukces.Code.Interfaces;
namespace iSukces.Code.AutoCode
{
public partial class Generators
{
public class BuilderForTypeGenerator : SingleClassGenerator<Auto.BuilderForTypeAttribute>
{
protected virtual void AddIBuilderAttribute()
{
#if SAMPLE
given interface :
public interface IBuilder<out TResult>
{
TResult Build();
}
following code decorates builder class with IBuilder<> implementation
var atTargetType = Attribute.TargetType;
var t = typeof(IBuilder<>).MakeGenericType(atTargetType);
var typeName = _class.GetTypeName(t);
// if (typeName=="IBuilder<PolyLinePoint>") Developer.Nop();
_class.ImplementedInterfaces.Add(typeName);
#endif
}
protected virtual void AddWithMethod(string propName, Type propertyType)
{
var pName = "new" + propName;
var propertyTypeName = _class.GetTypeName(propertyType);
var m = _class.AddMethod("With" + propName, _class.Name)
.WithAggressiveInlining(_class)
.WithBody(string.Format("{0} = {1};\r\nreturn this;", propName, pName));
m.AddParam(pName, propertyTypeName);
var property = new NameAndTypeName(propName, propertyTypeName);
AfterAddWithMethod(propertyType, property);
}
protected virtual void AfterAddWithMethod(Type propertyType, NameAndTypeName property)
{
#if SAMPLE
// sample code for creating custom Withxxx methods
if (propertyType == typeof(Point))
AddWithMethodUsingPropertyTypeConstructor(property, new NameAndType("X", null), new NameAndType("Y", null));
if (propertyType == typeof(PdAngleRange))
AddWithMethodUsingPropertyTypeConstructor(property, new NameAndType("Begin", null), new Tuple<string, Type>("End", null));
#endif
}
protected override void GenerateInternal()
{
try
{
var ats = Type.GetCustomAttributes<Auto.BuilderForTypePropertyAttribute>().ToArray();
_attributesForProperties = ats.ToDictionary(a => a.PropertyName, a => a);
var constructors = Attribute.TargetType.GetConstructors()
.Select(a => a.GetParameters())
.OrderByDescending(a => a.Length)
.ToArray();
if (constructors.Length == 0)
return;
var constructorParameterInfos = constructors[0];
if (constructorParameterInfos.Length == 0)
return;
_builderPropertyInfos = constructorParameterInfos.MapToArray(q =>
{
var info = BuilderPropertyInfo.MakeInfo(q, _attributesForProperties, Attribute);
return info;
});
_class = Context.GetOrCreateClass(Type);
_class.IsPartial = true;
AddIBuilderAttribute();
AddConstructors();
AddWithMethodsAndProperties();
AddBuildMethod();
}
finally
{
_class = null;
_attributesForProperties = null;
_builderPropertyInfos = null;
}
}
protected void AddWithMethodUsingPropertyTypeConstructor(NameAndTypeName property,
params NameAndType[] constructorParams)
{
var m = _class.AddMethod("With" + property.PropName, _class.Name)
.WithAggressiveInlining(_class);
var l = new List<string>();
foreach (var i in constructorParams)
{
var pName = $"new{i.Name}X";
l.Add(pName);
m.AddParam(pName, _class.GetTypeName(i.Type ?? typeof(double)));
}
var ll = string.Join(", ", l);
m.Body = $"{property.PropName} = new {property.PropertyTypeName}({ll});\r\nreturn this;";
}
private void AddBuildMethod()
{
var constructorParametersNames = _builderPropertyInfos.MapToArray(a => a.PropertyName);
var m = _class
.AddMethod("Build", _class.GetTypeName(Attribute.TargetType))
.WithAggressiveInlining(_class);
m.Body = string.Format("return new {0}({1});",
m.ResultType, string.Join(", ", constructorParametersNames));
}
private void AddConstructors()
{
// pusty konstruktor
_class.AddConstructor();
// konstruktor2
CodeWriter c = new CsCodeWriter();
if (Attribute.TargetType.IsClass)
c.WriteLine("if (source is null) return;");
foreach (var i in _builderPropertyInfos)
c.WriteLine(string.Format("{0} = source.{0};", i.PropertyName));
var m = _class.AddConstructor()
.WithBody(c);
m.Parameters.Add(new CsMethodParameter("source", _class.GetTypeName(Attribute.TargetType)));
}
private void AddWithMethodsAndProperties()
{
for (var index = 0; index < _builderPropertyInfos.Length; index++)
{
var info = _builderPropertyInfos[index];
var propertyTypeName = _class.GetTypeName(info.PropertyType);
var prop = _class.AddProperty(info.PropertyName, propertyTypeName)
.WithMakeAutoImplementIfPossible();
if (info.Create)
prop.WithConstValue("new " + propertyTypeName + "()");
if (!info.SkipWithMethod)
AddWithMethod(info.PropertyName, info.PropertyType);
if (!info.ExpandFlags) continue;
// var enumUnderlyingType = Enum.GetUnderlyingType(info.PropertyType);
foreach (var enumValue in Enum.GetValues(info.PropertyType))
{
// var value1 = Convert.ChangeType(enumValue, enumUnderlyingType);
var value2 = (int)Convert.ChangeType(enumValue, typeof(int));
if (value2 == 0)
continue;
var enumName = Enum.GetName(info.PropertyType, enumValue);
var propName = enumName.FirstUpper();
var prop1 = _class.AddProperty(propName, "bool")
.WithNoEmitField();
var v = $"{propertyTypeName}.{enumName}";
prop1.OwnGetter = $"return ({info.PropertyName} & {v}) != 0;";
prop1.OwnSetter =
$"{info.PropertyName} = value ? {info.PropertyName} | {v} : {info.PropertyName} & ~{v};";
// metoda
if (!info.SkipWithMethod)
AddWithMethod(propName, typeof(bool));
}
}
}
private BuilderPropertyInfo[] _builderPropertyInfos;
private CsClass _class;
private IReadOnlyDictionary<string, Auto.BuilderForTypePropertyAttribute> _attributesForProperties;
private sealed class BuilderPropertyInfo
{
public static BuilderPropertyInfo MakeInfo(ParameterInfo parameterInfo,
IReadOnlyDictionary<string, Auto.BuilderForTypePropertyAttribute> attributesForProperties,
Auto.BuilderForTypeAttribute at)
{
var propName = parameterInfo.Name.FirstUpper();
attributesForProperties.TryGetValue(propName, out var pa);
var a = new BuilderPropertyInfo
{
PropertyName = propName,
PropertyType = pa?.Type ?? parameterInfo.ParameterType,
SkipWithMethod = at.SkipWithFor != null && at.SkipWithFor.Length > 0 &&
at.SkipWithFor.Contains(propName),
Create = pa?.Create ?? false
//ExpandFlags = pa?.ExpandFlags ?? false
};
if (pa?.ExpandFlags ?? false)
if (a.PropertyType.IsEnum)
if (a.PropertyType.GetCustomAttribute<FlagsAttribute>() != null)
a.ExpandFlags = true;
return a;
}
public string PropertyName { get; private set; }
public Type PropertyType { get; private set; }
public bool SkipWithMethod { get; private set; }
public bool Create { get; private set; }
public bool ExpandFlags { get; set; }
}
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2018 FUJIWARA, Yusuke
//
// 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.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using MsgPack.Serialization.DefaultSerializers;
using MsgPack.Serialization.Polymorphic;
namespace MsgPack.Serialization
{
/// <summary>
/// Repository of known <see cref="MessagePackSerializer{T}"/>s.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Class coupling caused by default serializers registration." )]
public sealed partial class SerializerRepository : IDisposable
{
private static readonly object SyncRoot = new object();
private static SerializerRepository _internalDefault;
internal static SerializerRepository InternalDefault
{
get
{
// Lazy init to avoid .cctor recursion from SerializationContext.cctor()
lock ( SyncRoot )
{
if ( _internalDefault == null )
{
_internalDefault = GetDefault( SerializationContext.Default );
}
return _internalDefault;
}
}
}
private readonly SerializerTypeKeyRepository _repository;
/// <summary>
/// Initializes a new empty instance of the <see cref="SerializerRepository"/> class.
/// </summary>
public SerializerRepository()
{
this._repository = new SerializerTypeKeyRepository();
}
/// <summary>
/// Initializes a new instance of the <see cref="SerializerRepository"/> class which has copied serializers.
/// </summary>
/// <param name="copiedFrom">The repository which will be copied its contents.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="copiedFrom"/> is <c>null</c>.
/// </exception>
public SerializerRepository( SerializerRepository copiedFrom )
{
if ( copiedFrom == null )
{
throw new ArgumentNullException( "copiedFrom" );
}
this._repository = new SerializerTypeKeyRepository( copiedFrom._repository );
}
private SerializerRepository( Dictionary<RuntimeTypeHandle, object> table )
{
this._repository = new SerializerTypeKeyRepository( table );
}
/// <summary>
/// This method does not perform any operation.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_repository" )]
[Obsolete( "This class should not be disposable, so IDisposable will be removed in future." )]
public void Dispose()
{
// nop
}
/// <summary>
/// Gets the registered <see cref="MessagePackSerializer{T}"/> from this repository without provider parameter.
/// </summary>
/// <typeparam name="T">Type of the object to be marshaled/unmarshaled.</typeparam>
/// <param name="context">A serialization context.</param>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>. If no appropriate mashalers has benn registered, then <c>null</c>.
/// </returns>
public MessagePackSerializer<T> Get<T>( SerializationContext context )
{
return this.Get<T>( context, null );
}
/// <summary>
/// Gets the registered <see cref="MessagePackSerializer{T}"/> from this repository with specified provider parameter.
/// </summary>
/// <typeparam name="T">Type of the object to be marshaled/unmarshaled.</typeparam>
/// <param name="context">A serialization context.</param>
/// <param name="providerParameter">A provider specific parameter. See remarks section of <see cref="SerializationContext.GetSerializer{T}(Object)"/> for details.</param>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>. If no appropriate mashalers has benn registered, then <c>null</c>.
/// </returns>
/// <see cref="SerializationContext.GetSerializer{T}(Object)"/>
public MessagePackSerializer<T> Get<T>( SerializationContext context, object providerParameter )
{
if ( context == null )
{
throw new ArgumentNullException( "context" );
}
var result = this._repository.Get( context, typeof( T ) );
var asProvider = result as MessagePackSerializerProvider;
#if !UNITY
return ( asProvider != null ? asProvider.Get( context, providerParameter ) : result ) as MessagePackSerializer<T>;
#else
var asSerializer =
( asProvider != null ? asProvider.Get( context, providerParameter ) : result ) as MessagePackSerializer;
return asSerializer != null ? MessagePackSerializer.Wrap<T>( context, asSerializer ) : null;
#endif // !UNITY
}
#if UNITY
internal MessagePackSerializer Get( SerializationContext context, Type targetType, object providerParameter )
{
if ( context == null )
{
throw new ArgumentNullException( "context" );
}
if ( targetType == null )
{
throw new ArgumentNullException( "targetType" );
}
var result = this._repository.Get( context, targetType );
var asProvider = result as MessagePackSerializerProvider;
return ( asProvider != null ? asProvider.Get( context, providerParameter ) : result ) as MessagePackSerializer;
}
#endif // UNITY
/// <summary>
/// Registers a <see cref="MessagePackSerializer{T}"/>.
/// </summary>
/// <typeparam name="T">The type of serialization target.</typeparam>
/// <param name="serializer"><see cref="MessagePackSerializer{T}"/> instance.</param>
/// <returns>
/// <c>true</c> if success to register; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializer"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This method invokes <see cref="Register{T}(MsgPack.Serialization.MessagePackSerializer{T},SerializerRegistrationOptions)"/> with <see cref="SerializerRegistrationOptions.None"/>.
/// <note>
/// If you register serializer for value type, using <see cref="SerializerRegistrationOptions.WithNullable"/> is recommended because auto-generated deserializers use them to handle nil value.
/// You can use <see cref="Register{T}(MsgPack.Serialization.MessagePackSerializer{T},SerializerRegistrationOptions)"/> with <see cref="SerializerRegistrationOptions.WithNullable"/> to
/// get equivalant behavior for this method with registering nullable serializer automatically.
/// </note>
/// </remarks>
public bool Register<T>( MessagePackSerializer<T> serializer )
{
return this.Register( serializer, SerializerRegistrationOptions.None );
}
/// <summary>
/// Registers a <see cref="MessagePackSerializer{T}"/>.
/// </summary>
/// <typeparam name="T">The type of serialization target.</typeparam>
/// <param name="serializer"><see cref="MessagePackSerializer{T}"/> instance.</param>
/// <param name="options">A <see cref="SerializerRegistrationOptions"/> to control this registration process.</param>
/// <returns>
/// <c>true</c> if success to register; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializer"/> is <c>null</c>.
/// </exception>
public bool Register<T>( MessagePackSerializer<T> serializer, SerializerRegistrationOptions options )
{
if ( serializer == null )
{
throw new ArgumentNullException( "serializer" );
}
Type nullableType = null;
MessagePackSerializerProvider nullableSerializerProvider = null;
#if !UNITY
if ( ( options & SerializerRegistrationOptions.WithNullable ) != 0 )
{
GetNullableCompanion( typeof( T ), serializer.OwnerContext, serializer, out nullableType, out nullableSerializerProvider );
}
#endif // !UNITY
#if !UNITY
return this.Register( typeof( T ), new PolymorphicSerializerProvider<T>( serializer ), nullableType, nullableSerializerProvider, options );
#else
return this.Register( typeof( T ), new PolymorphicSerializerProvider<T>( serializer.OwnerContext, serializer ), nullableType, nullableSerializerProvider, options );
#endif // !UNITY
}
#if !UNITY
internal static void GetNullableCompanion(
Type targetType,
SerializationContext context,
object serializer,
out Type nullableType,
out MessagePackSerializerProvider nullableSerializerProvider
)
{
if ( targetType.GetIsValueType() && Nullable.GetUnderlyingType( targetType ) == null )
{
nullableType = typeof( Nullable<> ).MakeGenericType( targetType );
var nullableCtor =
typeof( NullableMessagePackSerializer<> ).MakeGenericType( targetType ).GetConstructor(
new[]
{
typeof( SerializationContext ),
typeof( MessagePackSerializer<> ).MakeGenericType( targetType )
}
);
nullableSerializerProvider =
( MessagePackSerializerProvider ) ReflectionExtensions.CreateInstancePreservingExceptionType(
typeof( PolymorphicSerializerProvider<> ).MakeGenericType( nullableType ),
nullableCtor.InvokePreservingExceptionType(
context,
serializer
)
);
}
else
{
nullableType = null;
nullableSerializerProvider = null;
}
}
#endif // !UNITY
#if UNITY && DEBUG
public
#else
internal
#endif
bool Register( Type targetType, MessagePackSerializerProvider serializerProvider, Type nullableType, MessagePackSerializerProvider nullableSerializerProvider, SerializerRegistrationOptions options )
{
return this._repository.Register( targetType, serializerProvider, nullableType, nullableSerializerProvider, options );
}
/// <summary>
/// Registers a <see cref="MessagePackSerializer{T}"/> forcibley.
/// </summary>
/// <typeparam name="T">The type of serialization target.</typeparam>
/// <param name="serializer"><see cref="MessagePackSerializer{T}"/> instance.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializer"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This method invokes <see cref="Register{T}(MsgPack.Serialization.MessagePackSerializer{T},SerializerRegistrationOptions)"/> with <see cref="SerializerRegistrationOptions.AllowOverride"/>.
/// <note>
/// If you register serializer for value type, using <see cref="SerializerRegistrationOptions.WithNullable"/> is recommended because auto-generated deserializers use them to handle nil value.
/// You can use <see cref="Register{T}(MsgPack.Serialization.MessagePackSerializer{T},SerializerRegistrationOptions)"/>
/// with <see cref="SerializerRegistrationOptions.AllowOverride"/> and <see cref="SerializerRegistrationOptions.WithNullable"/> to
/// get equivalant behavior for this method with registering nullable serializer automatically.
/// </note>
/// </remarks>
public void RegisterOverride<T>( MessagePackSerializer<T> serializer )
{
this.Register( serializer, SerializerRegistrationOptions.AllowOverride );
}
/// <summary>
/// Gets the system default repository bound to default context.
/// </summary>
/// <value>
/// The system default repository.
/// This value will not be <c>null</c>.
/// Note that the repository is frozen.
/// </value>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "Historical reason" )]
[Obsolete( "Use GetDefault()")]
public static SerializerRepository Default
{
get { return GetDefault( SerializationContext.Default ); }
}
/// <summary>
/// Gets the system default repository bound to default context.
/// </summary>
/// <returns>
/// The system default repository.
/// This value will not be <c>null</c>.
/// Note that the repository is frozen.
/// </returns>
public static SerializerRepository GetDefault()
{
return GetDefault( SerializationContext.Default );
}
/// <summary>
/// Gets the system default repository bound to default context.
/// </summary>
/// <param name="packerCompatibilityOptions">Not used.</param>
/// <returns>
/// The system default repository.
/// This value will not be <c>null</c>.
/// Note that the repository is frozen.
/// </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "packerCompatibilityOptions", Justification = "Historical reason" )]
[Obsolete( "Use GetDefault()" )]
public static SerializerRepository GetDefault( PackerCompatibilityOptions packerCompatibilityOptions )
{
return GetDefault( SerializationContext.Default );
}
/// <summary>
/// Gets the system default repository bound for specified context.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which will be bound to default serializers.</param>
/// <exception cref="ArgumentNullException"><paramref name="ownerContext"/> is <c>null</c>.</exception>
/// <returns>
/// The system default repository.
/// This value will not be <c>null</c>.
/// Note that the repository is frozen.
/// </returns>
public static SerializerRepository GetDefault( SerializationContext ownerContext )
{
if ( ownerContext == null )
{
throw new ArgumentNullException( "ownerContext" );
}
return new SerializerRepository( InitializeDefaultTable( ownerContext ) );
}
/// <summary>
/// Determines whether this repository contains serializer for the specified target type.
/// </summary>
/// <param name="targetType">Type of the target.</param>
/// <returns>
/// <c>true</c> if this repository contains serializer for the specified target type; otherwise, <c>false</c>.
/// This method returns <c>false</c> for <c>null</c>.
/// </returns>
public bool ContainsFor( Type targetType )
{
return this._repository.Contains( targetType );
}
/// <summary>
/// Gets the copy of registered serializer entries.
/// </summary>
/// <returns>
/// The copy of registered serializer entries.
/// This value will not be <c>null</c> and consistent in the invoked timing.
/// </returns>
/// <remarks>
/// This method returns snapshot of the invoked timing, so the result may not reflect latest status.
/// You should use the result for debugging or tooling purpose only.
/// Use <c>Get()</c> overloads to get proper serializer.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method causes collection copying." )]
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design" )]
public IEnumerable<KeyValuePair<Type, MessagePackSerializer>> GetRegisteredSerializers()
{
return
this._repository.GetEntries()
.Select( kv => new KeyValuePair<Type, MessagePackSerializer>( kv.Key, kv.Value as MessagePackSerializer ) )
.Where( kV => kV.Value != null );
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt163()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt163();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt163
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt16[] values = new UInt16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt16();
}
Vector128<UInt16> value = Vector128.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt16 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt16 insertedValue = TestLibrary.Generator.GetUInt16();
try
{
Vector128<UInt16> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt16[] values = new UInt16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt16();
}
Vector128<UInt16> value = Vector128.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.GetElement))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt16)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt16 insertedValue = TestLibrary.Generator.GetUInt16();
try
{
object result2 = typeof(Vector128)
.GetMethod(nameof(Vector128.WithElement))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector128<UInt16>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt16 result, UInt16[] values, [CallerMemberName] string method = "")
{
if (result != values[3])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.GetElement(3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector128<UInt16> result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "")
{
UInt16[] resultElements = new UInt16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt16[] result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 3) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[3] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.WithElement(3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//
// ZoneTest.cs - NUnit Test Cases for Zone
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Policy;
namespace MonoTests.System.Security.Policy {
[TestFixture]
public class ZoneTest : Assertion {
[Test]
public void MyComputer ()
{
Zone z = new Zone (SecurityZone.MyComputer);
AssertEquals ("MyComputer.SecurityZone", SecurityZone.MyComputer, z.SecurityZone);
Assert ("MyComputer.ToString", (z.ToString ().IndexOf ("<Zone>MyComputer</Zone>") >= 0));
Zone zc = (Zone) z.Copy ();
Assert ("MyComputer.Copy.Equals", z.Equals (zc));
IPermission p = z.CreateIdentityPermission (null);
AssertNotNull ("MyComputer.CreateIdentityPermission", p);
Assert ("MyComputer.MyComputer.Equals", z.Equals (new Zone (SecurityZone.MyComputer)));
Assert ("MyComputer.Intranet.Equals", !z.Equals (new Zone (SecurityZone.Intranet)));
Assert ("MyComputer.Trusted.Equals", !z.Equals (new Zone (SecurityZone.Trusted)));
Assert ("MyComputer.Internet.Equals", !z.Equals (new Zone (SecurityZone.Internet)));
Assert ("MyComputer.Untrusted.Equals", !z.Equals (new Zone (SecurityZone.Untrusted)));
Assert ("MyComputer.NoZone.Equals", !z.Equals (new Zone (SecurityZone.NoZone)));
Assert ("MyComputer.Null.Equals", !z.Equals (null));
}
[Test]
public void Intranet ()
{
Zone z = new Zone (SecurityZone.Intranet);
AssertEquals ("Intranet.SecurityZone", SecurityZone.Intranet, z.SecurityZone);
Assert ("Intranet.ToString", (z.ToString ().IndexOf ("<Zone>Intranet</Zone>") >= 0));
Zone zc = (Zone) z.Copy ();
Assert ("Intranet.Copy.Equals", z.Equals (zc));
IPermission p = z.CreateIdentityPermission (null);
AssertNotNull ("Intranet.CreateIdentityPermission", p);
Assert ("Intranet.MyComputer.Equals", !z.Equals (new Zone (SecurityZone.MyComputer)));
Assert ("Intranet.Intranet.Equals", z.Equals (new Zone (SecurityZone.Intranet)));
Assert ("Intranet.Trusted.Equals", !z.Equals (new Zone (SecurityZone.Trusted)));
Assert ("Intranet.Internet.Equals", !z.Equals (new Zone (SecurityZone.Internet)));
Assert ("Intranet.Untrusted.Equals", !z.Equals (new Zone (SecurityZone.Untrusted)));
Assert ("Intranet.NoZone.Equals", !z.Equals (new Zone (SecurityZone.NoZone)));
Assert ("Intranet.Null.Equals", !z.Equals (null));
}
[Test]
public void Trusted ()
{
Zone z = new Zone (SecurityZone.Trusted);
AssertEquals ("Trusted.SecurityZone", SecurityZone.Trusted, z.SecurityZone);
Assert ("Trusted.ToString", (z.ToString ().IndexOf ("<Zone>Trusted</Zone>") >= 0));
Zone zc = (Zone) z.Copy ();
Assert ("Trusted.Copy.Equals", z.Equals (zc));
IPermission p = z.CreateIdentityPermission (null);
AssertNotNull ("Trusted.CreateIdentityPermission", p);
Assert ("Trusted.MyComputer.Equals", !z.Equals (new Zone (SecurityZone.MyComputer)));
Assert ("Trusted.Intranet.Equals", !z.Equals (new Zone (SecurityZone.Intranet)));
Assert ("Trusted.Trusted.Equals", z.Equals (new Zone (SecurityZone.Trusted)));
Assert ("Trusted.Internet.Equals", !z.Equals (new Zone (SecurityZone.Internet)));
Assert ("Trusted.Untrusted.Equals", !z.Equals (new Zone (SecurityZone.Untrusted)));
Assert ("Trusted.NoZone.Equals", !z.Equals (new Zone (SecurityZone.NoZone)));
Assert ("Trusted.Null.Equals", !z.Equals (null));
}
[Test]
public void Internet ()
{
Zone z = new Zone (SecurityZone.Internet);
AssertEquals ("Internet.SecurityZone", SecurityZone.Internet, z.SecurityZone);
Assert ("Internet.ToString", (z.ToString ().IndexOf ("<Zone>Internet</Zone>") >= 0));
Zone zc = (Zone) z.Copy ();
Assert ("Internet.Copy.Equals", z.Equals (zc));
IPermission p = z.CreateIdentityPermission (null);
AssertNotNull ("Internet.CreateIdentityPermission", p);
Assert ("Internet.MyComputer.Equals", !z.Equals (new Zone (SecurityZone.MyComputer)));
Assert ("Internet.Intranet.Equals", !z.Equals (new Zone (SecurityZone.Intranet)));
Assert ("Internet.Trusted.Equals", !z.Equals (new Zone (SecurityZone.Trusted)));
Assert ("Internet.Internet.Equals", z.Equals (new Zone (SecurityZone.Internet)));
Assert ("Internet.Untrusted.Equals", !z.Equals (new Zone (SecurityZone.Untrusted)));
Assert ("Internet.NoZone.Equals", !z.Equals (new Zone (SecurityZone.NoZone)));
Assert ("Internet.Null.Equals", !z.Equals (null));
}
[Test]
public void Untrusted ()
{
Zone z = new Zone (SecurityZone.Untrusted);
AssertEquals ("Untrusted.SecurityZone", SecurityZone.Untrusted, z.SecurityZone);
Assert ("Untrusted.ToString", (z.ToString ().IndexOf ("<Zone>Untrusted</Zone>") >= 0));
Zone zc = (Zone) z.Copy ();
Assert ("Untrusted.Copy.Equals", z.Equals (zc));
IPermission p = z.CreateIdentityPermission (null);
AssertNotNull ("Untrusted.CreateIdentityPermission", p);
Assert ("Untrusted.MyComputer.Equals", !z.Equals (new Zone (SecurityZone.MyComputer)));
Assert ("Untrusted.Intranet.Equals", !z.Equals (new Zone (SecurityZone.Intranet)));
Assert ("Untrusted.Trusted.Equals", !z.Equals (new Zone (SecurityZone.Trusted)));
Assert ("Untrusted.Internet.Equals", !z.Equals (new Zone (SecurityZone.Internet)));
Assert ("Untrusted.Untrusted.Equals", z.Equals (new Zone (SecurityZone.Untrusted)));
Assert ("Untrusted.NoZone.Equals", !z.Equals (new Zone (SecurityZone.NoZone)));
Assert ("Untrusted.Null.Equals", !z.Equals (null));
}
[Test]
public void NoZone ()
{
Zone z = new Zone (SecurityZone.NoZone);
AssertEquals ("NoZone.SecurityZone", SecurityZone.NoZone, z.SecurityZone);
Assert ("NoZone.ToString", (z.ToString ().IndexOf ("<Zone>NoZone</Zone>") >= 0));
Zone zc = (Zone) z.Copy ();
Assert ("NoZone.Copy.Equals", z.Equals (zc));
IPermission p = z.CreateIdentityPermission (null);
AssertNotNull ("NoZone.CreateIdentityPermission", p);
// NoZone isn't added to the XML / string of permissions
Assert ("ToString!=NoZone", p.ToString ().IndexOf ("NoZone") < 0);
Assert ("NoZone.MyComputer.Equals", !z.Equals (new Zone (SecurityZone.MyComputer)));
Assert ("NoZone.Intranet.Equals", !z.Equals (new Zone (SecurityZone.Intranet)));
Assert ("NoZone.Trusted.Equals", !z.Equals (new Zone (SecurityZone.Trusted)));
Assert ("NoZone.Internet.Equals", !z.Equals (new Zone (SecurityZone.Internet)));
Assert ("NoZone.Untrusted.Equals", !z.Equals (new Zone (SecurityZone.Untrusted)));
Assert ("NoZone.NoZone.Equals", z.Equals (new Zone (SecurityZone.NoZone)));
Assert ("NoZone.Null.Equals", !z.Equals (null));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CreateFromUrl_Null ()
{
Zone.CreateFromUrl (null);
}
string[] noZoneUrls = {
String.Empty, // not accepted for a Site
};
[Test]
public void CreateFromUrl_NoZone ()
{
foreach (string url in noZoneUrls) {
Zone z = Zone.CreateFromUrl (url);
AssertEquals (url, SecurityZone.NoZone, z.SecurityZone);
}
}
// files are always rooted (Path.IsPathRooted) and exists (File.Exists)
string[] myComputerUrls = {
Path.GetTempFileName (),
Assembly.GetExecutingAssembly ().Location,
};
[Test]
public void CreateFromUrl_MyComputer ()
{
foreach (string u in myComputerUrls) {
string url = u;
Zone z = Zone.CreateFromUrl (url);
AssertEquals (url, SecurityZone.MyComputer, z.SecurityZone);
url = "file://" + u;
z = Zone.CreateFromUrl (url);
AssertEquals (url, SecurityZone.MyComputer, z.SecurityZone);
url = "FILE://" + u;
z = Zone.CreateFromUrl (url);
AssertEquals (url, SecurityZone.MyComputer, z.SecurityZone);
}
}
string[] intranetUrls = {
"file://mono/index.html", // file:// isn't supported as a site
"FILE://MONO/INDEX.HTML",
};
[Test]
public void CreateFromUrl_Intranet ()
{
foreach (string url in intranetUrls) {
Zone z = Zone.CreateFromUrl (url);
AssertEquals (url, SecurityZone.Intranet, z.SecurityZone);
}
}
string[] internetUrls = {
"http://www.go-mono.com",
"http://64.14.94.188/",
"HTTP://WWW.GO-MONO.COM",
"http://*.go-mono.com",
"http://www.go-mono.com:8080/index.html",
"mono://unknown/protocol",
Path.DirectorySeparatorChar + "mono" + Path.DirectorySeparatorChar + "index.html",
};
[Test]
public void CreateFromUrl_Internet ()
{
foreach (string url in internetUrls) {
Zone z = Zone.CreateFromUrl (url);
AssertEquals (url, SecurityZone.Internet, z.SecurityZone);
}
}
[Test]
public void ToString_ ()
{
Zone z = Zone.CreateFromUrl (String.Empty);
string ts = z.ToString ();
Assert ("Class", ts.StartsWith ("<System.Security.Policy.Zone"));
Assert ("Version", (ts.IndexOf (" version=\"1\"") >= 0));
Assert ("Zone", (ts.IndexOf ("<Zone>NoZone</Zone>") >= 0));
Assert ("End", (ts.IndexOf ("</System.Security.Policy.Zone>") >= 0));
}
}
}
| |
namespace Loon.Action.Avg
{
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Loon.Core.Graphics.Opengl;
using Loon.Core.Graphics;
using Loon.Utils;
using Loon.Core;
using Loon.Core.Graphics.Device;
public class AVGDialog
{
private static Dictionary<string, LTexture> lazyImages;
public static LTexture GetRMXPDialog(string fileName, int width,
int height)
{
if (lazyImages == null)
{
lazyImages = new Dictionary<string, LTexture>(10);
}
LImage dialog = LImage.CreateImage(fileName);
int w = dialog.GetWidth();
Color[] pixels = dialog.GetPixels();
int index = -1;
int count = 0;
uint pixel;
for (int i = 0; i < 5; i++)
{
pixel = pixels[(141 + i) + w * 12].PackedValue;
if (index == -1)
{
index = (int)pixel;
}
if (index == pixel)
{
count++;
}
}
if (count == 5)
{
return GetRMXPDialog(dialog, width, height, 16, 5);
}
else if (count == 1)
{
return GetRMXPDialog(dialog, width, height, 27, 5);
}
else if (count == 2)
{
return GetRMXPDialog(dialog, width, height, 20, 5);
}
else
{
return GetRMXPDialog(dialog, width, height, 27, 5);
}
}
public static LTexture GetRMXPloadBuoyage(string fileName, int width,
int height)
{
return GetRMXPloadBuoyage(LImage.CreateImage(fileName), width,
height);
}
public static LTexture GetRMXPloadBuoyage(LImage rmxpImage,
int width, int height)
{
if (lazyImages == null)
{
lazyImages = new Dictionary<string, LTexture>(10);
}
string keyName = ("buoyage" + width + "|" + height);
LTexture lazy = (LTexture)CollectionUtils.Get(lazyImages, keyName);
if (lazy == null)
{
LImage lazyImage;
LImage image, left, right, center, up, down = null;
int objWidth = 32;
int objHeight = 32;
int x1 = 128;
int x2 = 160;
int y1 = 64;
int y2 = 96;
int k = 1;
try
{
image = GraphicsUtils.DrawClipImage(rmxpImage, objWidth,
objHeight, x1, y1, x2, y2);
lazyImage = LImage.CreateImage(width, height, true);
LGraphics g = lazyImage.GetLGraphics();
left = GraphicsUtils.DrawClipImage(image, k, height, 0, 0, k,
objHeight);
right = GraphicsUtils.DrawClipImage(image, k, height, objWidth
- k, 0, objWidth, objHeight);
center = GraphicsUtils.DrawClipImage(image, width, height, k,
k, objWidth - k, objHeight - k);
up = GraphicsUtils.DrawClipImage(image, width, k, 0, 0,
objWidth, k);
down = GraphicsUtils.DrawClipImage(image, width, k, 0,
objHeight - k, objWidth, objHeight);
g.DrawImage(center, 0, 0);
g.DrawImage(left, 0, 0);
g.DrawImage(right, width - k, 0);
g.DrawImage(up, 0, 0);
g.DrawImage(down, 0, height - k);
g.Dispose();
lazy = lazyImage.GetTexture();
if (lazyImage != null)
{
lazyImage.Dispose();
lazyImage = null;
}
lazyImages.Add(keyName, lazy);
}
catch
{
return null;
}
finally
{
left = null;
right = null;
center = null;
up = null;
down = null;
image = null;
}
}
return lazy;
}
private static LTexture GetRMXPDialog(LImage rmxpImage, int width,
int height, int size, int offset)
{
if (lazyImages == null)
{
lazyImages = new Dictionary<string, LTexture>(10);
}
string keyName = "dialog" + width + "|" + height;
LTexture lazy = (LTexture)CollectionUtils.Get(lazyImages, keyName);
if (lazy == null)
{
try
{
int objWidth = 64;
int objHeight = 64;
int x1 = 128;
int x2 = 192;
int y1 = 0;
int y2 = 64;
int center_size = objHeight - size * 2;
LImage lazyImage = null;
LImage image = null;
LImage messageImage = null;
image = GraphicsUtils.DrawClipImage(rmxpImage, objWidth,
objHeight, x1, y1, x2, y2);
LImage centerTop = GraphicsUtils.DrawClipImage(image,
center_size, size, size, 0);
LImage centerDown = GraphicsUtils.DrawClipImage(image,
center_size, size, size, objHeight - size);
LImage leftTop = GraphicsUtils.DrawClipImage(image, size, size,
0, 0);
LImage leftCenter = GraphicsUtils.DrawClipImage(image, size,
center_size, 0, size);
LImage leftDown = GraphicsUtils.DrawClipImage(image, size,
size, 0, objHeight - size);
LImage rightTop = GraphicsUtils.DrawClipImage(image, size,
size, objWidth - size, 0);
LImage rightCenter = GraphicsUtils.DrawClipImage(image, size,
center_size, objWidth - size, size);
LImage rightDown = GraphicsUtils.DrawClipImage(image, size,
size, objWidth - size, objHeight - size);
lazyImage = centerTop;
lazyImage = LImage.CreateImage(width, height, true);
LGraphics g = lazyImage.GetLGraphics();
g.SetAlpha(0.5f);
messageImage = GraphicsUtils.DrawClipImage(rmxpImage, 128, 128,
0, 0, 128, 128);
messageImage = GraphicsUtils.GetResize(messageImage, width
- offset, height - offset);
messageImage.XNAUpdateAlpha(125);
g.DrawImage(messageImage, (lazyImage.Width - messageImage.Width) / 2 + 1, (lazyImage.Height - messageImage
.Height) / 2 + 1);
LImage tmp = GraphicsUtils.GetResize(centerTop, width
- (size * 2), size);
g.DrawImage(tmp, size, 0);
if (tmp != null)
{
tmp.Dispose();
tmp = null;
}
tmp = GraphicsUtils.GetResize(centerDown, width - (size * 2),
size);
g.DrawImage(tmp, size, height - size);
if (tmp != null)
{
tmp.Dispose();
tmp = null;
}
g.DrawImage(leftTop, 0, 0);
tmp = GraphicsUtils.GetResize(leftCenter,
leftCenter.GetWidth(), width - (size * 2));
g.DrawImage(tmp, 0, size);
if (tmp != null)
{
tmp.Dispose();
tmp = null;
}
g.DrawImage(leftDown, 0, height - size);
int right = width - size;
g.DrawImage(rightTop, right, 0);
tmp = GraphicsUtils.GetResize(rightCenter, leftCenter
.Width, width - (size * 2));
g.DrawImage(tmp, right, size);
if (tmp != null)
{
tmp.Dispose();
tmp = null;
}
g.DrawImage(rightDown, right, height - size);
g.Dispose();
lazy = lazyImage.GetTexture();
lazyImages.Add(keyName, lazy);
image.Dispose();
messageImage.Dispose();
centerTop.Dispose();
centerDown.Dispose();
leftTop.Dispose();
leftCenter.Dispose();
leftDown.Dispose();
rightTop.Dispose();
rightCenter.Dispose();
rightDown.Dispose();
image = null;
messageImage = null;
centerTop = null;
centerDown = null;
leftTop = null;
leftCenter = null;
leftDown = null;
rightTop = null;
rightCenter = null;
rightDown = null;
}
catch(Exception ex)
{
Loon.Utils.Debugging.Log.Exception(ex);
}
}
return lazy;
}
public static void Clear()
{
foreach (LTexture tex2d in lazyImages.Values)
{
if (tex2d != null)
{
tex2d.Destroy();
}
}
lazyImages.Clear();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void Permute2x128Int162()
{
var test = new ImmBinaryOpTest__Permute2x128Int162();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__Permute2x128Int162
{
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__Permute2x128Int162 testClass)
{
var result = Avx.Permute2x128(_fld1, _fld2, 2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static ImmBinaryOpTest__Permute2x128Int162()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public ImmBinaryOpTest__Permute2x128Int162()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Permute2x128(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Permute2x128(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Permute2x128(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Permute2x128(
_clsVar1,
_clsVar2,
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__Permute2x128Int162();
var result = Avx.Permute2x128(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Permute2x128(_fld1, _fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Permute2x128(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i < 8 ? right[i] : left[i-8]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Permute2x128)}<Int16>(Vector256<Int16>.2, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Compute.Tests
{
public class VMScaleSetExtensionTests : VMScaleSetTestsBase
{
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VMScaleSet
/// Create VMSS Extension
/// Update VMSS Extension
/// Get VMSS Extension
/// List VMSS Extensions
/// Delete VMSS Extension
/// Delete RG
/// </summary>
[Fact]
public void TestVMScaleSetExtensions()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
TestVMScaleSetExtensionsImpl(context);
}
}
[Fact]
public void TestVMScaleSetExtensionSequencing()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
VirtualMachineScaleSet inputVMScaleSet;
try
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: false);
VirtualMachineScaleSetExtensionProfile vmssExtProfile = GetTestVmssExtensionProfile();
// Set extension sequencing (ext2 is provisioned after ext1)
vmssExtProfile.Extensions[1].ProvisionAfterExtensions = new List<string> { vmssExtProfile.Extensions[0].Name };
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName,
vmssName,
null,
imageRef,
out inputVMScaleSet,
extensionProfile: vmssExtProfile,
createWithManagedDisks: true);
Assert.Equal("PT1H20M", vmScaleSet.VirtualMachineProfile.ExtensionProfile.ExtensionsTimeBudget);
// Perform a Get operation on each extension
VirtualMachineScaleSetExtension getVmssExtResponse = null;
for (int i = 0; i < vmssExtProfile.Extensions.Count; i++)
{
getVmssExtResponse = m_CrpClient.VirtualMachineScaleSetExtensions.Get(rgName, vmssName, vmssExtProfile.Extensions[i].Name);
ValidateVmssExtension(vmssExtProfile.Extensions[i], getVmssExtResponse);
}
// Add a new extension to the VMSS (ext3 is provisioned after ext2)
VirtualMachineScaleSetExtension vmssExtension = GetTestVMSSVMExtension(name: "3", publisher: "Microsoft.CPlat.Core", type: "NullLinux", version: "4.0");
vmssExtension.ProvisionAfterExtensions = new List<string> { vmssExtProfile.Extensions[1].Name };
var response = m_CrpClient.VirtualMachineScaleSetExtensions.CreateOrUpdate(rgName, vmssName, vmssExtension.Name, vmssExtension);
ValidateVmssExtension(vmssExtension, response);
// Perform a Get operation on the extension
getVmssExtResponse = m_CrpClient.VirtualMachineScaleSetExtensions.Get(rgName, vmssName, vmssExtension.Name);
ValidateVmssExtension(vmssExtension, getVmssExtResponse);
// Clear the sequencing in ext3
vmssExtension.ProvisionAfterExtensions.Clear();
var patchVmssExtsResponse = m_CrpClient.VirtualMachineScaleSetExtensions.CreateOrUpdate(rgName, vmssName, vmssExtension.Name, vmssExtension);
ValidateVmssExtension(vmssExtension, patchVmssExtsResponse);
// Perform a List operation on vmss extensions
var listVmssExtsResponse = m_CrpClient.VirtualMachineScaleSetExtensions.List(rgName, vmssName);
int installedExtensionsCount = listVmssExtsResponse.Count();
Assert.Equal(3, installedExtensionsCount);
VirtualMachineScaleSetExtension expectedVmssExt = null;
for (int i = 0; i < installedExtensionsCount; i++)
{
if (i < installedExtensionsCount - 1)
{
expectedVmssExt = vmssExtProfile.Extensions[i];
}
else
{
expectedVmssExt = vmssExtension;
}
ValidateVmssExtension(expectedVmssExt, listVmssExtsResponse.ElementAt(i));
}
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
private VirtualMachineScaleSetExtensionProfile GetTestVmssExtensionProfile()
{
return new VirtualMachineScaleSetExtensionProfile
{
Extensions = new List<VirtualMachineScaleSetExtension>()
{
GetTestVMSSVMExtension(name: "1", publisher: "Microsoft.CPlat.Core", type: "NullSeqA", version: "2.0"),
GetTestVMSSVMExtension(name: "2", publisher: "Microsoft.CPlat.Core", type: "NullSeqB", version: "2.0")
},
ExtensionsTimeBudget = "PT1H20M"
};
}
private void TestVMScaleSetExtensionsImpl(MockContext context)
{
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName,
vmssName,
storageAccountOutput,
imageRef,
out inputVMScaleSet);
// Add an extension to the VMSS
VirtualMachineScaleSetExtension vmssExtension = GetTestVMSSVMExtension(autoUpdateMinorVersion:false);
vmssExtension.ForceUpdateTag = "RerunExtension";
var response = m_CrpClient.VirtualMachineScaleSetExtensions.CreateOrUpdate(rgName, vmssName, vmssExtension.Name, vmssExtension);
ValidateVmssExtension(vmssExtension, response);
// Perform a Get operation on the extension
var getVmssExtResponse = m_CrpClient.VirtualMachineScaleSetExtensions.Get(rgName, vmssName, vmssExtension.Name);
ValidateVmssExtension(vmssExtension, getVmssExtResponse);
// Validate the extension instance view in the VMSS instance-view
var getVmssWithInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
ValidateVmssExtensionInstanceView(getVmssWithInstanceViewResponse.Extensions.FirstOrDefault());
// Update an extension in the VMSS
vmssExtension.Settings = string.Empty;
var patchVmssExtsResponse = m_CrpClient.VirtualMachineScaleSetExtensions.CreateOrUpdate(rgName, vmssName, vmssExtension.Name, vmssExtension);
ValidateVmssExtension(vmssExtension, patchVmssExtsResponse);
// Perform a List operation on vmss extensions
var listVmssExtsResponse = m_CrpClient.VirtualMachineScaleSetExtensions.List(rgName, vmssName);
ValidateVmssExtension(vmssExtension, listVmssExtsResponse.FirstOrDefault(c => c.ForceUpdateTag == "RerunExtension"));
// Validate the extension delete API
m_CrpClient.VirtualMachineScaleSetExtensions.Delete(rgName, vmssName, vmssExtension.Name);
passed = true;
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
Assert.True(passed);
}
protected void ValidateVmssExtension(VirtualMachineScaleSetExtension vmssExtension, VirtualMachineScaleSetExtension vmssExtensionOut)
{
Assert.NotNull(vmssExtensionOut);
Assert.True(!string.IsNullOrEmpty(vmssExtensionOut.ProvisioningState));
Assert.True(vmssExtension.Publisher == vmssExtensionOut.Publisher);
Assert.True(vmssExtension.Type1 == vmssExtensionOut.Type1);
Assert.True(vmssExtension.AutoUpgradeMinorVersion == vmssExtensionOut.AutoUpgradeMinorVersion);
Assert.True(vmssExtension.TypeHandlerVersion == vmssExtensionOut.TypeHandlerVersion);
Assert.True(vmssExtension.Settings.ToString() == vmssExtensionOut.Settings.ToString());
Assert.True(vmssExtension.ForceUpdateTag == vmssExtensionOut.ForceUpdateTag);
if (vmssExtension.ProvisionAfterExtensions != null)
{
Assert.True(vmssExtension.ProvisionAfterExtensions.Count == vmssExtensionOut.ProvisionAfterExtensions.Count);
for (int i = 0; i < vmssExtension.ProvisionAfterExtensions.Count; i++)
{
Assert.True(vmssExtension.ProvisionAfterExtensions[i] == vmssExtensionOut.ProvisionAfterExtensions[i]);
}
}
}
protected void ValidateVmssExtensionInstanceView(VirtualMachineScaleSetVMExtensionsSummary vmssExtSummary)
{
Assert.NotNull(vmssExtSummary);
Assert.NotNull(vmssExtSummary.Name);
Assert.NotNull(vmssExtSummary.StatusesSummary[0].Code);
Assert.NotNull(vmssExtSummary.StatusesSummary[0].Count);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Static methods to serialize and deserialize scene objects to and from XML
/// </summary>
public class SceneXmlLoader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region old xml format
public static void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
XmlDocument doc = new XmlDocument();
XmlNode rootNode;
if (fileName.StartsWith("http:") || File.Exists(fileName))
{
XmlTextReader reader = new XmlTextReader(fileName);
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
rootNode = doc.FirstChild;
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml);
if (newIDS)
{
obj.ResetIDs();
}
//if we want this to be a import method then we need new uuids for the object to avoid any clashes
//obj.RegenerateFullIDs();
scene.AddNewSceneObject(obj, true);
obj.AggregateDeepPerms();
}
}
else
{
throw new Exception("Could not open file " + fileName + " for reading");
}
}
public static void SavePrimsToXml(Scene scene, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
StreamWriter stream = new StreamWriter(file);
int primCount = 0;
stream.WriteLine("<scene>\n");
EntityBase[] entityList = scene.GetEntities();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent));
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Close();
file.Close();
}
#endregion
#region XML2 serialization
// Called by archives (save oar)
public static string SaveGroupToXml2(SceneObjectGroup grp, Dictionary<string, object> options)
{
//return SceneObjectSerializer.ToXml2Format(grp);
using (MemoryStream mem = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mem, System.Text.Encoding.UTF8))
{
SceneObjectSerializer.SOGToXml2(writer, grp, options);
writer.Flush();
using (StreamReader reader = new StreamReader(mem))
{
mem.Seek(0, SeekOrigin.Begin);
return reader.ReadToEnd();
}
}
}
}
// Called by scene serializer (save xml2)
public static void SavePrimsToXml2(Scene scene, string fileName)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, fileName);
}
// Called by scene serializer (save xml2)
public static void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
m_log.InfoFormat(
"[SERIALISER]: Saving prims with name {0} in xml2 format for region {1} to {2}",
primName, scene.RegionInfo.RegionName, fileName);
EntityBase[] entityList = scene.GetEntities();
List<EntityBase> primList = new List<EntityBase>();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
if (ent.Name == primName)
{
primList.Add(ent);
}
}
}
SavePrimListToXml2(primList.ToArray(), fileName);
}
// Called by REST Application plugin
public static void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, stream, min, max);
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
try
{
StreamWriter stream = new StreamWriter(file);
try
{
SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero);
}
finally
{
stream.Close();
}
}
finally
{
file.Close();
}
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, TextWriter stream, Vector3 min, Vector3 max)
{
XmlTextWriter writer = new XmlTextWriter(stream);
int primCount = 0;
stream.WriteLine("<scene>\n");
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup g = (SceneObjectGroup)ent;
if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero))
{
Vector3 pos = g.RootPart.GetWorldPosition();
if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z)
continue;
if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z)
continue;
}
//stream.WriteLine(SceneObjectSerializer.ToXml2Format(g));
SceneObjectSerializer.SOGToXml2(writer, (SceneObjectGroup)ent, new Dictionary<string,object>());
stream.WriteLine();
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Flush();
}
#endregion
#region XML2 deserialization
public static SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
return SceneObjectSerializer.FromXml2Format(xmlString);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="fileName"></param>
public static void LoadPrimsFromXml2(Scene scene, string fileName)
{
LoadPrimsFromXml2(scene, new XmlTextReader(fileName), false);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
public static void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
LoadPrimsFromXml2(scene, new XmlTextReader(reader), startScripts);
}
/// <summary>
/// Load prims from the xml2 format. This method will close the reader
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
protected static void LoadPrimsFromXml2(Scene scene, XmlTextReader reader, bool startScripts)
{
XmlDocument doc = new XmlDocument();
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
XmlNode rootNode = doc.FirstChild;
ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = DeserializeGroupFromXml2(aPrimNode.OuterXml);
scene.AddNewSceneObject(obj, true);
if (startScripts)
sceneObjects.Add(obj);
}
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0);
sceneObject.ResumeScripts();
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// 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.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski 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.
//
namespace NLog.UnitTests.Internal.FileAppenders
{
using System;
using System.IO;
using System.Text;
using Xunit;
using NLog.Targets;
using NLog.Internal.FileAppenders;
public class FileAppenderCacheTests : NLogTestBase
{
[Fact]
public void FileAppenderCache_Empty()
{
FileAppenderCache cache = FileAppenderCache.Empty;
// An empty FileAppenderCache will have Size = 0 as well as Factory and CreateFileParameters parameters equal to null.
Assert.True(cache.Size == 0);
Assert.Null(cache.Factory);
Assert.Null(cache.CreateFileParameters);
}
[Fact]
public void FileAppenderCache_Construction()
{
IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory;
ICreateFileParameters fileTarget = new FileTarget();
FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget);
Assert.True(cache.Size == 3);
Assert.NotNull(cache.Factory);
Assert.NotNull(cache.CreateFileParameters);
}
[Fact]
public void FileAppenderCache_Allocate()
{
// Allocate on an Empty FileAppenderCache.
FileAppenderCache emptyCache = FileAppenderCache.Empty;
Assert.Throws<NullReferenceException>(() => emptyCache.AllocateAppender("file.txt"));
// Construct a on non-empty FileAppenderCache.
IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory;
ICreateFileParameters fileTarget = new FileTarget();
String tempFile = Path.Combine(
Path.GetTempPath(),
Path.Combine(Guid.NewGuid().ToString(), "file.txt")
);
// Allocate an appender.
FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget);
BaseFileAppender appender = cache.AllocateAppender(tempFile);
//
// Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used
// for the file.
//
// Write, flush the content into the file and release the file.
// We need to release the file before invoking AssertFileContents() method.
appender.Write(StringToBytes("NLog test string."));
appender.Flush();
appender.Close();
// Verify the appender has been allocated correctly.
AssertFileContents(tempFile, "NLog test string.", Encoding.Unicode);
}
[Fact]
public void FileAppenderCache_InvalidateAppender()
{
// Invoke InvalidateAppender() on an Empty FileAppenderCache.
FileAppenderCache emptyCache = FileAppenderCache.Empty;
emptyCache.InvalidateAppender("file.txt");
// Construct a on non-empty FileAppenderCache.
IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory;
ICreateFileParameters fileTarget = new FileTarget();
String tempFile = Path.Combine(
Path.GetTempPath(),
Path.Combine(Guid.NewGuid().ToString(), "file.txt")
);
// Allocate an appender.
FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget);
BaseFileAppender appender = cache.AllocateAppender(tempFile);
//
// Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used
// for the file.
//
// Write, flush the content into the file and release the file. This happens throught the
// InvalidateAppender() method. We need to release the file before invoking AssertFileContents() method.
appender.Write(StringToBytes("NLog test string."));
cache.InvalidateAppender(tempFile);
// Verify the appender has been allocated correctly.
AssertFileContents(tempFile, "NLog test string.", Encoding.Unicode);
}
[Fact]
public void FileAppenderCache_CloseAppenders()
{
// Invoke CloseAppenders() on an Empty FileAppenderCache.
FileAppenderCache emptyCache = FileAppenderCache.Empty;
emptyCache.CloseAppenders(string.Empty);
IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory;
ICreateFileParameters fileTarget = new FileTarget();
FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget);
// Invoke CloseAppenders() on non-empty FileAppenderCache - Before allocating any appenders.
cache.CloseAppenders(string.Empty);
// Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders.
cache.AllocateAppender("file1.txt");
cache.AllocateAppender("file2.txt");
cache.CloseAppenders(string.Empty);
// Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders.
cache.AllocateAppender("file1.txt");
cache.AllocateAppender("file2.txt");
cache.CloseAppenders(string.Empty);
FileAppenderCache cache2 = new FileAppenderCache(3, appenderFactory, fileTarget);
// Invoke CloseAppenders() on non-empty FileAppenderCache - Before allocating any appenders.
cache2.CloseAppenders(DateTime.Now);
// Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders.
cache.AllocateAppender("file1.txt");
cache.AllocateAppender("file2.txt");
cache.CloseAppenders(DateTime.Now);
}
[Fact]
public void FileAppenderCache_GetFileCharacteristics_Single()
{
IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory;
ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date };
FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget);
}
[Fact]
public void FileAppenderCache_GetFileCharacteristics_Multi()
{
IFileAppenderFactory appenderFactory = MutexMultiProcessFileAppender.TheFactory;
ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date, ForceManaged = true };
FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget);
}
#if !MONO && !NETSTANDARD
[Fact]
public void FileAppenderCache_GetFileCharacteristics_Windows()
{
if (NLog.Internal.PlatformDetector.IsDesktopWin32)
{
IFileAppenderFactory appenderFactory = WindowsMultiProcessFileAppender.TheFactory;
ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date };
FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget);
}
}
#endif
private void FileAppenderCache_GetFileCharacteristics(IFileAppenderFactory appenderFactory, ICreateFileParameters fileParameters)
{
// Invoke GetFileCharacteristics() on an Empty FileAppenderCache.
FileAppenderCache emptyCache = FileAppenderCache.Empty;
Assert.Null(emptyCache.GetFileCreationTimeSource("file.txt", false));
Assert.Null(emptyCache.GetFileLastWriteTimeUtc("file.txt", false));
Assert.Null(emptyCache.GetFileLength("file.txt", false));
FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileParameters);
// Invoke GetFileCharacteristics() on non-empty FileAppenderCache - Before allocating any appenders.
Assert.Null(emptyCache.GetFileCreationTimeSource("file.txt", false));
Assert.Null(emptyCache.GetFileLastWriteTimeUtc("file.txt", false));
Assert.Null(emptyCache.GetFileLength("file.txt", false));
String tempFile = Path.Combine(
Path.GetTempPath(),
Path.Combine(Guid.NewGuid().ToString(), "file.txt")
);
// Allocate an appender.
BaseFileAppender appender = cache.AllocateAppender(tempFile);
appender.Write(StringToBytes("NLog test string."));
//
// Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used
// for the file.
//
// File information should be returned.
var fileCreationTimeUtc = cache.GetFileCreationTimeSource(tempFile, false);
Assert.NotNull(fileCreationTimeUtc);
Assert.True(fileCreationTimeUtc > Time.TimeSource.Current.FromSystemTime(DateTime.UtcNow.AddMinutes(-2)),"creationtime is wrong");
var fileLastWriteTimeUtc = cache.GetFileLastWriteTimeUtc(tempFile, false);
Assert.NotNull(fileLastWriteTimeUtc);
Assert.True(fileLastWriteTimeUtc > DateTime.UtcNow.AddMinutes(-2), "lastwrite is wrong");
Assert.Equal(34, cache.GetFileLength(tempFile, false));
// Clean up.
appender.Flush();
appender.Close();
}
/// <summary>
/// Converts a string to byte array.
/// </summary>
private static byte[] StringToBytes(string text)
{
byte[] bytes = new byte[sizeof(char) * text.Length];
Buffer.BlockCopy(text.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Runtime.Serialization;
namespace System.Management.Automation
{
/// <summary>
/// The exception thrown if the specified value can not be bound parameter of a command.
/// </summary>
[Serializable]
public class ParameterBindingException : RuntimeException
{
#region Constructors
#region Preferred constructors
/// <summary>
/// Constructs a ParameterBindingException.
/// </summary>
/// <param name="errorCategory">
/// The category for the error.
/// </param>
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
/// <!--
/// InvocationInfo.MyCommand.Name == {0}
/// -->
/// </param>
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
/// If position is null, the one from the InvocationInfo is used.
/// <!--
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// -->
/// </param>
/// <param name="parameterName">
/// The parameter on which binding caused the error.
/// <!--
/// parameterName == {1}
/// -->
/// </param>
/// <param name="parameterType">
/// The Type the parameter was expecting.
/// <!--
/// parameterType == {2}
/// -->
/// </param>
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
/// <!--
/// typeSpecified == {3}
/// -->
/// </param>
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
/// <param name="errorId">
/// The error ID.
/// </param>
/// <param name="args">
/// Additional arguments to pass to the format string.
/// <!--
/// starts at {6}
/// -->
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingException(
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(errorCategory, invocationInfo, errorPosition, errorId, null, null)
{
if (string.IsNullOrEmpty(resourceString))
{
throw PSTraceSource.NewArgumentException(nameof(resourceString));
}
if (string.IsNullOrEmpty(errorId))
{
throw PSTraceSource.NewArgumentException(nameof(errorId));
}
_invocationInfo = invocationInfo;
if (_invocationInfo != null)
{
_commandName = invocationInfo.MyCommand.Name;
}
_parameterName = parameterName;
_parameterType = parameterType;
_typeSpecified = typeSpecified;
if ((errorPosition == null) && (_invocationInfo != null))
{
errorPosition = invocationInfo.ScriptPosition;
}
if (errorPosition != null)
{
_line = errorPosition.StartLineNumber;
_offset = errorPosition.StartColumnNumber;
}
_resourceString = resourceString;
_errorId = errorId;
if (args != null)
{
_args = args;
}
}
/// <summary>
/// Constructs a ParameterBindingException.
/// </summary>
/// <param name="innerException">
/// The inner exception.
/// </param>
/// <param name="errorCategory">
/// The category for the error.
/// </param>
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
/// If position is null, the one from the InvocationInfo is used.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
/// <param name="errorId">
/// The error ID.
/// </param>
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="invocationInfo"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingException(
Exception innerException,
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(errorCategory, invocationInfo, errorPosition, errorId, null, innerException)
{
if (invocationInfo == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(invocationInfo));
}
if (string.IsNullOrEmpty(resourceString))
{
throw PSTraceSource.NewArgumentException(nameof(resourceString));
}
if (string.IsNullOrEmpty(errorId))
{
throw PSTraceSource.NewArgumentException(nameof(errorId));
}
_invocationInfo = invocationInfo;
_commandName = invocationInfo.MyCommand.Name;
_parameterName = parameterName;
_parameterType = parameterType;
_typeSpecified = typeSpecified;
if (errorPosition == null)
{
errorPosition = invocationInfo.ScriptPosition;
}
if (errorPosition != null)
{
_line = errorPosition.StartLineNumber;
_offset = errorPosition.StartColumnNumber;
}
_resourceString = resourceString;
_errorId = errorId;
if (args != null)
{
_args = args;
}
}
/// <summary>
/// </summary>
/// <param name="innerException"></param>
/// <param name="pbex"></param>
/// <param name="resourceString"></param>
/// <param name="args"></param>
internal ParameterBindingException(
Exception innerException,
ParameterBindingException pbex,
string resourceString,
params object[] args)
: base(string.Empty, innerException)
{
if (pbex == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(pbex));
}
if (string.IsNullOrEmpty(resourceString))
{
throw PSTraceSource.NewArgumentException(nameof(resourceString));
}
_invocationInfo = pbex.CommandInvocation;
if (_invocationInfo != null)
{
_commandName = _invocationInfo.MyCommand.Name;
}
IScriptExtent errorPosition = null;
if (_invocationInfo != null)
{
errorPosition = _invocationInfo.ScriptPosition;
}
_line = pbex.Line;
_offset = pbex.Offset;
_parameterName = pbex.ParameterName;
_parameterType = pbex.ParameterType;
_typeSpecified = pbex.TypeSpecified;
_errorId = pbex.ErrorId;
_resourceString = resourceString;
if (args != null)
{
_args = args;
}
base.SetErrorCategory(pbex.ErrorRecord._category);
base.SetErrorId(_errorId);
if (_invocationInfo != null)
{
base.ErrorRecord.SetInvocationInfo(new InvocationInfo(_invocationInfo.MyCommand, errorPosition));
}
}
#endregion Preferred constructors
#region serialization
/// <summary>
/// Constructors a ParameterBindingException using serialized data.
/// </summary>
/// <param name="info">
/// serialization information
/// </param>
/// <param name="context">
/// streaming context
/// </param>
protected ParameterBindingException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
_message = info.GetString("ParameterBindingException_Message");
_parameterName = info.GetString("ParameterName");
_line = info.GetInt64("Line");
_offset = info.GetInt64("Offset");
}
/// <summary>
/// Serializes the exception.
/// </summary>
/// <param name="info">
/// serialization information
/// </param>
/// <param name="context">
/// streaming context
/// </param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new PSArgumentNullException(nameof(info));
}
base.GetObjectData(info, context);
info.AddValue("ParameterBindingException_Message", this.Message);
info.AddValue("ParameterName", _parameterName);
info.AddValue("Line", _line);
info.AddValue("Offset", _offset);
}
#endregion serialization
#region Do Not Use
/// <summary>
/// Constructs a ParameterBindingException.
/// </summary>
/// <remarks>
/// DO NOT USE!!!
/// </remarks>
public ParameterBindingException() : base() { }
/// <summary>
/// Constructors a ParameterBindingException.
/// </summary>
/// <param name="message">
/// Message to be included in exception.
/// </param>
/// <remarks>
/// DO NOT USE!!!
/// </remarks>
public ParameterBindingException(string message) : base(message) { _message = message; }
/// <summary>
/// Constructs a ParameterBindingException.
/// </summary>
/// <param name="message">
/// Message to be included in the exception.
/// </param>
/// <param name="innerException">
/// exception that led to this exception
/// </param>
/// <remarks>
/// DO NOT USE!!!
/// </remarks>
public ParameterBindingException(
string message,
Exception innerException)
: base(message, innerException)
{ _message = message; }
#endregion Do Not Use
#endregion Constructors
#region Properties
/// <summary>
/// Gets the message for the exception.
/// </summary>
public override string Message
{
get { return _message ??= BuildMessage(); }
}
private string _message;
/// <summary>
/// Gets the name of the parameter that the parameter binding
/// error was encountered on.
/// </summary>
public string ParameterName
{
get
{
return _parameterName;
}
}
private readonly string _parameterName = string.Empty;
/// <summary>
/// Gets the type the parameter is expecting.
/// </summary>
public Type ParameterType
{
get
{
return _parameterType;
}
}
private readonly Type _parameterType;
/// <summary>
/// Gets the Type that was specified as the parameter value.
/// </summary>
public Type TypeSpecified
{
get
{
return _typeSpecified;
}
}
private readonly Type _typeSpecified;
/// <summary>
/// Gets the errorId of this ParameterBindingException.
/// </summary>
public string ErrorId
{
get
{
return _errorId;
}
}
private readonly string _errorId;
/// <summary>
/// Gets the line in the script at which the error occurred.
/// </summary>
public Int64 Line
{
get
{
return _line;
}
}
private readonly Int64 _line = Int64.MinValue;
/// <summary>
/// Gets the offset on the line in the script at which the error occurred.
/// </summary>
public Int64 Offset
{
get
{
return _offset;
}
}
private readonly Int64 _offset = Int64.MinValue;
/// <summary>
/// Gets the invocation information about the command.
/// </summary>
public InvocationInfo CommandInvocation
{
get
{
return _invocationInfo;
}
}
private readonly InvocationInfo _invocationInfo;
#endregion Properties
#region private
private readonly string _resourceString;
private readonly object[] _args = Array.Empty<object>();
private readonly string _commandName;
private string BuildMessage()
{
object[] messageArgs = Array.Empty<object>();
if (_args != null)
{
messageArgs = new object[_args.Length + 6];
messageArgs[0] = _commandName;
messageArgs[1] = _parameterName;
messageArgs[2] = _parameterType;
messageArgs[3] = _typeSpecified;
messageArgs[4] = _line;
messageArgs[5] = _offset;
_args.CopyTo(messageArgs, 6);
}
string result = string.Empty;
if (!string.IsNullOrEmpty(_resourceString))
{
result = StringUtil.Format(_resourceString, messageArgs);
}
return result;
}
#endregion Private
}
[Serializable]
internal class ParameterBindingValidationException : ParameterBindingException
{
#region Preferred constructors
/// <summary>
/// Constructs a ParameterBindingValidationException.
/// </summary>
/// <param name="errorCategory">
/// The category for the error.
/// </param>
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
/// <param name="errorId">
/// The error ID.
/// </param>
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingValidationException(
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
/// <summary>
/// Constructs a ParameterBindingValidationException.
/// </summary>
/// <param name="innerException">
/// The inner exception.
/// </param>
/// <param name="errorCategory">
/// The category for the error.
/// </param>
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
/// <param name="errorId">
/// The error ID.
/// </param>
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="invocationInfo"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="resourceBaseName"/> or <paramref name="errorIdAndResourceId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingValidationException(
Exception innerException,
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
innerException,
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
ValidationMetadataException validationException = innerException as ValidationMetadataException;
if (validationException != null && validationException.SwallowException)
{
_swallowException = true;
}
}
#endregion Preferred constructors
#region serialization
/// <summary>
/// Constructs a ParameterBindingValidationException from serialized data.
/// </summary>
/// <param name="info">
/// serialization information
/// </param>
/// <param name="context">
/// streaming context
/// </param>
protected ParameterBindingValidationException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion serialization
#region Property
/// <summary>
/// Make the positional binding ignore this validation exception when it's set to true.
/// </summary>
/// <remarks>
/// This property is only used internally in the positional binding phase
/// </remarks>
internal bool SwallowException
{
get { return _swallowException; }
}
private readonly bool _swallowException = false;
#endregion Property
}
[Serializable]
internal class ParameterBindingArgumentTransformationException : ParameterBindingException
{
#region Preferred constructors
/// <summary>
/// Constructs a ParameterBindingArgumentTransformationException.
/// </summary>
/// <param name="errorCategory">
/// The category for the error.
/// </param>
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
/// <param name="errorId">
/// The error ID.
/// </param>
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingArgumentTransformationException(
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
/// <summary>
/// Constructs a ParameterBindingArgumentTransformationException.
/// </summary>
/// <param name="innerException">
/// The inner exception.
/// </param>
/// <param name="errorCategory">
/// The category for the error.
/// </param>
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
/// <param name="errorId">
/// The error ID.
/// </param>
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="invocationInfo"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingArgumentTransformationException(
Exception innerException,
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
innerException,
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
#endregion Preferred constructors
#region serialization
/// <summary>
/// Constructs a ParameterBindingArgumentTransformationException using serialized data.
/// </summary>
/// <param name="info">
/// serialization information
/// </param>
/// <param name="context">
/// streaming context
/// </param>
protected ParameterBindingArgumentTransformationException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion serialization
}
[Serializable]
internal class ParameterBindingParameterDefaultValueException : ParameterBindingException
{
#region Preferred constructors
/// <summary>
/// Constructs a ParameterBindingParameterDefaultValueException.
/// </summary>
/// <param name="errorCategory">
/// The category for the error.
/// </param>
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
/// <param name="errorId">
/// The error ID.
/// </param>
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingParameterDefaultValueException(
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
/// <summary>
/// Constructs a ParameterBindingParameterDefaultValueException.
/// </summary>
/// <param name="innerException">
/// The inner exception.
/// </param>
/// <param name="errorCategory">
/// The category for the error.
/// </param>
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
/// <param name="errorId">
/// The error ID.
/// </param>
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="invocationInfo"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingParameterDefaultValueException(
Exception innerException,
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
innerException,
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
#endregion Preferred constructors
#region serialization
/// <summary>
/// Constructs a ParameterBindingParameterDefaultValueException using serialized data.
/// </summary>
/// <param name="info">
/// serialization information
/// </param>
/// <param name="context">
/// streaming context
/// </param>
protected ParameterBindingParameterDefaultValueException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion serialization
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace OpenTK
{
/// <summary>
/// 3-component Vector of the Half type. Occupies 6 Byte total.
/// </summary>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Vector3h : ISerializable, IEquatable<Vector3h>
{
#region Public Fields
/// <summary>The X component of the Half3.</summary>
public Half X;
/// <summary>The Y component of the Half3.</summary>
public Half Y;
/// <summary>The Z component of the Half3.</summary>
public Half Z;
#endregion Public Fields
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector3h(Half value)
{
X = value;
Y = value;
Z = value;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector3h(Single value)
{
X = new Half(value);
Y = new Half(value);
Z = new Half(value);
}
/// <summary>
/// The new Half3 instance will avoid conversion and copy directly from the Half parameters.
/// </summary>
/// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="z">An Half instance of a 16-bit half-precision floating-point number.</param>
public Vector3h(Half x, Half y, Half z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
/// <summary>
/// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
public Vector3h(Single x, Single y, Single z)
{
X = new Half(x);
Y = new Half(y);
Z = new Half(z);
}
/// <summary>
/// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector3h(Single x, Single y, Single z, bool throwOnError)
{
X = new Half(x, throwOnError);
Y = new Half(y, throwOnError);
Z = new Half(z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
[CLSCompliant(false)]
public Vector3h(Vector3 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(Vector3 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// This is the fastest constructor.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
public Vector3h(ref Vector3 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
[CLSCompliant(false)]
public Vector3h(Vector3d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(Vector3d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// This is the faster constructor.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
#endregion Constructors
#region Swizzle
#region 2-component
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xy { get { return new Vector2h(X, Y); } set { X = value.X; Y = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xz { get { return new Vector2h(X, Z); } set { X = value.X; Z = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yx { get { return new Vector2h(Y, X); } set { Y = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yz { get { return new Vector2h(Y, Z); } set { Y = value.X; Z = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Z and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zx { get { return new Vector2h(Z, X); } set { Z = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Z and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zy { get { return new Vector2h(Z, Y); } set { Z = value.X; Y = value.Y; } }
#endregion
#region 3-component
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, Z, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xzy { get { return new Vector3h(X, Z, Y); } set { X = value.X; Z = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, X, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yxz { get { return new Vector3h(Y, X, Z); } set { Y = value.X; X = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, Z, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yzx { get { return new Vector3h(Y, Z, X); } set { Y = value.X; Z = value.Y; X = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, X, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zxy { get { return new Vector3h(Z, X, Y); } set { Z = value.X; X = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, Y, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zyx { get { return new Vector3h(Z, Y, X); } set { Z = value.X; Y = value.Y; X = value.Z; } }
#endregion
#endregion
#region Half -> Single
/// <summary>
/// Returns this Half3 instance's contents as Vector3.
/// </summary>
/// <returns>OpenTK.Vector3</returns>
public Vector3 ToVector3()
{
return new Vector3(X, Y, Z);
}
/// <summary>
/// Returns this Half3 instance's contents as Vector3d.
/// </summary>
public Vector3d ToVector3d()
{
return new Vector3d(X, Y, Z);
}
#endregion Half -> Single
#region Conversions
/// <summary>Converts OpenTK.Vector3 to OpenTK.Half3.</summary>
/// <param name="v3f">The Vector3 to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector3h(Vector3 v3f)
{
return new Vector3h(v3f);
}
/// <summary>Converts OpenTK.Vector3d to OpenTK.Half3.</summary>
/// <param name="v3d">The Vector3d to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector3h(Vector3d v3d)
{
return new Vector3h(v3d);
}
/// <summary>Converts OpenTK.Half3 to OpenTK.Vector3.</summary>
/// <param name="h3">The Half3 to convert.</param>
/// <returns>The resulting Vector3.</returns>
public static explicit operator Vector3(Vector3h h3)
{
Vector3 result = new Vector3();
result.X = h3.X.ToSingle();
result.Y = h3.Y.ToSingle();
result.Z = h3.Z.ToSingle();
return result;
}
/// <summary>Converts OpenTK.Half3 to OpenTK.Vector3d.</summary>
/// <param name="h3">The Half3 to convert.</param>
/// <returns>The resulting Vector3d.</returns>
public static explicit operator Vector3d(Vector3h h3)
{
Vector3d result = new Vector3d();
result.X = h3.X.ToSingle();
result.Y = h3.Y.ToSingle();
result.Z = h3.Z.ToSingle();
return result;
}
#endregion Conversions
#region Constants
/// <summary>The size in bytes for an instance of the Half3 struct is 6.</summary>
public static readonly int SizeInBytes = 6;
#endregion Constants
#region ISerializable
/// <summary>Constructor used by ISerializable to deserialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public Vector3h(SerializationInfo info, StreamingContext context)
{
this.X = (Half)info.GetValue("X", typeof(Half));
this.Y = (Half)info.GetValue("Y", typeof(Half));
this.Z = (Half)info.GetValue("Z", typeof(Half));
}
/// <summary>Used by ISerialize to serialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("X", this.X);
info.AddValue("Y", this.Y);
info.AddValue("Z", this.Z);
}
#endregion ISerializable
#region Binary dump
/// <summary>Updates the X,Y and Z components of this instance by reading from a Stream.</summary>
/// <param name="bin">A BinaryReader instance associated with an open Stream.</param>
public void FromBinaryStream(BinaryReader bin)
{
X.FromBinaryStream(bin);
Y.FromBinaryStream(bin);
Z.FromBinaryStream(bin);
}
/// <summary>Writes the X,Y and Z components of this instance into a Stream.</summary>
/// <param name="bin">A BinaryWriter instance associated with an open Stream.</param>
public void ToBinaryStream(BinaryWriter bin)
{
X.ToBinaryStream(bin);
Y.ToBinaryStream(bin);
Z.ToBinaryStream(bin);
}
#endregion Binary dump
#region IEquatable<Half3> Members
/// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half3 vector.</summary>
/// <param name="other">OpenTK.Half3 to compare to this instance..</param>
/// <returns>True, if other is equal to this instance; false otherwise.</returns>
public bool Equals(Vector3h other)
{
return (this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z));
}
#endregion
#region ToString()
private static string listSeparator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
/// <summary>Returns a string that contains this Half3's numbers in human-legible form.</summary>
public override string ToString()
{
return String.Format("({0}{3} {1}{3} {2})", X.ToString(), Y.ToString(), Z.ToString(), listSeparator);
}
#endregion ToString()
#region BitConverter
/// <summary>Returns the Half3 as an array of bytes.</summary>
/// <param name="h">The Half3 to convert.</param>
/// <returns>The input as byte array.</returns>
public static byte[] GetBytes(Vector3h h)
{
byte[] result = new byte[SizeInBytes];
byte[] temp = Half.GetBytes(h.X);
result[0] = temp[0];
result[1] = temp[1];
temp = Half.GetBytes(h.Y);
result[2] = temp[0];
result[3] = temp[1];
temp = Half.GetBytes(h.Z);
result[4] = temp[0];
result[5] = temp[1];
return result;
}
/// <summary>Converts an array of bytes into Half3.</summary>
/// <param name="value">A Half3 in it's byte[] representation.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A new Half3 instance.</returns>
public static Vector3h FromBytes(byte[] value, int startIndex)
{
Vector3h h3 = new Vector3h();
h3.X = Half.FromBytes(value, startIndex);
h3.Y = Half.FromBytes(value, startIndex + 2);
h3.Z = Half.FromBytes(value, startIndex + 4);
return h3;
}
#endregion BitConverter
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedRegionBackendServicesClientSnippets
{
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteRegionBackendServiceRequest, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
DeleteRegionBackendServiceRequest request = new DeleteRegionBackendServiceRequest
{
RequestId = "",
Region = "",
Project = "",
BackendService = "",
};
// Make the request
lro::Operation<Operation, Operation> response = regionBackendServicesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionBackendServicesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteRegionBackendServiceRequest, CallSettings)
// Additional: DeleteAsync(DeleteRegionBackendServiceRequest, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
DeleteRegionBackendServiceRequest request = new DeleteRegionBackendServiceRequest
{
RequestId = "",
Region = "",
Project = "",
BackendService = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await regionBackendServicesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionBackendServicesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, string, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
// Make the request
lro::Operation<Operation, Operation> response = regionBackendServicesClient.Delete(project, region, backendService);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionBackendServicesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, string, CallSettings)
// Additional: DeleteAsync(string, string, string, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
// Make the request
lro::Operation<Operation, Operation> response = await regionBackendServicesClient.DeleteAsync(project, region, backendService);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionBackendServicesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetRegionBackendServiceRequest, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
GetRegionBackendServiceRequest request = new GetRegionBackendServiceRequest
{
Region = "",
Project = "",
BackendService = "",
};
// Make the request
BackendService response = regionBackendServicesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetRegionBackendServiceRequest, CallSettings)
// Additional: GetAsync(GetRegionBackendServiceRequest, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
GetRegionBackendServiceRequest request = new GetRegionBackendServiceRequest
{
Region = "",
Project = "",
BackendService = "",
};
// Make the request
BackendService response = await regionBackendServicesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, string, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
// Make the request
BackendService response = regionBackendServicesClient.Get(project, region, backendService);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, string, CallSettings)
// Additional: GetAsync(string, string, string, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
// Make the request
BackendService response = await regionBackendServicesClient.GetAsync(project, region, backendService);
// End snippet
}
/// <summary>Snippet for GetHealth</summary>
public void GetHealthRequestObject()
{
// Snippet: GetHealth(GetHealthRegionBackendServiceRequest, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
GetHealthRegionBackendServiceRequest request = new GetHealthRegionBackendServiceRequest
{
ResourceGroupReferenceResource = new ResourceGroupReference(),
Region = "",
Project = "",
BackendService = "",
};
// Make the request
BackendServiceGroupHealth response = regionBackendServicesClient.GetHealth(request);
// End snippet
}
/// <summary>Snippet for GetHealthAsync</summary>
public async Task GetHealthRequestObjectAsync()
{
// Snippet: GetHealthAsync(GetHealthRegionBackendServiceRequest, CallSettings)
// Additional: GetHealthAsync(GetHealthRegionBackendServiceRequest, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
GetHealthRegionBackendServiceRequest request = new GetHealthRegionBackendServiceRequest
{
ResourceGroupReferenceResource = new ResourceGroupReference(),
Region = "",
Project = "",
BackendService = "",
};
// Make the request
BackendServiceGroupHealth response = await regionBackendServicesClient.GetHealthAsync(request);
// End snippet
}
/// <summary>Snippet for GetHealth</summary>
public void GetHealth()
{
// Snippet: GetHealth(string, string, string, ResourceGroupReference, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
ResourceGroupReference resourceGroupReferenceResource = new ResourceGroupReference();
// Make the request
BackendServiceGroupHealth response = regionBackendServicesClient.GetHealth(project, region, backendService, resourceGroupReferenceResource);
// End snippet
}
/// <summary>Snippet for GetHealthAsync</summary>
public async Task GetHealthAsync()
{
// Snippet: GetHealthAsync(string, string, string, ResourceGroupReference, CallSettings)
// Additional: GetHealthAsync(string, string, string, ResourceGroupReference, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
ResourceGroupReference resourceGroupReferenceResource = new ResourceGroupReference();
// Make the request
BackendServiceGroupHealth response = await regionBackendServicesClient.GetHealthAsync(project, region, backendService, resourceGroupReferenceResource);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertRegionBackendServiceRequest, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
InsertRegionBackendServiceRequest request = new InsertRegionBackendServiceRequest
{
RequestId = "",
Region = "",
Project = "",
BackendServiceResource = new BackendService(),
};
// Make the request
lro::Operation<Operation, Operation> response = regionBackendServicesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionBackendServicesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertRegionBackendServiceRequest, CallSettings)
// Additional: InsertAsync(InsertRegionBackendServiceRequest, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
InsertRegionBackendServiceRequest request = new InsertRegionBackendServiceRequest
{
RequestId = "",
Region = "",
Project = "",
BackendServiceResource = new BackendService(),
};
// Make the request
lro::Operation<Operation, Operation> response = await regionBackendServicesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionBackendServicesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, string, BackendService, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
BackendService backendServiceResource = new BackendService();
// Make the request
lro::Operation<Operation, Operation> response = regionBackendServicesClient.Insert(project, region, backendServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionBackendServicesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, string, BackendService, CallSettings)
// Additional: InsertAsync(string, string, BackendService, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
BackendService backendServiceResource = new BackendService();
// Make the request
lro::Operation<Operation, Operation> response = await regionBackendServicesClient.InsertAsync(project, region, backendServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionBackendServicesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListRegionBackendServicesRequest, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
ListRegionBackendServicesRequest request = new ListRegionBackendServicesRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<BackendServiceList, BackendService> response = regionBackendServicesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (BackendService item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (BackendServiceList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (BackendService item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<BackendService> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (BackendService item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListRegionBackendServicesRequest, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
ListRegionBackendServicesRequest request = new ListRegionBackendServicesRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<BackendServiceList, BackendService> response = regionBackendServicesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((BackendService item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((BackendServiceList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (BackendService item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<BackendService> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (BackendService item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, string, int?, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedEnumerable<BackendServiceList, BackendService> response = regionBackendServicesClient.List(project, region);
// Iterate over all response items, lazily performing RPCs as required
foreach (BackendService item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (BackendServiceList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (BackendService item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<BackendService> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (BackendService item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, string, int?, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedAsyncEnumerable<BackendServiceList, BackendService> response = regionBackendServicesClient.ListAsync(project, region);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((BackendService item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((BackendServiceList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (BackendService item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<BackendService> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (BackendService item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void PatchRequestObject()
{
// Snippet: Patch(PatchRegionBackendServiceRequest, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
PatchRegionBackendServiceRequest request = new PatchRegionBackendServiceRequest
{
RequestId = "",
Region = "",
Project = "",
BackendService = "",
BackendServiceResource = new BackendService(),
};
// Make the request
lro::Operation<Operation, Operation> response = regionBackendServicesClient.Patch(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionBackendServicesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchRequestObjectAsync()
{
// Snippet: PatchAsync(PatchRegionBackendServiceRequest, CallSettings)
// Additional: PatchAsync(PatchRegionBackendServiceRequest, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
PatchRegionBackendServiceRequest request = new PatchRegionBackendServiceRequest
{
RequestId = "",
Region = "",
Project = "",
BackendService = "",
BackendServiceResource = new BackendService(),
};
// Make the request
lro::Operation<Operation, Operation> response = await regionBackendServicesClient.PatchAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionBackendServicesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void Patch()
{
// Snippet: Patch(string, string, string, BackendService, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
BackendService backendServiceResource = new BackendService();
// Make the request
lro::Operation<Operation, Operation> response = regionBackendServicesClient.Patch(project, region, backendService, backendServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionBackendServicesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchAsync()
{
// Snippet: PatchAsync(string, string, string, BackendService, CallSettings)
// Additional: PatchAsync(string, string, string, BackendService, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
BackendService backendServiceResource = new BackendService();
// Make the request
lro::Operation<Operation, Operation> response = await regionBackendServicesClient.PatchAsync(project, region, backendService, backendServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionBackendServicesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Update</summary>
public void UpdateRequestObject()
{
// Snippet: Update(UpdateRegionBackendServiceRequest, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
UpdateRegionBackendServiceRequest request = new UpdateRegionBackendServiceRequest
{
RequestId = "",
Region = "",
Project = "",
BackendService = "",
BackendServiceResource = new BackendService(),
};
// Make the request
lro::Operation<Operation, Operation> response = regionBackendServicesClient.Update(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionBackendServicesClient.PollOnceUpdate(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateAsync</summary>
public async Task UpdateRequestObjectAsync()
{
// Snippet: UpdateAsync(UpdateRegionBackendServiceRequest, CallSettings)
// Additional: UpdateAsync(UpdateRegionBackendServiceRequest, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
UpdateRegionBackendServiceRequest request = new UpdateRegionBackendServiceRequest
{
RequestId = "",
Region = "",
Project = "",
BackendService = "",
BackendServiceResource = new BackendService(),
};
// Make the request
lro::Operation<Operation, Operation> response = await regionBackendServicesClient.UpdateAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionBackendServicesClient.PollOnceUpdateAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Update</summary>
public void Update()
{
// Snippet: Update(string, string, string, BackendService, CallSettings)
// Create client
RegionBackendServicesClient regionBackendServicesClient = RegionBackendServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
BackendService backendServiceResource = new BackendService();
// Make the request
lro::Operation<Operation, Operation> response = regionBackendServicesClient.Update(project, region, backendService, backendServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionBackendServicesClient.PollOnceUpdate(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateAsync</summary>
public async Task UpdateAsync()
{
// Snippet: UpdateAsync(string, string, string, BackendService, CallSettings)
// Additional: UpdateAsync(string, string, string, BackendService, CancellationToken)
// Create client
RegionBackendServicesClient regionBackendServicesClient = await RegionBackendServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string backendService = "";
BackendService backendServiceResource = new BackendService();
// Make the request
lro::Operation<Operation, Operation> response = await regionBackendServicesClient.UpdateAsync(project, region, backendService, backendServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionBackendServicesClient.PollOnceUpdateAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Clr.NativeCompilation;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class DkmUtilities
{
internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize);
// Return the set of managed module instances from the AppDomain.
private static IEnumerable<DkmClrModuleInstance> GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain)
{
if (appDomain.IsUnloaded)
{
return SpecializedCollections.EmptyEnumerable<DkmClrModuleInstance>();
}
var appDomainId = appDomain.Id;
// GetModuleInstances() may include instances of DkmClrNcContainerModuleInstance
// which are containers of managed module instances (see GetEmbeddedModules())
// but not managed modules themselves. Since GetModuleInstances() will include the
// embedded modules, we can simply ignore DkmClrNcContainerModuleInstances.
return runtime.GetModuleInstances().
OfType<DkmClrModuleInstance>().
Where(module =>
{
var moduleAppDomain = module.AppDomain;
return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId);
});
}
internal unsafe static ImmutableArray<MetadataBlock> GetMetadataBlocks(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain)
{
var builder = ArrayBuilder<MetadataBlock>.GetInstance();
IntPtr ptr;
uint size;
foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain))
{
MetadataBlock block;
try
{
ptr = module.GetMetaDataBytesPtr(out size);
Debug.Assert(size > 0);
block = GetMetadataBlock(ptr, size);
}
catch (NotImplementedException e) when (module is DkmClrNcModuleInstance)
{
// DkmClrNcModuleInstance.GetMetaDataBytesPtr not implemented in Dev14.
throw new NotImplementedMetadataException(e);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, module.FullName))
{
continue;
}
Debug.Assert(block.ModuleVersionId == module.Mvid);
builder.Add(block);
}
// Include "intrinsic method" assembly.
ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size);
builder.Add(GetMetadataBlock(ptr, size));
return builder.ToImmutableAndFree();
}
internal static ImmutableArray<MetadataBlock> GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities)
{
ArrayBuilder<MetadataBlock> builder = null;
foreach (AssemblyIdentity missingAssemblyIdentity in missingAssemblyIdentities)
{
MetadataBlock block;
try
{
uint size;
IntPtr ptr;
ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size);
Debug.Assert(size > 0);
block = GetMetadataBlock(ptr, size);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, missingAssemblyIdentity.GetDisplayName()))
{
continue;
}
if (builder == null)
{
builder = ArrayBuilder<MetadataBlock>.GetInstance();
}
builder.Add(block);
}
return builder == null ? ImmutableArray<MetadataBlock>.Empty : builder.ToImmutableAndFree();
}
internal static ImmutableArray<AssemblyReaders> MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress)
{
var builder = ArrayBuilder<AssemblyReaders>.GetInstance();
foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain))
{
var symReader = module.GetSymReader();
if (symReader == null)
{
continue;
}
MetadataReader reader;
unsafe
{
try
{
uint size;
IntPtr ptr;
ptr = module.GetMetaDataBytesPtr(out size);
Debug.Assert(size > 0);
reader = new MetadataReader((byte*)ptr, (int)size);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, module.FullName))
{
continue;
}
}
builder.Add(new AssemblyReaders(reader, symReader));
}
return builder.ToImmutableAndFree();
}
private unsafe static MetadataBlock GetMetadataBlock(IntPtr ptr, uint size)
{
var reader = new MetadataReader((byte*)ptr, (int)size);
var moduleDef = reader.GetModuleDefinition();
var moduleVersionId = reader.GetGuid(moduleDef.Mvid);
var generationId = reader.GetGuid(moduleDef.GenerationId);
return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size);
}
internal static object GetSymReader(this DkmClrModuleInstance clrModule)
{
var module = clrModule.Module; // Null if there are no symbols.
if (module == null)
{
return null;
}
// Use DkmClrModuleInstance.GetSymUnmanagedReader()
// rather than DkmModule.GetSymbolInterface() since the
// latter does not handle .NET Native modules.
return clrModule.GetSymUnmanagedReader();
}
internal static DkmCompiledClrInspectionQuery ToQueryResult(
this CompileResult compResult,
DkmCompilerId languageId,
ResultProperties resultProperties,
DkmClrRuntimeInstance runtimeInstance)
{
if (compResult == null)
{
return null;
}
Debug.Assert(compResult.Assembly != null);
Debug.Assert(compResult.TypeName != null);
Debug.Assert(compResult.MethodName != null);
ReadOnlyCollection<byte> customTypeInfo;
Guid customTypeInfoId = compResult.GetCustomTypeInfo(out customTypeInfo);
return DkmCompiledClrInspectionQuery.Create(
runtimeInstance,
Binary: new ReadOnlyCollection<byte>(compResult.Assembly),
DataContainer: null,
LanguageId: languageId,
TypeName: compResult.TypeName,
MethodName: compResult.MethodName,
FormatSpecifiers: compResult.FormatSpecifiers,
CompilationFlags: resultProperties.Flags,
ResultCategory: resultProperties.Category,
Access: resultProperties.AccessType,
StorageType: resultProperties.StorageType,
TypeModifierFlags: resultProperties.ModifierFlags,
CustomTypeInfo: customTypeInfo.ToCustomTypeInfo(customTypeInfoId));
}
internal static DkmClrCustomTypeInfo ToCustomTypeInfo(this ReadOnlyCollection<byte> payload, Guid payloadTypeId)
{
return (payload == null) ? null : DkmClrCustomTypeInfo.Create(payloadTypeId, payload);
}
internal static ResultProperties GetResultProperties<TSymbol>(this TSymbol symbol, DkmClrCompilationResultFlags flags, bool isConstant)
where TSymbol : ISymbol
{
var haveSymbol = symbol != null;
var category = haveSymbol
? GetResultCategory(symbol.Kind)
: DkmEvaluationResultCategory.Data;
var accessType = haveSymbol
? GetResultAccessType(symbol.DeclaredAccessibility)
: DkmEvaluationResultAccessType.None;
var storageType = haveSymbol && symbol.IsStatic
? DkmEvaluationResultStorageType.Static
: DkmEvaluationResultStorageType.None;
var modifierFlags = DkmEvaluationResultTypeModifierFlags.None;
if (isConstant)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant;
}
else if (!haveSymbol)
{
// No change.
}
else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual;
}
else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsVolatile)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile;
}
// CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)]
// and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any
// impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either.
return new ResultProperties(flags, category, accessType, storageType, modifierFlags);
}
private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind)
{
switch (kind)
{
case SymbolKind.Method:
return DkmEvaluationResultCategory.Method;
case SymbolKind.Property:
return DkmEvaluationResultCategory.Property;
default:
return DkmEvaluationResultCategory.Data;
}
}
private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility)
{
switch (accessibility)
{
case Accessibility.Public:
return DkmEvaluationResultAccessType.Public;
case Accessibility.Protected:
return DkmEvaluationResultAccessType.Protected;
case Accessibility.Private:
return DkmEvaluationResultAccessType.Private;
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal: // Dev12 treats this as "internal"
case Accessibility.ProtectedAndInternal: // Dev12 treats this as "internal"
return DkmEvaluationResultAccessType.Internal;
case Accessibility.NotApplicable:
return DkmEvaluationResultAccessType.None;
default:
throw ExceptionUtilities.UnexpectedValue(accessibility);
}
}
internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired)
{
return (flags & desired) == desired;
}
internal static TMetadataContext GetMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain)
where TMetadataContext : struct
{
var dataItem = appDomain.GetDataItem<MetadataContextItem<TMetadataContext>>();
return (dataItem == null) ? default(TMetadataContext) : dataItem.MetadataContext;
}
internal static void SetMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain, TMetadataContext context)
where TMetadataContext : struct
{
appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem<TMetadataContext>(context));
}
internal static void RemoveMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain)
where TMetadataContext : struct
{
appDomain.RemoveDataItem<MetadataContextItem<TMetadataContext>>();
}
private sealed class MetadataContextItem<TMetadataContext> : DkmDataItem
where TMetadataContext : struct
{
internal readonly TMetadataContext MetadataContext;
internal MetadataContextItem(TMetadataContext metadataContext)
{
this.MetadataContext = metadataContext;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using Microsoft.VisualStudio.Text;
using NuGet;
namespace NuGetConsole.Implementation.Console
{
internal interface IPrivateConsoleDispatcher : IConsoleDispatcher, IDisposable
{
event EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> ExecuteInputLine;
void PostInputLine(InputLine inputLine);
void PostKey(VsKeyInfo key);
void CancelWaitKey();
}
/// <summary>
/// This class handles input line posting and command line dispatching/execution.
/// </summary>
internal class ConsoleDispatcher : IPrivateConsoleDispatcher
{
private readonly BlockingCollection<VsKeyInfo> _keyBuffer = new BlockingCollection<VsKeyInfo>();
private CancellationTokenSource _cancelWaitKeySource;
private bool _isExecutingReadKey;
/// <summary>
/// The IPrivateWpfConsole instance this dispatcher works with.
/// </summary>
private IPrivateWpfConsole WpfConsole { get; set; }
/// <summary>
/// Child dispatcher based on host type. Its creation is postponed to Start(), so that
/// a WpfConsole's dispatcher can be accessed while inside a host construction.
/// </summary>
private Dispatcher _dispatcher;
private readonly object _lockObj = new object();
public event EventHandler StartCompleted;
public event EventHandler StartWaitingKey;
public ConsoleDispatcher(IPrivateWpfConsole wpfConsole)
{
UtilityMethods.ThrowIfArgumentNull(wpfConsole);
this.WpfConsole = wpfConsole;
}
public bool IsExecutingCommand
{
get
{
return (_dispatcher != null) && _dispatcher.IsExecuting;
}
}
public void PostKey(VsKeyInfo key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
_keyBuffer.Add(key);
}
public bool IsExecutingReadKey
{
get { return _isExecutingReadKey; }
}
public bool IsKeyAvailable
{
get
{
// In our BlockingCollection<T> producer/consumer this is
// not critical so no need for locking.
return _keyBuffer.Count > 0;
}
}
public void CancelWaitKey()
{
if (_isExecutingReadKey && !_cancelWaitKeySource.IsCancellationRequested)
{
_cancelWaitKeySource.Cancel();
}
}
public void AcceptKeyInput()
{
Debug.Assert(_dispatcher != null);
if (_dispatcher != null && WpfConsole != null)
{
WpfConsole.BeginInputLine();
}
}
public VsKeyInfo WaitKey()
{
try
{
// raise the StartWaitingKey event on main thread
RaiseEventSafe(StartWaitingKey);
// set/reset the cancellation token
_cancelWaitKeySource = new CancellationTokenSource();
_isExecutingReadKey = true;
// blocking call
VsKeyInfo key = _keyBuffer.Take(_cancelWaitKeySource.Token);
return key;
}
catch (OperationCanceledException)
{
return null;
}
finally
{
_isExecutingReadKey = false;
}
}
private void RaiseEventSafe(EventHandler handler)
{
if (handler != null)
{
Microsoft.VisualStudio.Shell.ThreadHelper.Generic.Invoke(() => handler(this, EventArgs.Empty));
}
}
public bool IsStartCompleted { get; private set; }
#region IConsoleDispatcher
public void Start()
{
// Only Start once
lock (_lockObj)
{
if (_dispatcher == null)
{
IHost host = WpfConsole.Host;
if (host == null)
{
throw new InvalidOperationException("Can't start Console dispatcher. Host is null.");
}
if (host is IAsyncHost)
{
_dispatcher = new AsyncHostConsoleDispatcher(this);
}
else
{
_dispatcher = new SyncHostConsoleDispatcher(this);
}
Task.Factory.StartNew(
// gives the host a chance to do initialization works before the console starts accepting user inputs
() => host.Initialize(WpfConsole)
).ContinueWith(
task =>
{
if (task.IsFaulted)
{
var exception = ExceptionUtility.Unwrap(task.Exception);
WriteError(exception.Message);
}
if (host.IsCommandEnabled)
{
Microsoft.VisualStudio.Shell.ThreadHelper.Generic.Invoke(_dispatcher.Start);
}
RaiseEventSafe(StartCompleted);
IsStartCompleted = true;
},
TaskContinuationOptions.NotOnCanceled
);
}
}
}
private void WriteError(string message)
{
if (WpfConsole != null)
{
WpfConsole.Write(message + Environment.NewLine, Colors.Red, null);
}
}
public void ClearConsole()
{
Debug.Assert(_dispatcher != null);
if (_dispatcher != null)
{
_dispatcher.ClearConsole();
}
}
#endregion
#region IPrivateConsoleDispatcher
public event EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> ExecuteInputLine;
void OnExecute(SnapshotSpan inputLineSpan, bool isComplete)
{
ExecuteInputLine.Raise(this, Tuple.Create(inputLineSpan, isComplete));
}
public void PostInputLine(InputLine inputLine)
{
Debug.Assert(_dispatcher != null);
if (_dispatcher != null)
{
_dispatcher.PostInputLine(inputLine);
}
}
#endregion
private abstract class Dispatcher
{
protected ConsoleDispatcher ParentDispatcher { get; private set; }
protected IPrivateWpfConsole WpfConsole { get; private set; }
private bool _isExecuting;
public bool IsExecuting
{
get
{
return _isExecuting;
}
protected set
{
_isExecuting = value;
WpfConsole.SetExecutionMode(_isExecuting);
}
}
protected Dispatcher(ConsoleDispatcher parentDispatcher)
{
ParentDispatcher = parentDispatcher;
WpfConsole = parentDispatcher.WpfConsole;
}
/// <summary>
/// Process a input line.
/// </summary>
/// <param name="inputLine"></param>
protected Tuple<bool, bool> Process(InputLine inputLine)
{
SnapshotSpan inputSpan = inputLine.SnapshotSpan;
if (inputLine.Flags.HasFlag(InputLineFlag.Echo))
{
WpfConsole.BeginInputLine();
if (inputLine.Flags.HasFlag(InputLineFlag.Execute))
{
WpfConsole.WriteLine(inputLine.Text);
inputSpan = WpfConsole.EndInputLine(true).Value;
}
else
{
WpfConsole.Write(inputLine.Text);
}
}
if (inputLine.Flags.HasFlag(InputLineFlag.Execute))
{
string command = inputLine.Text;
bool isExecuted = WpfConsole.Host.Execute(WpfConsole, command, null);
WpfConsole.InputHistory.Add(command);
ParentDispatcher.OnExecute(inputSpan, isExecuted);
return Tuple.Create(true, isExecuted);
}
return Tuple.Create(false, false);
}
protected void PromptNewLine()
{
WpfConsole.Write(WpfConsole.Host.Prompt + (char)32); // 32 is the space
WpfConsole.BeginInputLine();
}
public void ClearConsole()
{
// When inputting commands
if (WpfConsole.InputLineStart != null)
{
WpfConsole.Host.Abort(); // Clear constructing multi-line command
WpfConsole.Clear();
PromptNewLine();
}
else
{
WpfConsole.Clear();
}
}
public abstract void Start();
public abstract void PostInputLine(InputLine inputLine);
}
/// <summary>
/// This class dispatches inputs for synchronous hosts.
/// </summary>
private class SyncHostConsoleDispatcher : Dispatcher
{
public SyncHostConsoleDispatcher(ConsoleDispatcher parentDispatcher)
: base(parentDispatcher)
{
}
public override void Start()
{
PromptNewLine();
}
public override void PostInputLine(InputLine inputLine)
{
IsExecuting = true;
try
{
if (Process(inputLine).Item1)
{
PromptNewLine();
}
}
finally
{
IsExecuting = false;
}
}
}
/// <summary>
/// This class dispatches inputs for asynchronous hosts.
/// </summary>
private class AsyncHostConsoleDispatcher : Dispatcher
{
private Queue<InputLine> _buffer;
private readonly Marshaler _marshaler;
public AsyncHostConsoleDispatcher(ConsoleDispatcher parentDispatcher)
: base(parentDispatcher)
{
_marshaler = new Marshaler(this);
}
private bool IsStarted
{
get
{
return _buffer != null;
}
}
public override void Start()
{
if (IsStarted)
{
// Can only start once... ConsoleDispatcher is already protecting this.
throw new InvalidOperationException();
}
_buffer = new Queue<InputLine>();
IAsyncHost asyncHost = WpfConsole.Host as IAsyncHost;
if (asyncHost == null)
{
// ConsoleDispatcher is already checking this.
throw new InvalidOperationException();
}
asyncHost.ExecuteEnd += _marshaler.AsyncHost_ExecuteEnd;
PromptNewLine();
}
public override void PostInputLine(InputLine inputLine)
{
// The editor should be completely readonly unless started.
Debug.Assert(IsStarted);
if (IsStarted)
{
_buffer.Enqueue(inputLine);
ProcessInputs();
}
}
private void ProcessInputs()
{
if (IsExecuting)
{
return;
}
if (_buffer.Count > 0)
{
InputLine inputLine = _buffer.Dequeue();
Tuple<bool, bool> executeState = Process(inputLine);
if (executeState.Item1)
{
IsExecuting = true;
if (!executeState.Item2)
{
// If NOT really executed, processing the same as ExecuteEnd event
OnExecuteEnd();
}
}
}
}
private void OnExecuteEnd()
{
if (IsStarted)
{
// Filter out noise. A host could execute private commands.
Debug.Assert(IsExecuting);
IsExecuting = false;
PromptNewLine();
ProcessInputs();
}
}
/// <summary>
/// This private Marshaler marshals async host event to main thread so that the dispatcher
/// doesn't need to worry about threading.
/// </summary>
private class Marshaler : Marshaler<AsyncHostConsoleDispatcher>
{
public Marshaler(AsyncHostConsoleDispatcher impl)
: base(impl)
{
}
public void AsyncHost_ExecuteEnd(object sender, EventArgs e)
{
Invoke(() => _impl.OnExecuteEnd());
}
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_keyBuffer != null)
{
_keyBuffer.Dispose();
}
if (_cancelWaitKeySource != null)
{
_cancelWaitKeySource.Dispose();
}
}
}
void IDisposable.Dispose()
{
try
{
Dispose(true);
}
finally
{
GC.SuppressFinalize(this);
}
}
~ConsoleDispatcher()
{
Dispose(false);
}
}
[Flags]
internal enum InputLineFlag
{
Echo = 1,
Execute = 2
}
internal class InputLine
{
public SnapshotSpan SnapshotSpan { get; private set; }
public string Text { get; private set; }
public InputLineFlag Flags { get; private set; }
public InputLine(string text, bool execute)
{
this.Text = text;
this.Flags = InputLineFlag.Echo;
if (execute)
{
this.Flags |= InputLineFlag.Execute;
}
}
public InputLine(SnapshotSpan snapshotSpan)
{
this.SnapshotSpan = snapshotSpan;
this.Text = snapshotSpan.GetText();
this.Flags = InputLineFlag.Execute;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Linq;
using Avalonia.Markup.Xaml.Parsers;
using Sprache;
using Xunit;
namespace Avalonia.Xaml.Base.UnitTest.Parsers
{
public class SelectorGrammarTests
{
[Fact]
public void OfType()
{
var result = SelectorGrammar.Selector.Parse("Button").ToList();
Assert.Equal(
new[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button", Xmlns = null } },
result);
}
[Fact]
public void NamespacedOfType()
{
var result = SelectorGrammar.Selector.Parse("x|Button").ToList();
Assert.Equal(
new[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button", Xmlns = "x" } },
result);
}
[Fact]
public void Name()
{
var result = SelectorGrammar.Selector.Parse("#foo").ToList();
Assert.Equal(
new[] { new SelectorGrammar.NameSyntax { Name = "foo" }, },
result);
}
[Fact]
public void OfType_Name()
{
var result = SelectorGrammar.Selector.Parse("Button#foo").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NameSyntax { Name = "foo" },
},
result);
}
[Fact]
public void Is()
{
var result = SelectorGrammar.Selector.Parse(":is(Button)").ToList();
Assert.Equal(
new[] { new SelectorGrammar.IsSyntax { TypeName = "Button", Xmlns = null } },
result);
}
[Fact]
public void Is_Name()
{
var result = SelectorGrammar.Selector.Parse(":is(Button)#foo").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.IsSyntax { TypeName = "Button" },
new SelectorGrammar.NameSyntax { Name = "foo" },
},
result);
}
[Fact]
public void NamespacedIs_Name()
{
var result = SelectorGrammar.Selector.Parse(":is(x|Button)#foo").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.IsSyntax { TypeName = "Button", Xmlns = "x" },
new SelectorGrammar.NameSyntax { Name = "foo" },
},
result);
}
[Fact]
public void Class()
{
var result = SelectorGrammar.Selector.Parse(".foo").ToList();
Assert.Equal(
new[] { new SelectorGrammar.ClassSyntax { Class = "foo" } },
result);
}
[Fact]
public void Pseudoclass()
{
var result = SelectorGrammar.Selector.Parse(":foo").ToList();
Assert.Equal(
new[] { new SelectorGrammar.ClassSyntax { Class = ":foo" } },
result);
}
[Fact]
public void OfType_Class()
{
var result = SelectorGrammar.Selector.Parse("Button.foo").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Child_Class()
{
var result = SelectorGrammar.Selector.Parse("Button > .foo").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.ChildSyntax { },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Child_Class_No_Spaces()
{
var result = SelectorGrammar.Selector.Parse("Button>.foo").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.ChildSyntax { },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Descendant_Class()
{
var result = SelectorGrammar.Selector.Parse("Button .foo").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.DescendantSyntax { },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Template_Class()
{
var result = SelectorGrammar.Selector.Parse("Button /template/ .foo").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.TemplateSyntax { },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Property()
{
var result = SelectorGrammar.Selector.Parse("Button[Foo=bar]").ToList();
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.PropertySyntax { Property = "Foo", Value = "bar" },
},
result);
}
[Fact]
public void Namespace_Alone_Fails()
{
Assert.Throws<ParseException>(() => SelectorGrammar.Selector.Parse("ns|").ToList());
}
[Fact]
public void Dot_Alone_Fails()
{
Assert.Throws<ParseException>(() => SelectorGrammar.Selector.Parse(". dot").ToList());
}
[Fact]
public void Invalid_Identifier_Fails()
{
Assert.Throws<ParseException>(() => SelectorGrammar.Selector.Parse("%foo").ToList());
}
[Fact]
public void Invalid_Class_Fails()
{
Assert.Throws<ParseException>(() => SelectorGrammar.Selector.Parse(".%foo").ToList());
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace OrgPortalServer.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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.
//Testing simple math on local vars and fields - rem
#pragma warning disable 0414
using System;
internal class lclfldrem
{
//user-defined class that overloads operator %
public class numHolder
{
private int _i_num;
private uint _ui_num;
private long _l_num;
private ulong _ul_num;
private float _f_num;
private double _d_num;
private decimal _m_num;
public numHolder(int i_num)
{
_i_num = Convert.ToInt32(i_num);
_ui_num = Convert.ToUInt32(i_num);
_l_num = Convert.ToInt64(i_num);
_ul_num = Convert.ToUInt64(i_num);
_f_num = Convert.ToSingle(i_num);
_d_num = Convert.ToDouble(i_num);
_m_num = Convert.ToDecimal(i_num);
}
public static int operator %(numHolder a, int b)
{
return a._i_num % b;
}
public numHolder(uint ui_num)
{
_i_num = Convert.ToInt32(ui_num);
_ui_num = Convert.ToUInt32(ui_num);
_l_num = Convert.ToInt64(ui_num);
_ul_num = Convert.ToUInt64(ui_num);
_f_num = Convert.ToSingle(ui_num);
_d_num = Convert.ToDouble(ui_num);
_m_num = Convert.ToDecimal(ui_num);
}
public static uint operator %(numHolder a, uint b)
{
return a._ui_num % b;
}
public numHolder(long l_num)
{
_i_num = Convert.ToInt32(l_num);
_ui_num = Convert.ToUInt32(l_num);
_l_num = Convert.ToInt64(l_num);
_ul_num = Convert.ToUInt64(l_num);
_f_num = Convert.ToSingle(l_num);
_d_num = Convert.ToDouble(l_num);
_m_num = Convert.ToDecimal(l_num);
}
public static long operator %(numHolder a, long b)
{
return a._l_num % b;
}
public numHolder(ulong ul_num)
{
_i_num = Convert.ToInt32(ul_num);
_ui_num = Convert.ToUInt32(ul_num);
_l_num = Convert.ToInt64(ul_num);
_ul_num = Convert.ToUInt64(ul_num);
_f_num = Convert.ToSingle(ul_num);
_d_num = Convert.ToDouble(ul_num);
_m_num = Convert.ToDecimal(ul_num);
}
public static long operator %(numHolder a, ulong b)
{
return (long)(a._ul_num % b);
}
public numHolder(float f_num)
{
_i_num = Convert.ToInt32(f_num);
_ui_num = Convert.ToUInt32(f_num);
_l_num = Convert.ToInt64(f_num);
_ul_num = Convert.ToUInt64(f_num);
_f_num = Convert.ToSingle(f_num);
_d_num = Convert.ToDouble(f_num);
_m_num = Convert.ToDecimal(f_num);
}
public static float operator %(numHolder a, float b)
{
return a._f_num % b;
}
public numHolder(double d_num)
{
_i_num = Convert.ToInt32(d_num);
_ui_num = Convert.ToUInt32(d_num);
_l_num = Convert.ToInt64(d_num);
_ul_num = Convert.ToUInt64(d_num);
_f_num = Convert.ToSingle(d_num);
_d_num = Convert.ToDouble(d_num);
_m_num = Convert.ToDecimal(d_num);
}
public static double operator %(numHolder a, double b)
{
return a._d_num % b;
}
public numHolder(decimal m_num)
{
_i_num = Convert.ToInt32(m_num);
_ui_num = Convert.ToUInt32(m_num);
_l_num = Convert.ToInt64(m_num);
_ul_num = Convert.ToUInt64(m_num);
_f_num = Convert.ToSingle(m_num);
_d_num = Convert.ToDouble(m_num);
_m_num = Convert.ToDecimal(m_num);
}
public static int operator %(numHolder a, decimal b)
{
return (int)(a._m_num % b);
}
public static int operator %(numHolder a, numHolder b)
{
return a._i_num % b._i_num;
}
}
private static int s_i_s_op1 = 9;
private static uint s_ui_s_op1 = 9;
private static long s_l_s_op1 = 9;
private static ulong s_ul_s_op1 = 9;
private static float s_f_s_op1 = 9;
private static double s_d_s_op1 = 9;
private static decimal s_m_s_op1 = 9;
private static int s_i_s_op2 = 5;
private static uint s_ui_s_op2 = 5;
private static long s_l_s_op2 = 5;
private static ulong s_ul_s_op2 = 5;
private static float s_f_s_op2 = 5;
private static double s_d_s_op2 = 5;
private static decimal s_m_s_op2 = 5;
private static numHolder s_nHldr_s_op2 = new numHolder(5);
public static int i_f(String s)
{
if (s == "op1")
return 9;
else
return 5;
}
public static uint ui_f(String s)
{
if (s == "op1")
return 9;
else
return 5;
}
public static long l_f(String s)
{
if (s == "op1")
return 9;
else
return 5;
}
public static ulong ul_f(String s)
{
if (s == "op1")
return 9;
else
return 5;
}
public static float f_f(String s)
{
if (s == "op1")
return 9;
else
return 5;
}
public static double d_f(String s)
{
if (s == "op1")
return 9;
else
return 5;
}
public static decimal m_f(String s)
{
if (s == "op1")
return 9;
else
return 5;
}
public static numHolder nHldr_f(String s)
{
if (s == "op1")
return new numHolder(9);
else
return new numHolder(5);
}
private class CL
{
public int i_cl_op1 = 9;
public uint ui_cl_op1 = 9;
public long l_cl_op1 = 9;
public ulong ul_cl_op1 = 9;
public float f_cl_op1 = 9;
public double d_cl_op1 = 9;
public decimal m_cl_op1 = 9;
public int i_cl_op2 = 5;
public uint ui_cl_op2 = 5;
public long l_cl_op2 = 5;
public ulong ul_cl_op2 = 5;
public float f_cl_op2 = 5;
public double d_cl_op2 = 5;
public decimal m_cl_op2 = 5;
public numHolder nHldr_cl_op2 = new numHolder(5);
}
private struct VT
{
public int i_vt_op1;
public uint ui_vt_op1;
public long l_vt_op1;
public ulong ul_vt_op1;
public float f_vt_op1;
public double d_vt_op1;
public decimal m_vt_op1;
public int i_vt_op2;
public uint ui_vt_op2;
public long l_vt_op2;
public ulong ul_vt_op2;
public float f_vt_op2;
public double d_vt_op2;
public decimal m_vt_op2;
public numHolder nHldr_vt_op2;
}
public static int Main()
{
bool passed = true;
//initialize class
CL cl1 = new CL();
//initialize struct
VT vt1;
vt1.i_vt_op1 = 9;
vt1.ui_vt_op1 = 9;
vt1.l_vt_op1 = 9;
vt1.ul_vt_op1 = 9;
vt1.f_vt_op1 = 9;
vt1.d_vt_op1 = 9;
vt1.m_vt_op1 = 9;
vt1.i_vt_op2 = 5;
vt1.ui_vt_op2 = 5;
vt1.l_vt_op2 = 5;
vt1.ul_vt_op2 = 5;
vt1.f_vt_op2 = 5;
vt1.d_vt_op2 = 5;
vt1.m_vt_op2 = 5;
vt1.nHldr_vt_op2 = new numHolder(5);
int[] i_arr1d_op1 = { 0, 9 };
int[,] i_arr2d_op1 = { { 0, 9 }, { 1, 1 } };
int[,,] i_arr3d_op1 = { { { 0, 9 }, { 1, 1 } } };
uint[] ui_arr1d_op1 = { 0, 9 };
uint[,] ui_arr2d_op1 = { { 0, 9 }, { 1, 1 } };
uint[,,] ui_arr3d_op1 = { { { 0, 9 }, { 1, 1 } } };
long[] l_arr1d_op1 = { 0, 9 };
long[,] l_arr2d_op1 = { { 0, 9 }, { 1, 1 } };
long[,,] l_arr3d_op1 = { { { 0, 9 }, { 1, 1 } } };
ulong[] ul_arr1d_op1 = { 0, 9 };
ulong[,] ul_arr2d_op1 = { { 0, 9 }, { 1, 1 } };
ulong[,,] ul_arr3d_op1 = { { { 0, 9 }, { 1, 1 } } };
float[] f_arr1d_op1 = { 0, 9 };
float[,] f_arr2d_op1 = { { 0, 9 }, { 1, 1 } };
float[,,] f_arr3d_op1 = { { { 0, 9 }, { 1, 1 } } };
double[] d_arr1d_op1 = { 0, 9 };
double[,] d_arr2d_op1 = { { 0, 9 }, { 1, 1 } };
double[,,] d_arr3d_op1 = { { { 0, 9 }, { 1, 1 } } };
decimal[] m_arr1d_op1 = { 0, 9 };
decimal[,] m_arr2d_op1 = { { 0, 9 }, { 1, 1 } };
decimal[,,] m_arr3d_op1 = { { { 0, 9 }, { 1, 1 } } };
int[] i_arr1d_op2 = { 5, 0, 1 };
int[,] i_arr2d_op2 = { { 0, 5 }, { 1, 1 } };
int[,,] i_arr3d_op2 = { { { 0, 5 }, { 1, 1 } } };
uint[] ui_arr1d_op2 = { 5, 0, 1 };
uint[,] ui_arr2d_op2 = { { 0, 5 }, { 1, 1 } };
uint[,,] ui_arr3d_op2 = { { { 0, 5 }, { 1, 1 } } };
long[] l_arr1d_op2 = { 5, 0, 1 };
long[,] l_arr2d_op2 = { { 0, 5 }, { 1, 1 } };
long[,,] l_arr3d_op2 = { { { 0, 5 }, { 1, 1 } } };
ulong[] ul_arr1d_op2 = { 5, 0, 1 };
ulong[,] ul_arr2d_op2 = { { 0, 5 }, { 1, 1 } };
ulong[,,] ul_arr3d_op2 = { { { 0, 5 }, { 1, 1 } } };
float[] f_arr1d_op2 = { 5, 0, 1 };
float[,] f_arr2d_op2 = { { 0, 5 }, { 1, 1 } };
float[,,] f_arr3d_op2 = { { { 0, 5 }, { 1, 1 } } };
double[] d_arr1d_op2 = { 5, 0, 1 };
double[,] d_arr2d_op2 = { { 0, 5 }, { 1, 1 } };
double[,,] d_arr3d_op2 = { { { 0, 5 }, { 1, 1 } } };
decimal[] m_arr1d_op2 = { 5, 0, 1 };
decimal[,] m_arr2d_op2 = { { 0, 5 }, { 1, 1 } };
decimal[,,] m_arr3d_op2 = { { { 0, 5 }, { 1, 1 } } };
numHolder[] nHldr_arr1d_op2 = { new numHolder(5), new numHolder(0), new numHolder(1) };
numHolder[,] nHldr_arr2d_op2 = { { new numHolder(0), new numHolder(5) }, { new numHolder(1), new numHolder(1) } };
numHolder[,,] nHldr_arr3d_op2 = { { { new numHolder(0), new numHolder(5) }, { new numHolder(1), new numHolder(1) } } };
int[,] index = { { 0, 0 }, { 1, 1 } };
{
int i_l_op1 = 9;
int i_l_op2 = 5;
uint ui_l_op2 = 5;
long l_l_op2 = 5;
ulong ul_l_op2 = 5;
float f_l_op2 = 5;
double d_l_op2 = 5;
decimal m_l_op2 = 5;
numHolder nHldr_l_op2 = new numHolder(5);
if ((i_l_op1 % i_l_op2 != i_l_op1 % ui_l_op2) || (i_l_op1 % ui_l_op2 != i_l_op1 % l_l_op2) || (i_l_op1 % l_l_op2 != i_l_op1 % (int)ul_l_op2) || (i_l_op1 % (int)ul_l_op2 != i_l_op1 % f_l_op2) || (i_l_op1 % f_l_op2 != i_l_op1 % d_l_op2) || ((decimal)(i_l_op1 % d_l_op2) != i_l_op1 % m_l_op2) || (i_l_op1 % m_l_op2 != i_l_op1 % i_l_op2) || (i_l_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 1 failed");
passed = false;
}
if ((i_l_op1 % s_i_s_op2 != i_l_op1 % s_ui_s_op2) || (i_l_op1 % s_ui_s_op2 != i_l_op1 % s_l_s_op2) || (i_l_op1 % s_l_s_op2 != i_l_op1 % (int)s_ul_s_op2) || (i_l_op1 % (int)s_ul_s_op2 != i_l_op1 % s_f_s_op2) || (i_l_op1 % s_f_s_op2 != i_l_op1 % s_d_s_op2) || ((decimal)(i_l_op1 % s_d_s_op2) != i_l_op1 % s_m_s_op2) || (i_l_op1 % s_m_s_op2 != i_l_op1 % s_i_s_op2) || (i_l_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 2 failed");
passed = false;
}
if ((s_i_s_op1 % i_l_op2 != s_i_s_op1 % ui_l_op2) || (s_i_s_op1 % ui_l_op2 != s_i_s_op1 % l_l_op2) || (s_i_s_op1 % l_l_op2 != s_i_s_op1 % (int)ul_l_op2) || (s_i_s_op1 % (int)ul_l_op2 != s_i_s_op1 % f_l_op2) || (s_i_s_op1 % f_l_op2 != s_i_s_op1 % d_l_op2) || ((decimal)(s_i_s_op1 % d_l_op2) != s_i_s_op1 % m_l_op2) || (s_i_s_op1 % m_l_op2 != s_i_s_op1 % i_l_op2) || (s_i_s_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 3 failed");
passed = false;
}
if ((s_i_s_op1 % s_i_s_op2 != s_i_s_op1 % s_ui_s_op2) || (s_i_s_op1 % s_ui_s_op2 != s_i_s_op1 % s_l_s_op2) || (s_i_s_op1 % s_l_s_op2 != s_i_s_op1 % (int)s_ul_s_op2) || (s_i_s_op1 % (int)s_ul_s_op2 != s_i_s_op1 % s_f_s_op2) || (s_i_s_op1 % s_f_s_op2 != s_i_s_op1 % s_d_s_op2) || ((decimal)(s_i_s_op1 % s_d_s_op2) != s_i_s_op1 % s_m_s_op2) || (s_i_s_op1 % s_m_s_op2 != s_i_s_op1 % s_i_s_op2) || (s_i_s_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 4 failed");
passed = false;
}
}
{
uint ui_l_op1 = 9;
int i_l_op2 = 5;
uint ui_l_op2 = 5;
long l_l_op2 = 5;
ulong ul_l_op2 = 5;
float f_l_op2 = 5;
double d_l_op2 = 5;
decimal m_l_op2 = 5;
numHolder nHldr_l_op2 = new numHolder(5);
if ((ui_l_op1 % i_l_op2 != ui_l_op1 % ui_l_op2) || (ui_l_op1 % ui_l_op2 != ui_l_op1 % l_l_op2) || ((ulong)(ui_l_op1 % l_l_op2) != ui_l_op1 % ul_l_op2) || (ui_l_op1 % ul_l_op2 != ui_l_op1 % f_l_op2) || (ui_l_op1 % f_l_op2 != ui_l_op1 % d_l_op2) || ((decimal)(ui_l_op1 % d_l_op2) != ui_l_op1 % m_l_op2) || (ui_l_op1 % m_l_op2 != ui_l_op1 % i_l_op2) || (ui_l_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 5 failed");
passed = false;
}
if ((ui_l_op1 % s_i_s_op2 != ui_l_op1 % s_ui_s_op2) || (ui_l_op1 % s_ui_s_op2 != ui_l_op1 % s_l_s_op2) || ((ulong)(ui_l_op1 % s_l_s_op2) != ui_l_op1 % s_ul_s_op2) || (ui_l_op1 % s_ul_s_op2 != ui_l_op1 % s_f_s_op2) || (ui_l_op1 % s_f_s_op2 != ui_l_op1 % s_d_s_op2) || ((decimal)(ui_l_op1 % s_d_s_op2) != ui_l_op1 % s_m_s_op2) || (ui_l_op1 % s_m_s_op2 != ui_l_op1 % s_i_s_op2) || (ui_l_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 6 failed");
passed = false;
}
if ((s_ui_s_op1 % i_l_op2 != s_ui_s_op1 % ui_l_op2) || (s_ui_s_op1 % ui_l_op2 != s_ui_s_op1 % l_l_op2) || ((ulong)(s_ui_s_op1 % l_l_op2) != s_ui_s_op1 % ul_l_op2) || (s_ui_s_op1 % ul_l_op2 != s_ui_s_op1 % f_l_op2) || (s_ui_s_op1 % f_l_op2 != s_ui_s_op1 % d_l_op2) || ((decimal)(s_ui_s_op1 % d_l_op2) != s_ui_s_op1 % m_l_op2) || (s_ui_s_op1 % m_l_op2 != s_ui_s_op1 % i_l_op2) || (s_ui_s_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 7 failed");
passed = false;
}
if ((s_ui_s_op1 % s_i_s_op2 != s_ui_s_op1 % s_ui_s_op2) || (s_ui_s_op1 % s_ui_s_op2 != s_ui_s_op1 % s_l_s_op2) || ((ulong)(s_ui_s_op1 % s_l_s_op2) != s_ui_s_op1 % s_ul_s_op2) || (s_ui_s_op1 % s_ul_s_op2 != s_ui_s_op1 % s_f_s_op2) || (s_ui_s_op1 % s_f_s_op2 != s_ui_s_op1 % s_d_s_op2) || ((decimal)(s_ui_s_op1 % s_d_s_op2) != s_ui_s_op1 % s_m_s_op2) || (s_ui_s_op1 % s_m_s_op2 != s_ui_s_op1 % s_i_s_op2) || (s_ui_s_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 8 failed");
passed = false;
}
}
{
long l_l_op1 = 9;
int i_l_op2 = 5;
uint ui_l_op2 = 5;
long l_l_op2 = 5;
ulong ul_l_op2 = 5;
float f_l_op2 = 5;
double d_l_op2 = 5;
decimal m_l_op2 = 5;
numHolder nHldr_l_op2 = new numHolder(5);
if ((l_l_op1 % i_l_op2 != l_l_op1 % ui_l_op2) || (l_l_op1 % ui_l_op2 != l_l_op1 % l_l_op2) || (l_l_op1 % l_l_op2 != l_l_op1 % (long)ul_l_op2) || (l_l_op1 % (long)ul_l_op2 != l_l_op1 % f_l_op2) || (l_l_op1 % f_l_op2 != l_l_op1 % d_l_op2) || ((decimal)(l_l_op1 % d_l_op2) != l_l_op1 % m_l_op2) || (l_l_op1 % m_l_op2 != l_l_op1 % i_l_op2) || (l_l_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 9 failed");
passed = false;
}
if ((l_l_op1 % s_i_s_op2 != l_l_op1 % s_ui_s_op2) || (l_l_op1 % s_ui_s_op2 != l_l_op1 % s_l_s_op2) || (l_l_op1 % s_l_s_op2 != l_l_op1 % (long)s_ul_s_op2) || (l_l_op1 % (long)s_ul_s_op2 != l_l_op1 % s_f_s_op2) || (l_l_op1 % s_f_s_op2 != l_l_op1 % s_d_s_op2) || ((decimal)(l_l_op1 % s_d_s_op2) != l_l_op1 % s_m_s_op2) || (l_l_op1 % s_m_s_op2 != l_l_op1 % s_i_s_op2) || (l_l_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 10 failed");
passed = false;
}
if ((s_l_s_op1 % i_l_op2 != s_l_s_op1 % ui_l_op2) || (s_l_s_op1 % ui_l_op2 != s_l_s_op1 % l_l_op2) || (s_l_s_op1 % l_l_op2 != s_l_s_op1 % (long)ul_l_op2) || (s_l_s_op1 % (long)ul_l_op2 != s_l_s_op1 % f_l_op2) || (s_l_s_op1 % f_l_op2 != s_l_s_op1 % d_l_op2) || ((decimal)(s_l_s_op1 % d_l_op2) != s_l_s_op1 % m_l_op2) || (s_l_s_op1 % m_l_op2 != s_l_s_op1 % i_l_op2) || (s_l_s_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 11 failed");
passed = false;
}
if ((s_l_s_op1 % s_i_s_op2 != s_l_s_op1 % s_ui_s_op2) || (s_l_s_op1 % s_ui_s_op2 != s_l_s_op1 % s_l_s_op2) || (s_l_s_op1 % s_l_s_op2 != s_l_s_op1 % (long)s_ul_s_op2) || (s_l_s_op1 % (long)s_ul_s_op2 != s_l_s_op1 % s_f_s_op2) || (s_l_s_op1 % s_f_s_op2 != s_l_s_op1 % s_d_s_op2) || ((decimal)(s_l_s_op1 % s_d_s_op2) != s_l_s_op1 % s_m_s_op2) || (s_l_s_op1 % s_m_s_op2 != s_l_s_op1 % s_i_s_op2) || (s_l_s_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 12 failed");
passed = false;
}
}
{
ulong ul_l_op1 = 9;
int i_l_op2 = 5;
uint ui_l_op2 = 5;
long l_l_op2 = 5;
ulong ul_l_op2 = 5;
float f_l_op2 = 5;
double d_l_op2 = 5;
decimal m_l_op2 = 5;
numHolder nHldr_l_op2 = new numHolder(5);
if ((ul_l_op1 % (ulong)i_l_op2 != ul_l_op1 % ui_l_op2) || (ul_l_op1 % ui_l_op2 != ul_l_op1 % (ulong)l_l_op2) || (ul_l_op1 % (ulong)l_l_op2 != ul_l_op1 % ul_l_op2) || (ul_l_op1 % ul_l_op2 != ul_l_op1 % f_l_op2) || (ul_l_op1 % f_l_op2 != ul_l_op1 % d_l_op2) || ((decimal)(ul_l_op1 % d_l_op2) != ul_l_op1 % m_l_op2) || (ul_l_op1 % m_l_op2 != ul_l_op1 % (ulong)i_l_op2) || (ul_l_op1 % (ulong)i_l_op2 != 4))
{
Console.WriteLine("testcase 13 failed");
passed = false;
}
if ((ul_l_op1 % (ulong)s_i_s_op2 != ul_l_op1 % s_ui_s_op2) || (ul_l_op1 % s_ui_s_op2 != ul_l_op1 % (ulong)s_l_s_op2) || (ul_l_op1 % (ulong)s_l_s_op2 != ul_l_op1 % s_ul_s_op2) || (ul_l_op1 % s_ul_s_op2 != ul_l_op1 % s_f_s_op2) || (ul_l_op1 % s_f_s_op2 != ul_l_op1 % s_d_s_op2) || ((decimal)(ul_l_op1 % s_d_s_op2) != ul_l_op1 % s_m_s_op2) || (ul_l_op1 % s_m_s_op2 != ul_l_op1 % (ulong)s_i_s_op2) || (ul_l_op1 % (ulong)s_i_s_op2 != 4))
{
Console.WriteLine("testcase 14 failed");
passed = false;
}
if ((s_ul_s_op1 % (ulong)i_l_op2 != s_ul_s_op1 % ui_l_op2) || (s_ul_s_op1 % ui_l_op2 != s_ul_s_op1 % (ulong)l_l_op2) || (s_ul_s_op1 % (ulong)l_l_op2 != s_ul_s_op1 % ul_l_op2) || (s_ul_s_op1 % ul_l_op2 != s_ul_s_op1 % f_l_op2) || (s_ul_s_op1 % f_l_op2 != s_ul_s_op1 % d_l_op2) || ((decimal)(s_ul_s_op1 % d_l_op2) != s_ul_s_op1 % m_l_op2) || (s_ul_s_op1 % m_l_op2 != s_ul_s_op1 % (ulong)i_l_op2) || (s_ul_s_op1 % (ulong)i_l_op2 != 4))
{
Console.WriteLine("testcase 15 failed");
passed = false;
}
if ((s_ul_s_op1 % (ulong)s_i_s_op2 != s_ul_s_op1 % s_ui_s_op2) || (s_ul_s_op1 % s_ui_s_op2 != s_ul_s_op1 % (ulong)s_l_s_op2) || (s_ul_s_op1 % (ulong)s_l_s_op2 != s_ul_s_op1 % s_ul_s_op2) || (s_ul_s_op1 % s_ul_s_op2 != s_ul_s_op1 % s_f_s_op2) || (s_ul_s_op1 % s_f_s_op2 != s_ul_s_op1 % s_d_s_op2) || ((decimal)(s_ul_s_op1 % s_d_s_op2) != s_ul_s_op1 % s_m_s_op2) || (s_ul_s_op1 % s_m_s_op2 != s_ul_s_op1 % (ulong)s_i_s_op2) || (s_ul_s_op1 % (ulong)s_i_s_op2 != 4))
{
Console.WriteLine("testcase 16 failed");
passed = false;
}
}
{
float f_l_op1 = 9;
int i_l_op2 = 5;
uint ui_l_op2 = 5;
long l_l_op2 = 5;
ulong ul_l_op2 = 5;
float f_l_op2 = 5;
double d_l_op2 = 5;
decimal m_l_op2 = 5;
numHolder nHldr_l_op2 = new numHolder(5);
if ((f_l_op1 % i_l_op2 != f_l_op1 % ui_l_op2) || (f_l_op1 % ui_l_op2 != f_l_op1 % l_l_op2) || (f_l_op1 % l_l_op2 != f_l_op1 % ul_l_op2) || (f_l_op1 % ul_l_op2 != f_l_op1 % f_l_op2) || (f_l_op1 % f_l_op2 != f_l_op1 % d_l_op2) || (f_l_op1 % d_l_op2 != f_l_op1 % (float)m_l_op2) || (f_l_op1 % (float)m_l_op2 != f_l_op1 % i_l_op2) || (f_l_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 17 failed");
passed = false;
}
if ((f_l_op1 % s_i_s_op2 != f_l_op1 % s_ui_s_op2) || (f_l_op1 % s_ui_s_op2 != f_l_op1 % s_l_s_op2) || (f_l_op1 % s_l_s_op2 != f_l_op1 % s_ul_s_op2) || (f_l_op1 % s_ul_s_op2 != f_l_op1 % s_f_s_op2) || (f_l_op1 % s_f_s_op2 != f_l_op1 % s_d_s_op2) || (f_l_op1 % s_d_s_op2 != f_l_op1 % (float)s_m_s_op2) || (f_l_op1 % (float)s_m_s_op2 != f_l_op1 % s_i_s_op2) || (f_l_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 18 failed");
passed = false;
}
if ((s_f_s_op1 % i_l_op2 != s_f_s_op1 % ui_l_op2) || (s_f_s_op1 % ui_l_op2 != s_f_s_op1 % l_l_op2) || (s_f_s_op1 % l_l_op2 != s_f_s_op1 % ul_l_op2) || (s_f_s_op1 % ul_l_op2 != s_f_s_op1 % f_l_op2) || (s_f_s_op1 % f_l_op2 != s_f_s_op1 % d_l_op2) || (s_f_s_op1 % d_l_op2 != s_f_s_op1 % (float)m_l_op2) || (s_f_s_op1 % (float)m_l_op2 != s_f_s_op1 % i_l_op2) || (s_f_s_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 19 failed");
passed = false;
}
if ((s_f_s_op1 % s_i_s_op2 != s_f_s_op1 % s_ui_s_op2) || (s_f_s_op1 % s_ui_s_op2 != s_f_s_op1 % s_l_s_op2) || (s_f_s_op1 % s_l_s_op2 != s_f_s_op1 % s_ul_s_op2) || (s_f_s_op1 % s_ul_s_op2 != s_f_s_op1 % s_f_s_op2) || (s_f_s_op1 % s_f_s_op2 != s_f_s_op1 % s_d_s_op2) || (s_f_s_op1 % s_d_s_op2 != s_f_s_op1 % (float)s_m_s_op2) || (s_f_s_op1 % (float)s_m_s_op2 != s_f_s_op1 % s_i_s_op2) || (s_f_s_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 20 failed");
passed = false;
}
}
{
double d_l_op1 = 9;
int i_l_op2 = 5;
uint ui_l_op2 = 5;
long l_l_op2 = 5;
ulong ul_l_op2 = 5;
float f_l_op2 = 5;
double d_l_op2 = 5;
decimal m_l_op2 = 5;
numHolder nHldr_l_op2 = new numHolder(5);
if ((d_l_op1 % i_l_op2 != d_l_op1 % ui_l_op2) || (d_l_op1 % ui_l_op2 != d_l_op1 % l_l_op2) || (d_l_op1 % l_l_op2 != d_l_op1 % ul_l_op2) || (d_l_op1 % ul_l_op2 != d_l_op1 % f_l_op2) || (d_l_op1 % f_l_op2 != d_l_op1 % d_l_op2) || (d_l_op1 % d_l_op2 != d_l_op1 % (double)m_l_op2) || (d_l_op1 % (double)m_l_op2 != d_l_op1 % i_l_op2) || (d_l_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 21 failed");
passed = false;
}
if ((d_l_op1 % s_i_s_op2 != d_l_op1 % s_ui_s_op2) || (d_l_op1 % s_ui_s_op2 != d_l_op1 % s_l_s_op2) || (d_l_op1 % s_l_s_op2 != d_l_op1 % s_ul_s_op2) || (d_l_op1 % s_ul_s_op2 != d_l_op1 % s_f_s_op2) || (d_l_op1 % s_f_s_op2 != d_l_op1 % s_d_s_op2) || (d_l_op1 % s_d_s_op2 != d_l_op1 % (double)s_m_s_op2) || (d_l_op1 % (double)s_m_s_op2 != d_l_op1 % s_i_s_op2) || (d_l_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 22 failed");
passed = false;
}
if ((s_d_s_op1 % i_l_op2 != s_d_s_op1 % ui_l_op2) || (s_d_s_op1 % ui_l_op2 != s_d_s_op1 % l_l_op2) || (s_d_s_op1 % l_l_op2 != s_d_s_op1 % ul_l_op2) || (s_d_s_op1 % ul_l_op2 != s_d_s_op1 % f_l_op2) || (s_d_s_op1 % f_l_op2 != s_d_s_op1 % d_l_op2) || (s_d_s_op1 % d_l_op2 != s_d_s_op1 % (double)m_l_op2) || (s_d_s_op1 % (double)m_l_op2 != s_d_s_op1 % i_l_op2) || (s_d_s_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 23 failed");
passed = false;
}
if ((s_d_s_op1 % s_i_s_op2 != s_d_s_op1 % s_ui_s_op2) || (s_d_s_op1 % s_ui_s_op2 != s_d_s_op1 % s_l_s_op2) || (s_d_s_op1 % s_l_s_op2 != s_d_s_op1 % s_ul_s_op2) || (s_d_s_op1 % s_ul_s_op2 != s_d_s_op1 % s_f_s_op2) || (s_d_s_op1 % s_f_s_op2 != s_d_s_op1 % s_d_s_op2) || (s_d_s_op1 % s_d_s_op2 != s_d_s_op1 % (double)s_m_s_op2) || (s_d_s_op1 % (double)s_m_s_op2 != s_d_s_op1 % s_i_s_op2) || (s_d_s_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 24 failed");
passed = false;
}
}
{
decimal m_l_op1 = 9;
int i_l_op2 = 5;
uint ui_l_op2 = 5;
long l_l_op2 = 5;
ulong ul_l_op2 = 5;
float f_l_op2 = 5;
double d_l_op2 = 5;
decimal m_l_op2 = 5;
numHolder nHldr_l_op2 = new numHolder(5);
if ((m_l_op1 % i_l_op2 != m_l_op1 % ui_l_op2) || (m_l_op1 % ui_l_op2 != m_l_op1 % l_l_op2) || (m_l_op1 % l_l_op2 != m_l_op1 % ul_l_op2) || (m_l_op1 % ul_l_op2 != m_l_op1 % (decimal)f_l_op2) || (m_l_op1 % (decimal)f_l_op2 != m_l_op1 % (decimal)d_l_op2) || (m_l_op1 % (decimal)d_l_op2 != m_l_op1 % m_l_op2) || (m_l_op1 % m_l_op2 != m_l_op1 % i_l_op2) || (m_l_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 25 failed");
passed = false;
}
if ((m_l_op1 % s_i_s_op2 != m_l_op1 % s_ui_s_op2) || (m_l_op1 % s_ui_s_op2 != m_l_op1 % s_l_s_op2) || (m_l_op1 % s_l_s_op2 != m_l_op1 % s_ul_s_op2) || (m_l_op1 % s_ul_s_op2 != m_l_op1 % (decimal)s_f_s_op2) || (m_l_op1 % (decimal)s_f_s_op2 != m_l_op1 % (decimal)s_d_s_op2) || (m_l_op1 % (decimal)s_d_s_op2 != m_l_op1 % s_m_s_op2) || (m_l_op1 % s_m_s_op2 != m_l_op1 % s_i_s_op2) || (m_l_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 26 failed");
passed = false;
}
if ((s_m_s_op1 % i_l_op2 != s_m_s_op1 % ui_l_op2) || (s_m_s_op1 % ui_l_op2 != s_m_s_op1 % l_l_op2) || (s_m_s_op1 % l_l_op2 != s_m_s_op1 % ul_l_op2) || (s_m_s_op1 % ul_l_op2 != s_m_s_op1 % (decimal)f_l_op2) || (s_m_s_op1 % (decimal)f_l_op2 != s_m_s_op1 % (decimal)d_l_op2) || (s_m_s_op1 % (decimal)d_l_op2 != s_m_s_op1 % m_l_op2) || (s_m_s_op1 % m_l_op2 != s_m_s_op1 % i_l_op2) || (s_m_s_op1 % i_l_op2 != 4))
{
Console.WriteLine("testcase 27 failed");
passed = false;
}
if ((s_m_s_op1 % s_i_s_op2 != s_m_s_op1 % s_ui_s_op2) || (s_m_s_op1 % s_ui_s_op2 != s_m_s_op1 % s_l_s_op2) || (s_m_s_op1 % s_l_s_op2 != s_m_s_op1 % s_ul_s_op2) || (s_m_s_op1 % s_ul_s_op2 != s_m_s_op1 % (decimal)s_f_s_op2) || (s_m_s_op1 % (decimal)s_f_s_op2 != s_m_s_op1 % (decimal)s_d_s_op2) || (s_m_s_op1 % (decimal)s_d_s_op2 != s_m_s_op1 % s_m_s_op2) || (s_m_s_op1 % s_m_s_op2 != s_m_s_op1 % s_i_s_op2) || (s_m_s_op1 % s_i_s_op2 != 4))
{
Console.WriteLine("testcase 28 failed");
passed = false;
}
}
if (!passed)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using StacksOfWax.AttributeRoutingApi.Areas.HelpPage.ModelDescriptions;
using StacksOfWax.AttributeRoutingApi.Areas.HelpPage.Models;
namespace StacksOfWax.AttributeRoutingApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Text;
/// <summary>
/// GetBytes(System.Char[],System.Int32,System.Int32)
/// </summary>
public class EncodingGetBytes2
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetBytes.");
try
{
char[] testChar = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };
Encoding u8 = Encoding.UTF8;
Encoding u16LE = Encoding.Unicode;
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] actualBytesUTF8 = new byte[] {
0x7A, 0x61, 0xCC ,0x86, 0xC7 ,0xBD,
0xCE ,0xB2 ,0xF1, 0x8F ,0xB3 ,0xBF};
byte[] actualBytesUnicode = new byte[]{
0x7A, 0x00, 0x61, 0x00, 0x06, 0x03,
0xFD, 0x01, 0xB2, 0x03, 0xFF, 0xD8,
0xFF, 0xDC};
byte[] actualBytesBigEndianUnicode = new byte[]{
0x00, 0x7A, 0x00, 0x61, 0x03, 0x06,
0x01, 0xFD, 0x03, 0xB2, 0xD8, 0xFF,
0xDC, 0xFF};
if (!VerifyByteItemValue(u8.GetBytes(testChar,0,testChar.Length), actualBytesUTF8) ||
!VerifyByteItemValue(u16LE.GetBytes(testChar,0,testChar.Length), actualBytesUnicode) ||
!VerifyByteItemValue(u16BE.GetBytes(testChar,0,testChar.Length), actualBytesBigEndianUnicode))
{
TestLibrary.TestFramework.LogError("001.1", "Method GetBytes Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetBytes when chars is null.");
try
{
char[] testChar = new char[0];
Encoding u8 = Encoding.UTF8;
Encoding u16LE = Encoding.Unicode;
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] result = new byte[0];
if (!VerifyByteItemValue(u8.GetBytes(testChar, 0, testChar.Length), result) ||
!VerifyByteItemValue(u16LE.GetBytes(testChar, 0, testChar.Length), result) ||
!VerifyByteItemValue(u16BE.GetBytes(testChar, 0, testChar.Length), result))
{
TestLibrary.TestFramework.LogError("002.1", "Method GetBytes Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown.");
try
{
char[] testChar = null;
Encoding u7 = Encoding.UTF8;
byte[] result = u7.GetBytes(testChar, 2, 1);
TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException is not thrown.");
try
{
char[] testChar = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };
Encoding u7 = Encoding.UTF8;
byte[] result = u7.GetBytes(testChar, -1, 1);
TestLibrary.TestFramework.LogError("102.1", "ArgumentOutOfRangeException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown.");
try
{
char[] testChar = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };
Encoding u7 = Encoding.UTF8;
byte[] result = u7.GetBytes(testChar, 0, -1);
TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown.");
try
{
char[] testChar = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };
Encoding u7 = Encoding.UTF8;
byte[] result = u7.GetBytes(testChar, 0, testChar.Length + 1);
TestLibrary.TestFramework.LogError("104.1", "ArgumentOutOfRangeException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
EncodingGetBytes2 test = new EncodingGetBytes2();
TestLibrary.TestFramework.BeginTestCase("EncodingGetBytes2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Method
private bool VerifyByteItemValue(byte[] getBytes, byte[] actualBytes)
{
if (getBytes.Length != actualBytes.Length)
return false;
else
{
for (int i = 0; i < getBytes.Length; i++)
if (getBytes[i] != actualBytes[i])
return false;
}
return true;
}
#endregion
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Calendars;
using NodaTime.Globalization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace NodaTime.Text.Patterns
{
/// <summary>
/// Common methods used when parsing dates - these are used from both LocalDateTimePatternParser
/// and LocalDatePatternParser.
/// </summary>
internal static class DatePatternHelper
{
/// <summary>
/// Creates a character handler for the year-of-era specifier (y).
/// </summary>
internal static CharacterHandler<TResult, TBucket> CreateYearOfEraHandler<TResult, TBucket>
(Func<TResult, int> yearGetter, Action<TBucket, int> setter)
where TBucket : ParseBucket<TResult>
{
return (pattern, builder) =>
{
int count = pattern.GetRepeatCount(4);
builder.AddField(PatternFields.YearOfEra, pattern.Current);
switch (count)
{
case 2:
builder.AddParseValueAction(2, 2, 'y', 0, 99, setter);
// Force the year into the range 0-99.
builder.AddFormatLeftPad(2, value => ((yearGetter(value) % 100) + 100) % 100,
assumeNonNegative: true,
assumeFitsInCount: true);
// Just remember that we've set this particular field. We can't set it twice as we've already got the YearOfEra flag set.
builder.AddField(PatternFields.YearTwoDigits, pattern.Current);
break;
case 4:
// Left-pad to 4 digits when formatting; parse exactly 4 digits.
builder.AddParseValueAction(4, 4, 'y', 1, 9999, setter);
builder.AddFormatLeftPad(4, yearGetter,
assumeNonNegative: false,
assumeFitsInCount: true);
break;
default:
throw new InvalidPatternException(TextErrorMessages.InvalidRepeatCount, pattern.Current, count);
}
};
}
/// <summary>
/// Creates a character handler for the month-of-year specifier (M).
/// </summary>
internal static CharacterHandler<TResult, TBucket> CreateMonthOfYearHandler<TResult, TBucket>
(Func<TResult, int> numberGetter, Action<TBucket, int> textSetter, Action<TBucket, int> numberSetter)
where TBucket : ParseBucket<TResult>
{
return (pattern, builder) =>
{
int count = pattern.GetRepeatCount(4);
PatternFields field;
switch (count)
{
case 1:
case 2:
field = PatternFields.MonthOfYearNumeric;
// Handle real maximum value in the bucket
builder.AddParseValueAction(count, 2, pattern.Current, 1, 99, numberSetter);
builder.AddFormatLeftPad(count, numberGetter, assumeNonNegative: true, assumeFitsInCount: count == 2);
break;
case 3:
case 4:
field = PatternFields.MonthOfYearText;
var format = builder.FormatInfo;
IReadOnlyList<string> nonGenitiveTextValues = count == 3 ? format.ShortMonthNames : format.LongMonthNames;
IReadOnlyList<string> genitiveTextValues = count == 3 ? format.ShortMonthGenitiveNames : format.LongMonthGenitiveNames;
if (nonGenitiveTextValues == genitiveTextValues)
{
builder.AddParseLongestTextAction(pattern.Current, textSetter, format.CompareInfo, nonGenitiveTextValues);
}
else
{
builder.AddParseLongestTextAction(pattern.Current, textSetter, format.CompareInfo,
genitiveTextValues, nonGenitiveTextValues);
}
// Hack: see below
builder.AddFormatAction(new MonthFormatActionHolder<TResult, TBucket>(format, count, numberGetter).DummyMethod);
break;
default:
throw new InvalidOperationException("Invalid count!");
}
builder.AddField(field, pattern.Current);
};
}
// Hacky way of building an action which depends on the final set of pattern fields to determine whether to format a month
// using the genitive form or not.
private sealed class MonthFormatActionHolder<TResult, TBucket> : SteppedPatternBuilder<TResult, TBucket>.IPostPatternParseFormatAction
where TBucket : ParseBucket<TResult>
{
private readonly int count;
private readonly NodaFormatInfo formatInfo;
private readonly Func<TResult, int> getter;
internal MonthFormatActionHolder(NodaFormatInfo formatInfo, int count, Func<TResult, int> getter)
{
this.count = count;
this.formatInfo = formatInfo;
this.getter = getter;
}
[ExcludeFromCodeCoverage]
internal void DummyMethod(TResult value, StringBuilder builder)
{
// This method is never called. We use it to create a delegate with a target that implements
// IPostPatternParseFormatAction. There's no test for this throwing.
throw new InvalidOperationException("This method should never be called");
}
public Action<TResult, StringBuilder> BuildFormatAction(PatternFields finalFields)
{
bool genitive = (finalFields & PatternFields.DayOfMonth) != 0;
IReadOnlyList<string> textValues = count == 3
? (genitive ? formatInfo.ShortMonthGenitiveNames : formatInfo.ShortMonthNames)
: (genitive ? formatInfo.LongMonthGenitiveNames : formatInfo.LongMonthNames);
return (value, sb) => sb.Append(textValues[getter(value)]);
}
}
/// <summary>
/// Creates a character handler for the day specifier (d).
/// </summary>
internal static CharacterHandler<TResult, TBucket> CreateDayHandler<TResult, TBucket>
(Func<TResult, int> dayOfMonthGetter, Func<TResult, int> dayOfWeekGetter,
Action<TBucket, int> dayOfMonthSetter, Action<TBucket, int> dayOfWeekSetter)
where TBucket : ParseBucket<TResult>
{
return (pattern, builder) =>
{
int count = pattern.GetRepeatCount(4);
PatternFields field;
switch (count)
{
case 1:
case 2:
field = PatternFields.DayOfMonth;
// Handle real maximum value in the bucket
builder.AddParseValueAction(count, 2, pattern.Current, 1, 99, dayOfMonthSetter);
builder.AddFormatLeftPad(count, dayOfMonthGetter, assumeNonNegative: true, assumeFitsInCount: count == 2);
break;
case 3:
case 4:
field = PatternFields.DayOfWeek;
var format = builder.FormatInfo;
IReadOnlyList<string> textValues = count == 3 ? format.ShortDayNames : format.LongDayNames;
builder.AddParseLongestTextAction(pattern.Current, dayOfWeekSetter, format.CompareInfo, textValues);
builder.AddFormatAction((value, sb) => sb.Append(textValues[dayOfWeekGetter(value)]));
break;
default:
throw new InvalidOperationException("Invalid count!");
}
builder.AddField(field, pattern.Current);
};
}
/// <summary>
/// Creates a character handler for the era specifier (g).
/// </summary>
internal static CharacterHandler<TResult, TBucket> CreateEraHandler<TResult, TBucket>
(Func<TResult, Era> eraFromValue, Func<TBucket, LocalDatePatternParser.LocalDateParseBucket> dateBucketFromBucket)
where TBucket : ParseBucket<TResult>
{
return (pattern, builder) =>
{
pattern.GetRepeatCount(2);
builder.AddField(PatternFields.Era, pattern.Current);
var formatInfo = builder.FormatInfo;
// Note: currently the count is ignored. More work needed to determine whether abbreviated era names should be used for just "g".
builder.AddParseAction((cursor, bucket) =>
{
var dateBucket = dateBucketFromBucket(bucket);
return dateBucket.ParseEra<TResult>(formatInfo, cursor);
});
builder.AddFormatAction((value, sb) => sb.Append(formatInfo.GetEraPrimaryName(eraFromValue(value))));
};
}
/// <summary>
/// Creates a character handler for the calendar specifier (c).
/// </summary>
internal static CharacterHandler<TResult, TBucket> CreateCalendarHandler<TResult, TBucket>
(Func<TResult, CalendarSystem> getter, Action<TBucket, CalendarSystem> setter)
where TBucket : ParseBucket<TResult>
{
return (pattern, builder) =>
{
builder.AddField(PatternFields.Calendar, pattern.Current);
builder.AddParseAction((cursor, bucket) =>
{
foreach (var id in CalendarSystem.Ids)
{
if (cursor.Match(id))
{
setter(bucket, CalendarSystem.ForId(id));
return null;
}
}
return ParseResult<TResult>.NoMatchingCalendarSystem(cursor);
});
builder.AddFormatAction((value, sb) => sb.Append(getter(value).Id));
};
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/timestamp.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.WellKnownTypes {
/// <summary>Holder for reflection information generated from google/protobuf/timestamp.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class TimestampReflection {
#region Descriptor
/// <summary>File descriptor for google/protobuf/timestamp.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TimestampReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJv",
"dG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MY",
"AiABKAVCUQoTY29tLmdvb2dsZS5wcm90b2J1ZkIOVGltZXN0YW1wUHJvdG9Q",
"AaABAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Timestamp), global::Google.Protobuf.WellKnownTypes.Timestamp.Parser, new[]{ "Seconds", "Nanos" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A Timestamp represents a point in time independent of any time zone
/// or calendar, represented as seconds and fractions of seconds at
/// nanosecond resolution in UTC Epoch time. It is encoded using the
/// Proleptic Gregorian Calendar which extends the Gregorian calendar
/// backwards to year one. It is encoded assuming all minutes are 60
/// seconds long, i.e. leap seconds are "smeared" so that no leap second
/// table is needed for interpretation. Range is from
/// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
/// By restricting to that range, we ensure that we can convert to
/// and from RFC 3339 date strings.
/// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
///
/// Example 1: Compute Timestamp from POSIX `time()`.
///
/// Timestamp timestamp;
/// timestamp.set_seconds(time(NULL));
/// timestamp.set_nanos(0);
///
/// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
///
/// struct timeval tv;
/// gettimeofday(&tv, NULL);
///
/// Timestamp timestamp;
/// timestamp.set_seconds(tv.tv_sec);
/// timestamp.set_nanos(tv.tv_usec * 1000);
///
/// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
///
/// FILETIME ft;
/// GetSystemTimeAsFileTime(&ft);
/// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
///
/// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
/// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
/// Timestamp timestamp;
/// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
/// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
///
/// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
///
/// long millis = System.currentTimeMillis();
///
/// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
/// .setNanos((int) ((millis % 1000) * 1000000)).build();
///
/// Example 5: Compute Timestamp from current time in Python.
///
/// now = time.time()
/// seconds = int(now)
/// nanos = int((now - seconds) * 10**9)
/// timestamp = Timestamp(seconds=seconds, nanos=nanos)
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Timestamp : pb::IMessage<Timestamp> {
private static readonly pb::MessageParser<Timestamp> _parser = new pb::MessageParser<Timestamp>(() => new Timestamp());
public static pb::MessageParser<Timestamp> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Timestamp() {
OnConstruction();
}
partial void OnConstruction();
public Timestamp(Timestamp other) : this() {
seconds_ = other.seconds_;
nanos_ = other.nanos_;
}
public Timestamp Clone() {
return new Timestamp(this);
}
/// <summary>Field number for the "seconds" field.</summary>
public const int SecondsFieldNumber = 1;
private long seconds_;
/// <summary>
/// Represents seconds of UTC time since Unix epoch
/// 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
/// 9999-12-31T23:59:59Z inclusive.
/// </summary>
public long Seconds {
get { return seconds_; }
set {
seconds_ = value;
}
}
/// <summary>Field number for the "nanos" field.</summary>
public const int NanosFieldNumber = 2;
private int nanos_;
/// <summary>
/// Non-negative fractions of a second at nanosecond resolution. Negative
/// second values with fractions must still have non-negative nanos values
/// that count forward in time. Must be from 0 to 999,999,999
/// inclusive.
/// </summary>
public int Nanos {
get { return nanos_; }
set {
nanos_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Timestamp);
}
public bool Equals(Timestamp other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Seconds != other.Seconds) return false;
if (Nanos != other.Nanos) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Seconds != 0L) hash ^= Seconds.GetHashCode();
if (Nanos != 0) hash ^= Nanos.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Seconds != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(16);
output.WriteInt32(Nanos);
}
}
public int CalculateSize() {
int size = 0;
if (Seconds != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds);
}
if (Nanos != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos);
}
return size;
}
public void MergeFrom(Timestamp other) {
if (other == null) {
return;
}
if (other.Seconds != 0L) {
Seconds = other.Seconds;
}
if (other.Nanos != 0) {
Nanos = other.Nanos;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Seconds = input.ReadInt64();
break;
}
case 16: {
Nanos = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Hwi;
using WalletWasabi.Hwi.Models;
using WalletWasabi.Hwi.Parsers;
using WalletWasabi.Hwi.ProcessBridge;
using Xunit;
using WalletWasabi.Helpers;
namespace WalletWasabi.Tests.UnitTests.Hwi
{
/// <summary>
/// Tests to run without connecting any hardware wallet to the computer.
/// </summary>
/// <seealso cref="XunitConfiguration.SerialCollectionDefinition"/>
[Collection("Serial unit tests collection")]
public class DefaultResponseTests
{
#region SharedVariables
// Bottleneck: Windows CI.
public TimeSpan ReasonableRequestTimeout { get; } = TimeSpan.FromMinutes(1);
#endregion SharedVariables
#region Tests
[Theory]
[MemberData(nameof(GetDifferentNetworkValues))]
public void CanCreate(Network network)
{
new HwiClient(network);
}
[Fact]
public void ConstructorThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new HwiClient(null!));
}
[Theory]
[MemberData(nameof(GetHwiClientConfigurationCombinationValues))]
public async Task GetVersionTestsAsync(HwiClient client)
{
using var cts = new CancellationTokenSource(ReasonableRequestTimeout);
Version version = await client.GetVersionAsync(cts.Token);
Assert.Equal(Constants.HwiVersion, version);
}
[Theory]
[MemberData(nameof(GetHwiClientConfigurationCombinationValues))]
public async Task GetHelpTestsAsync(HwiClient client)
{
using var cts = new CancellationTokenSource(ReasonableRequestTimeout);
string help = await client.GetHelpAsync(cts.Token);
Assert.NotEmpty(help);
}
[Theory]
[MemberData(nameof(GetHwiClientConfigurationCombinationValues))]
public async Task CanEnumerateAsync(HwiClient client)
{
using var cts = new CancellationTokenSource(ReasonableRequestTimeout);
IEnumerable<HwiEnumerateEntry> enumerate = await client.EnumerateAsync(cts.Token);
Assert.Empty(enumerate);
}
[Theory]
[MemberData(nameof(GetHwiClientConfigurationCombinationValues))]
public async Task ThrowOperationCanceledExceptionsAsync(HwiClient client)
{
using var cts = new CancellationTokenSource();
cts.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(async () => await client.GetVersionAsync(cts.Token));
await Assert.ThrowsAsync<OperationCanceledException>(async () => await client.GetHelpAsync(cts.Token));
await Assert.ThrowsAsync<OperationCanceledException>(async () => await client.EnumerateAsync(cts.Token));
}
[Theory]
[MemberData(nameof(GetHwiClientConfigurationCombinationValues))]
public async Task ThrowArgumentExceptionsForWrongDevicePathAsync(HwiClient client)
{
var wrongDeviePaths = new[] { "", " " };
using var cts = new CancellationTokenSource(ReasonableRequestTimeout);
foreach (HardwareWalletModels deviceType in Enum.GetValues(typeof(HardwareWalletModels)).Cast<HardwareWalletModels>())
{
foreach (var wrongDevicePath in wrongDeviePaths)
{
await Assert.ThrowsAsync<ArgumentException>(async () => await client.WipeAsync(deviceType, wrongDevicePath, cts.Token));
await Assert.ThrowsAsync<ArgumentException>(async () => await client.SetupAsync(deviceType, wrongDevicePath, false, cts.Token));
}
await Assert.ThrowsAsync<ArgumentNullException>(async () => await client.WipeAsync(deviceType, null!, cts.Token));
await Assert.ThrowsAsync<ArgumentNullException>(async () => await client.SetupAsync(deviceType, null!, false, cts.Token));
}
}
[Theory]
[MemberData(nameof(GetHwiClientConfigurationCombinationValues))]
public async Task CanCallAsynchronouslyAsync(HwiClient client)
{
using var cts = new CancellationTokenSource();
var tasks = new List<Task>
{
client.GetVersionAsync(cts.Token),
client.GetVersionAsync(cts.Token),
client.GetHelpAsync(cts.Token),
client.GetHelpAsync(cts.Token),
client.EnumerateAsync(cts.Token),
client.EnumerateAsync(cts.Token)
};
cts.CancelAfter(ReasonableRequestTimeout * tasks.Count);
await Task.WhenAny(tasks);
}
[Fact]
public async Task OpenConsoleDoesntThrowAsync()
{
HwiProcessBridge pb = new();
using var cts = new CancellationTokenSource(ReasonableRequestTimeout);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var res = await pb.SendCommandAsync("version", openConsole: true, cts.Token);
Assert.Contains("success", res.response);
}
else
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(async () => await pb.SendCommandAsync("enumerate", openConsole: true, cts.Token));
}
}
[Theory]
[InlineData("", false)]
[InlineData("hwi", false)]
[InlineData("hwi ", false)]
[InlineData("hwi 1", false)]
[InlineData("hwi 1.", false)]
[InlineData("hwi 1.1", false)]
[InlineData("hwi 1.1.", false)]
[InlineData("hwi 1.1.2\n", true)]
[InlineData("hwi 1.1.2", true)]
[InlineData("hwi 1.1.2-rc1\n", true)]
[InlineData("hwi 1.1.2-rc1", true)]
[InlineData("hwi.exe 1.1.2\n", true)]
[InlineData("hwi.exe 1.1.2", true)]
[InlineData("hwi.exe 1.1.2-", true)]
[InlineData("hwi.exe 1.1.2-rc1\n", true)]
[InlineData("hwi.exe 1.1.2-rc1", true)]
[InlineData("1.1.2-rc1\n", false)]
[InlineData("1.1-rc1\n", false)]
public void TryParseVersionTests(string input, bool isParsable)
{
Version expectedVersion = new Version(1, 1, 2);
Assert.Equal(isParsable, HwiParser.TryParseVersion(input, out Version? actualVersion));
if (isParsable)
{
Assert.Equal(expectedVersion, actualVersion);
}
}
#endregion Tests
#region HelperMethods
public static IEnumerable<object[]> GetDifferentNetworkValues()
{
var networks = new List<Network>
{
Network.Main,
Network.TestNet,
Network.RegTest
};
foreach (Network network in networks)
{
yield return new object[] { network };
}
}
public static IEnumerable<object[]> GetHwiClientConfigurationCombinationValues()
{
var networks = new List<Network>
{
Network.Main,
Network.TestNet,
Network.RegTest
};
foreach (Network network in networks)
{
yield return new object[] { new HwiClient(network) };
}
}
#endregion HelperMethods
/// <summary>Verify that <c>--version</c> argument returns output as expected.</summary>
[Fact]
public async Task HwiVersionTestAsync()
{
using var cts = new CancellationTokenSource(ReasonableRequestTimeout);
HwiProcessBridge pb = new();
// Start HWI with "version" argument and test that we get non-empty response.
(string response, int exitCode) result = await pb.SendCommandAsync("--version", openConsole: false, cts.Token);
Assert.Contains(Constants.HwiVersion.ToString(), result.response);
// Start HWI with "version" argument and test that we get non-empty response + verify that "standardInputWriter" is actually called.
bool stdInputActionCalled = false;
result = await pb.SendCommandAsync("--version", openConsole: false, cts.Token, (sw) => stdInputActionCalled = true);
Assert.Contains(Constants.HwiVersion.ToString(), result.response);
Assert.True(stdInputActionCalled);
}
/// <summary>Verify that <c>--help</c> returns output as expected.</summary>
[Fact]
public async void HwiHelpTestAsync()
{
using var cts = new CancellationTokenSource(ReasonableRequestTimeout);
HwiProcessBridge processBridge = new();
(string response, int exitCode) result = await processBridge.SendCommandAsync("--help", openConsole: false, cts.Token);
Assert.Equal(0, result.exitCode);
Assert.Equal(@"{""error"": ""Help text requested"", ""code"": -17}" + Environment.NewLine, result.response);
}
}
}
| |
// 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.Diagnostics;
using System.IO.PortsTests;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class DataBits_Property : PortsTest
{
//The default number of bytes to read/write to verify the speed of the port
//and that the bytes were transfered successfully
private const int DEFAULT_BYTE_SIZE = 256;
//If the percentage difference between the expected time to transfer with the specified dataBits
//and the actual time found through Stopwatch is greater then 5% then the DataBits value was not correctly
//set and the testcase fails.
private const double MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE = .05;
private const int NUM_TRYS = 5;
private enum ThrowAt { Set, Open };
#region Test Cases
[ConditionalFact(nameof(HasNullModem))]
public void DataBits_Default()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DataBits");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDataBits(com1, DEFAULT_BYTE_SIZE);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DataBits_7_BeforeOpen()
{
Debug.WriteLine("Verifying 7 DataBits before open");
VerifyDataBitsBeforeOpen(7, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void DataBits_8_BeforeOpen()
{
Debug.WriteLine("Verifying 8 DataBits before open");
VerifyDataBitsBeforeOpen(8, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void DataBits_7_AfterOpen()
{
Debug.WriteLine("Verifying 7 DataBits after open");
VerifyDataBitsAfterOpen(7, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void DataBits_8_AfterOpen()
{
Debug.WriteLine("Verifying 8 DataBits after open");
VerifyDataBitsAfterOpen(8, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void DataBits_Int32MinValue()
{
Debug.WriteLine("Verifying Int32.MinValue DataBits");
VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void DataBits_Neg8()
{
Debug.WriteLine("Verifying -8 DataBits");
VerifyException(-8, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void DataBits_Neg1()
{
Debug.WriteLine("Verifying -1 DataBits");
VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void DataBits_0()
{
Debug.WriteLine("Verifying 0 DataBits");
VerifyException(0, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void DataBits_1()
{
Debug.WriteLine("Verifying 1 DataBits");
VerifyException(1, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void DataBits_4()
{
Debug.WriteLine("Verifying 4 DataBits");
VerifyException(4, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void DataBits_9()
{
Debug.WriteLine("Verifying 9 DataBits");
VerifyException(9, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void DataBits_Int32MaxValue()
{
Debug.WriteLine("Verifying Int32.MaxValue DataBits");
VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
#endregion
#region Verification for Test Cases
private void VerifyException(int dataBits, ThrowAt throwAt, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
VerifyExceptionAtOpen(com, dataBits, throwAt, expectedException);
if (com.IsOpen)
com.Close();
VerifyExceptionAfterOpen(com, dataBits, expectedException);
}
}
private void VerifyExceptionAtOpen(SerialPort com, int dataBits, ThrowAt throwAt, Type expectedException)
{
int origDataBits = com.DataBits;
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
if (ThrowAt.Open == throwAt)
serPortProp.SetProperty("DataBits", dataBits);
try
{
com.DataBits = dataBits;
if (ThrowAt.Open == throwAt)
com.Open();
if (null != expectedException)
{
Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
com.DataBits = origDataBits;
}
private void VerifyExceptionAfterOpen(SerialPort com, int dataBits, Type expectedException)
{
SerialPortProperties serPortProp = new SerialPortProperties();
com.Open();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
try
{
com.DataBits = dataBits;
if (null != expectedException)
{
Fail("ERROR!!! Expected setting the DataBits after Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected setting the DataBits after Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected setting the DataBits after Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
}
private void VerifyDataBitsBeforeOpen(int dataBits, int numBytesToSend)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.DataBits = dataBits;
com1.Open();
serPortProp.SetProperty("DataBits", dataBits);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDataBits(com1, numBytesToSend);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyDataBitsAfterOpen(int dataBits, int numBytesToSend)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.DataBits = dataBits;
serPortProp.SetProperty("DataBits", dataBits);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDataBits(com1, numBytesToSend);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyDataBits(SerialPort com1, int numBytesToSend)
{
byte[] xmitBytes = new byte[numBytesToSend];
byte[] expectedBytes = new byte[numBytesToSend];
byte[] rcvBytes = new byte[numBytesToSend];
Random rndGen = new Random();
Stopwatch sw = new Stopwatch();
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
double expectedTime, actualTime, percentageDifference;
int numBytes = 0;
byte shiftMask = 0xFF;
//Create a mask that when logicaly and'd with the transmitted byte will
//will result in the byte recievied due to the leading bits being chopped
//off due to DataBits less then 8
shiftMask >>= 8 - com1.DataBits;
//Generate some random bytes to read/write for this DataBits setting
for (int i = 0; i < xmitBytes.Length; i++)
{
xmitBytes[i] = (byte)rndGen.Next(0, 256);
expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask);
}
com2.DataBits = com1.DataBits;
com2.Open();
actualTime = 0;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
IAsyncResult beginWriteResult;
int bytesToRead = 0;
com2.DiscardInBuffer();
beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, xmitBytes.Length, null, null);
while (0 == (bytesToRead = com2.BytesToRead))
{
}
sw.Start();
while (numBytesToSend > com2.BytesToRead)
{
//Wait for all of the bytes to reach the input buffer of com2
}
sw.Stop();
actualTime += sw.ElapsedMilliseconds;
actualTime += ((bytesToRead * (2.0 + com1.DataBits)) / com1.BaudRate) * 1000;
beginWriteResult.AsyncWaitHandle.WaitOne();
sw.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
expectedTime = ((xmitBytes.Length * (2.0 + com1.DataBits)) / com1.BaudRate) * 1000;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime);
//If the percentageDifference between the expected time and the actual time is to high
//then the expected baud rate must not have been used and we should report an error
if (MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE < percentageDifference)
{
Fail("ERROR!!! DataBits not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference, numBytes);
}
com2.Read(rcvBytes, 0, rcvBytes.Length);
}
//Verify that the bytes we sent were the same ones we received
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], rcvBytes[i]);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Ocsp;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Ocsp
{
/**
* Generator for basic OCSP response objects.
*/
public class BasicOcspRespGenerator
{
private readonly IList list = Platform.CreateArrayList();
private X509Extensions responseExtensions;
private RespID responderID;
private class ResponseObject
{
internal CertificateID certId;
internal CertStatus certStatus;
internal DerGeneralizedTime thisUpdate;
internal DerGeneralizedTime nextUpdate;
internal X509Extensions extensions;
public ResponseObject(
CertificateID certId,
CertificateStatus certStatus,
DateTime thisUpdate,
X509Extensions extensions)
: this(certId, certStatus, new DerGeneralizedTime(thisUpdate), null, extensions)
{
}
public ResponseObject(
CertificateID certId,
CertificateStatus certStatus,
DateTime thisUpdate,
DateTime nextUpdate,
X509Extensions extensions)
: this(certId, certStatus, new DerGeneralizedTime(thisUpdate), new DerGeneralizedTime(nextUpdate), extensions)
{
}
private ResponseObject(
CertificateID certId,
CertificateStatus certStatus,
DerGeneralizedTime thisUpdate,
DerGeneralizedTime nextUpdate,
X509Extensions extensions)
{
this.certId = certId;
if (certStatus == null)
{
this.certStatus = new CertStatus();
}
else if (certStatus is UnknownStatus)
{
this.certStatus = new CertStatus(2, DerNull.Instance);
}
else
{
RevokedStatus rs = (RevokedStatus) certStatus;
CrlReason revocationReason = rs.HasRevocationReason
? new CrlReason(rs.RevocationReason)
: null;
this.certStatus = new CertStatus(
new RevokedInfo(new DerGeneralizedTime(rs.RevocationTime), revocationReason));
}
this.thisUpdate = thisUpdate;
this.nextUpdate = nextUpdate;
this.extensions = extensions;
}
public SingleResponse ToResponse()
{
return new SingleResponse(certId.ToAsn1Object(), certStatus, thisUpdate, nextUpdate, extensions);
}
}
/**
* basic constructor
*/
public BasicOcspRespGenerator(
RespID responderID)
{
this.responderID = responderID;
}
/**
* construct with the responderID to be the SHA-1 keyHash of the passed in public key.
*/
public BasicOcspRespGenerator(
IAsymmetricKeyParameter publicKey)
{
this.responderID = new RespID(publicKey);
}
/**
* Add a response for a particular Certificate ID.
*
* @param certID certificate ID details
* @param certStatus status of the certificate - null if okay
*/
public void AddResponse(
CertificateID certID,
CertificateStatus certStatus)
{
list.Add(new ResponseObject(certID, certStatus, DateTime.UtcNow, null));
}
/**
* Add a response for a particular Certificate ID.
*
* @param certID certificate ID details
* @param certStatus status of the certificate - null if okay
* @param singleExtensions optional extensions
*/
public void AddResponse(
CertificateID certID,
CertificateStatus certStatus,
X509Extensions singleExtensions)
{
list.Add(new ResponseObject(certID, certStatus, DateTime.UtcNow, singleExtensions));
}
/**
* Add a response for a particular Certificate ID.
*
* @param certID certificate ID details
* @param nextUpdate date when next update should be requested
* @param certStatus status of the certificate - null if okay
* @param singleExtensions optional extensions
*/
public void AddResponse(
CertificateID certID,
CertificateStatus certStatus,
DateTime nextUpdate,
X509Extensions singleExtensions)
{
list.Add(new ResponseObject(certID, certStatus, DateTime.UtcNow, nextUpdate, singleExtensions));
}
/**
* Add a response for a particular Certificate ID.
*
* @param certID certificate ID details
* @param thisUpdate date this response was valid on
* @param nextUpdate date when next update should be requested
* @param certStatus status of the certificate - null if okay
* @param singleExtensions optional extensions
*/
public void AddResponse(
CertificateID certID,
CertificateStatus certStatus,
DateTime thisUpdate,
DateTime nextUpdate,
X509Extensions singleExtensions)
{
list.Add(new ResponseObject(certID, certStatus, thisUpdate, nextUpdate, singleExtensions));
}
/**
* Set the extensions for the response.
*
* @param responseExtensions the extension object to carry.
*/
public void SetResponseExtensions(
X509Extensions responseExtensions)
{
this.responseExtensions = responseExtensions;
}
private BasicOcspResp GenerateResponse(
string signatureName,
IAsymmetricKeyParameter privateKey,
X509Certificate[] chain,
DateTime producedAt,
SecureRandom random)
{
DerObjectIdentifier signingAlgorithm;
try
{
signingAlgorithm = OcspUtilities.GetAlgorithmOid(signatureName);
}
catch (Exception e)
{
throw new ArgumentException("unknown signing algorithm specified", e);
}
Asn1EncodableVector responses = new Asn1EncodableVector();
foreach (ResponseObject respObj in list)
{
try
{
responses.Add(respObj.ToResponse());
}
catch (Exception e)
{
throw new OcspException("exception creating Request", e);
}
}
ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);
ISigner sig = null;
try
{
sig = SignerUtilities.GetSigner(signatureName);
if (random != null)
{
sig.Init(true, new ParametersWithRandom(privateKey, random));
}
else
{
sig.Init(true, privateKey);
}
}
catch (Exception e)
{
throw new OcspException("exception creating signature: " + e, e);
}
DerBitString bitSig = null;
try
{
byte[] encoded = tbsResp.GetDerEncoded();
sig.BlockUpdate(encoded, 0, encoded.Length);
bitSig = new DerBitString(sig.GenerateSignature());
}
catch (Exception e)
{
throw new OcspException("exception processing TBSRequest: " + e, e);
}
AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);
DerSequence chainSeq = null;
if (chain != null && chain.Length > 0)
{
Asn1EncodableVector v = new Asn1EncodableVector();
try
{
for (int i = 0; i != chain.Length; i++)
{
v.Add(
X509CertificateStructure.GetInstance(
Asn1Object.FromByteArray(chain[i].GetEncoded())));
}
}
catch (IOException e)
{
throw new OcspException("error processing certs", e);
}
catch (CertificateEncodingException e)
{
throw new OcspException("error encoding certs", e);
}
chainSeq = new DerSequence(v);
}
return new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq));
}
public BasicOcspResp Generate(
string signingAlgorithm,
IAsymmetricKeyParameter privateKey,
X509Certificate[] chain,
DateTime thisUpdate)
{
return Generate(signingAlgorithm, privateKey, chain, thisUpdate, null);
}
public BasicOcspResp Generate(
string signingAlgorithm,
IAsymmetricKeyParameter privateKey,
X509Certificate[] chain,
DateTime producedAt,
SecureRandom random)
{
if (signingAlgorithm == null)
{
throw new ArgumentException("no signing algorithm specified");
}
return GenerateResponse(signingAlgorithm, privateKey, chain, producedAt, random);
}
/**
* Return an IEnumerable of the signature names supported by the generator.
*
* @return an IEnumerable containing recognised names.
*/
public IEnumerable SignatureAlgNames
{
get { return OcspUtilities.AlgNames; }
}
}
}
| |
using System;
using System.Threading;
using System.IO;
using Sce.PlayStation.HighLevel.UI;
using Sce.PlayStation.Core.Graphics;
using Sce.PlayStation.Core.Imaging;
using Sample;
namespace Avi_Movie_Player
{
public enum State
{
None,
Play,
Pause,
Resume,
Stop
}
public class StateEventArgs : EventArgs
{
public State Status;
}
public class ErrorEventArgs : EventArgs
{
public String Message;
}
public class MoviePlayer : IDisposable
{
// singleton
private static MoviePlayer instance = new MoviePlayer();
private static Movie movie;
public State Status = State.None;
private Uri targetUri;
private String fileName;
private HttpRequestUtil requestUtil;
private DateTime m_BaseTime;
private DateTime m_PauseTime;
private GraphicsContext sm_GraphicsContext = null;
private Texture2D sm_Texture2D = null;
private SampleSprite sm_SampleSprite = null;
// Buffer for Sprite (Atmic)
static object sm_LockObjectForBuffer = new object();
static byte[] sm_Buffer = null;
static byte[] Buffer {
get {
lock (sm_LockObjectForBuffer) {
return sm_Buffer;
}
}
set {
lock (sm_LockObjectForBuffer) {
sm_Buffer = value;
}
}
}
// for synchronization
private bool isInitialized;
public delegate void StateEventHandler(object sender, StateEventArgs e);
public delegate void ErrorEventHandler(object sender, ErrorEventArgs e);
public event StateEventHandler StateChanged;
public event ErrorEventHandler ErrorOccurred;
public static MoviePlayer getInstance(Movie movie) {
MoviePlayer.movie = movie;
return instance;
}
private MoviePlayer ()
{
requestUtil = new HttpRequestUtil();
requestUtil.Completed += this.startMovie;
requestUtil.ErrorOccurred += this.applyNetworkError;
}
public void Dispose() {
Term();
}
public void Play(String uri) {
if (Status != State.Play) {
try {
this.targetUri = new Uri(uri);
} catch(System.UriFormatException ure) {
sendErrorOccurred(ure.Message);
return;
}
this.fileName = targetUri.Segments[targetUri.Segments.Length - 1];
if (Status == State.None || Status == State.Stop) {
String outputDir = movie.OutputDir;
if (targetUri.Scheme == "http") {
movie.MovieFileDir = outputDir;
requestUtil.DownloadFile(targetUri, outputDir + "/" + fileName);
} else if (this.targetUri.Scheme == "file") {
String filePath = targetUri.AbsolutePath;
int fIndex = filePath.LastIndexOf("/" + fileName);
movie.MovieFileDir = filePath.Substring(0, fIndex);
Thread thread = new Thread(new ThreadStart(startMovie));
thread.Start();
} else {
sendErrorOccurred("This scheme is unknown.: " + targetUri.Scheme);
return;
}
}
}
return ;
}
public void Stop() {
if (Status != State.Stop && Status != State.None) {
movie.AudioStop();
TermSampleSprite();
TermTexture2D();
isInitialized = false;
Status = State.Stop;
sendStatusChanged();
}
return ;
}
public void Pause() {
if (Status == State.Play || Status == State.Resume) {
movie.AudioPause();
m_PauseTime = DateTime.Now;
Status = State.Pause;
sendStatusChanged();
}
return;
}
public void Resume() {
if (Status == State.Pause) {
movie.AudioResume();
m_BaseTime += DateTime.Now - m_PauseTime;
Status = State.Resume;
sendStatusChanged();
}
return;
}
public void Init(GraphicsContext graphicsContext) {
Status = State.None;
sm_GraphicsContext = graphicsContext;
InitSampleDraw();
}
public void Update()
{
MovieThreadUtil.Run();
if (!isInitialized && Status == State.Play) {
InitTexture2D();
InitSampleSprite();
movie.AudioPlay();
isInitialized = true;
}
if (Status == State.Play || Status == State.Resume) {
SampleDraw.Update();
UpdateTexture2D();
}
}
public void Render()
{
if (Status == State.Play || Status == State.Resume || Status == State.Pause) {
RenderSprite();
}
}
public void Term()
{
TermTexture2D();
TermSampleSprite();
TermSampleDraw();
}
////////////////////////////////////////////////////////////////
public void InitSampleDraw()
{
if (null == sm_GraphicsContext) {
return;
}
SampleDraw.Init(sm_GraphicsContext);
}
public void TermSampleDraw()
{
SampleDraw.Term();
}
////////////////////////////////////////////////////////////////
public void InitTexture2D()
{
TermTexture2D();
sm_Texture2D = new Texture2D(movie.Width, movie.Height, false, PixelFormat.Rgba);
// Rgba8888 : 4 bytes per pixel
// Rgb565 : 2 bytes per pixel
var bytesCount = movie.Width * movie.Height * 4;
Buffer = new byte[bytesCount];
sm_Texture2D.SetPixels(0, Buffer);
}
public void UpdateTexture2D()
{
if (null == sm_Texture2D)
{
return;
}
if (null == Buffer)
{
return;
}
DateTime now = DateTime.Now;
long ival_100ns = now.Ticks - m_BaseTime.Ticks;
int index = (int)((ival_100ns / 10000000.0) / (movie.MicroSecPerFrame / 1000000.0));
if (movie.TotalFrames <= index) {
index = movie.TotalFrames -1;
}
AviOldIndexEntry entry = movie.VideoEntryList[index];
int size = entry.Size;
int offset = entry.Offset;
BinaryReader reader = new BinaryReader(File.OpenRead(movie.MovieFileDir + "/" + fileName));
reader.BaseStream.Seek(movie.MoviIndex + 4 + 4 + offset, SeekOrigin.Begin);
byte[] tmp = reader.ReadBytes(size);
reader.Close();
reader.Dispose();
if (tmp.Length != 0) {
Image img = new Image(tmp);
img.Decode();
Buffer = img.ToBuffer();
sm_Texture2D.SetPixels(0, Buffer);
img.Dispose();
}
}
public void TermTexture2D()
{
if (null == sm_Texture2D)
{
return;
}
sm_Texture2D.Dispose();
sm_Texture2D = null;
}
////////////////////////////////////////////////////////////////
public void InitSampleSprite()
{
if (null == sm_Texture2D) {
return;
}
if (0 >= sm_Texture2D.Width || 0 >= sm_Texture2D.Height) {
return;
}
TermSampleSprite();
var positionX = (SampleDraw.Width - sm_Texture2D.Width) / 2;
var positionY = (SampleDraw.Height - sm_Texture2D.Height) / 2;
var scale =
Math.Min(
(float)SampleDraw.Width / sm_Texture2D.Width,
(float)SampleDraw.Height / sm_Texture2D.Height);
sm_SampleSprite = new SampleSprite(sm_Texture2D, positionX, positionY, 0, scale);
}
public void RenderSprite()
{
if (null == sm_GraphicsContext) {
return;
}
if (null == sm_SampleSprite) {
return;
}
SampleDraw.DrawSprite(sm_SampleSprite);
}
public void TermSampleSprite()
{
if (null == sm_SampleSprite) {
return;
}
sm_SampleSprite.Dispose();
sm_SampleSprite = null;
}
////////////////////////////////////////////////////////////////
private void startMovie(object sender, EventArgs e) {
startMovie();
}
private void applyNetworkError(object sender, ErrorEventArgs e) {
sendErrorOccurred(e.Message);
}
private void startMovie() {
bool isRead = movie.ReadLocalMovie(movie.MovieFileDir + "/" + fileName);
if (!isRead) {
sendErrorOccurred("Local movie file is not found.");
return;
}
m_BaseTime = DateTime.Now;
Status = State.Play;
sendStatusChanged();
}
private void sendStatusChanged() {
StateEventArgs e = new StateEventArgs();
e.Status = Status;
MovieThreadUtil.InvokeLator(OnStateChanged, e);
}
private void sendErrorOccurred(String message) {
ErrorEventArgs e = new ErrorEventArgs();
e.Message = message;
MovieThreadUtil.InvokeLator(OnErrorOccurred, e);
}
private void OnStateChanged(StateEventArgs e) {
if (StateChanged != null) {
StateChanged(this, e);
}
}
private void OnErrorOccurred(ErrorEventArgs e) {
if (ErrorOccurred != null) {
ErrorOccurred(this, e);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Manage.Internal
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[IdentityDefaultUI(typeof(EnableAuthenticatorModel<>))]
public class EnableAuthenticatorModel : PageModel
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public string SharedKey { get; set; }
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public string AuthenticatorUri { get; set; }
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[TempData]
public string[] RecoveryCodes { get; set; }
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[TempData]
public string StatusMessage { get; set; }
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[BindProperty]
public InputModel Input { get; set; }
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class InputModel
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Required]
[StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Text)]
[Display(Name = "Verification Code")]
public string Code { get; set; }
}
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual Task<IActionResult> OnGetAsync() => throw new NotImplementedException();
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual Task<IActionResult> OnPostAsync() => throw new NotImplementedException();
}
internal class EnableAuthenticatorModel<TUser> : EnableAuthenticatorModel where TUser : class
{
private readonly UserManager<TUser> _userManager;
private readonly ILogger<EnableAuthenticatorModel> _logger;
private readonly UrlEncoder _urlEncoder;
private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";
public EnableAuthenticatorModel(
UserManager<TUser> userManager,
ILogger<EnableAuthenticatorModel> logger,
UrlEncoder urlEncoder)
{
_userManager = userManager;
_logger = logger;
_urlEncoder = urlEncoder;
}
public override async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadSharedKeyAndQrCodeUriAsync(user);
return Page();
}
public override async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadSharedKeyAndQrCodeUriAsync(user);
return Page();
}
// Strip spaces and hyphens
var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
if (!is2faTokenValid)
{
ModelState.AddModelError("Input.Code", "Verification code is invalid.");
await LoadSharedKeyAndQrCodeUriAsync(user);
return Page();
}
await _userManager.SetTwoFactorEnabledAsync(user, true);
var userId = await _userManager.GetUserIdAsync(user);
_logger.LogInformation(LoggerEventIds.TwoFAEnabled, "User has enabled 2FA with an authenticator app.");
StatusMessage = "Your authenticator app has been verified.";
if (await _userManager.CountRecoveryCodesAsync(user) == 0)
{
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
RecoveryCodes = recoveryCodes.ToArray();
return RedirectToPage("./ShowRecoveryCodes");
}
else
{
return RedirectToPage("./TwoFactorAuthentication");
}
}
private async Task LoadSharedKeyAndQrCodeUriAsync(TUser user)
{
// Load the authenticator key & QR code URI to display on the form
var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
if (string.IsNullOrEmpty(unformattedKey))
{
await _userManager.ResetAuthenticatorKeyAsync(user);
unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
}
SharedKey = FormatKey(unformattedKey);
var email = await _userManager.GetEmailAsync(user);
AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
}
private string FormatKey(string unformattedKey)
{
var result = new StringBuilder();
int currentPosition = 0;
while (currentPosition + 4 < unformattedKey.Length)
{
result.Append(unformattedKey.AsSpan(currentPosition, 4)).Append(' ');
currentPosition += 4;
}
if (currentPosition < unformattedKey.Length)
{
result.Append(unformattedKey.AsSpan(currentPosition));
}
return result.ToString().ToLowerInvariant();
}
private string GenerateQrCodeUri(string email, string unformattedKey)
{
return string.Format(
CultureInfo.InvariantCulture,
AuthenticatorUriFormat,
_urlEncoder.Encode("Microsoft.AspNetCore.Identity.UI"),
_urlEncoder.Encode(email),
unformattedKey);
}
}
}
| |
/*
Copyright (c) 2005-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Web;
using System.Xml;
using System.Collections;
using System.Configuration;
using PHP.Core;
using System.Diagnostics;
namespace PHP.Library.Xml
{
#region Local Configuration
/// <summary>
/// Script independent Zlib configuration.
/// </summary>
[Serializable]
public sealed class XmlLocalConfig : IPhpConfiguration, IPhpConfigurationSection
{
internal XmlLocalConfig() { }
/// <summary>
/// Creates a deep copy of the configuration record.
/// </summary>
/// <returns>The copy.</returns>
public IPhpConfiguration DeepCopy()
{
return (XmlLocalConfig)this.MemberwiseClone();
}
/// <summary>
/// Loads configuration from XML.
/// </summary>
public bool Parse(string name, string value, XmlNode node)
{
switch (name)
{
default:
return false;
}
//return true;
}
}
#endregion
#region Global Configuration
/// <summary>
/// Script dependent MSSQL configuration.
/// </summary>
[Serializable]
public sealed class XmlGlobalConfig : IPhpConfiguration, IPhpConfigurationSection
{
internal XmlGlobalConfig() { }
/// <summary>
/// Loads configuration from XML.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="node"></param>
/// <returns></returns>
public bool Parse(string name, string value, XmlNode node)
{
switch (name)
{
default:
return false;
}
//return true;
}
/// <summary>
/// Creates a deep copy of the configuration record.
/// </summary>
/// <returns>The copy.</returns>
public IPhpConfiguration DeepCopy()
{
return (XmlGlobalConfig)this.MemberwiseClone();
}
}
#endregion
/// <summary>
/// Zlib extension configuration.
/// </summary>
public static class XmlConfiguration
{
#region Legacy Configuration
/// <summary>
/// Gets, sets, or restores a value of a legacy configuration option.
/// </summary>
private static object GetSetRestore(LocalConfiguration config, string option, object value, IniAction action)
{
XmlLocalConfig local = (XmlLocalConfig)config.GetLibraryConfig(XmlLibraryDescriptor.Singleton);
XmlLocalConfig @default = DefaultLocal;
XmlGlobalConfig global = Global;
//switch (option)
//{
//// local:
//case "mssql.connect_timeout":
//return PhpIni.GSR(ref local.ConnectTimeout, @default.ConnectTimeout, value, action);
//case "mssql.timeout":
//return PhpIni.GSR(ref local.Timeout, @default.Timeout, value, action);
//case "mssql.batchsize":
//return PhpIni.GSR(ref local.BatchSize, @default.BatchSize, value, action);
//// global:
//case "mssql.max_links":
//Debug.Assert(action == IniAction.Get);
//return PhpIni.GSR(ref global.MaxConnections, 0, null, action);
//case "mssql.secure_connection":
//Debug.Assert(action == IniAction.Get);
//return PhpIni.GSR(ref global.NTAuthentication, false, null, action);
//}
Debug.Fail("Option '" + option + "' is supported but not implemented.");
return null;
}
/// <summary>
/// Writes MySql legacy options and their values to XML text stream.
/// Skips options whose values are the same as default values of Phalanger.
/// </summary>
/// <param name="writer">XML writer.</param>
/// <param name="options">A hashtable containing PHP names and option values. Consumed options are removed from the table.</param>
/// <param name="writePhpNames">Whether to add "phpName" attribute to option nodes.</param>
public static void LegacyOptionsToXml(XmlTextWriter writer, Hashtable options, bool writePhpNames) // GENERICS:<string,string>
{
if (writer == null)
throw new ArgumentNullException("writer");
if (options == null)
throw new ArgumentNullException("options");
XmlLocalConfig local = new XmlLocalConfig();
XmlGlobalConfig global = new XmlGlobalConfig();
PhpIniXmlWriter ow = new PhpIniXmlWriter(writer, options, writePhpNames);
ow.StartSection("zlib");
//// local:
//ow.WriteOption("mssql.connect_timeout", "ConnectTimeout", 5, local.ConnectTimeout);
//ow.WriteOption("mssql.timeout", "Timeout", 60, local.Timeout);
//ow.WriteOption("mssql.batchsize", "BatchSize", 0, local.BatchSize);
//// global:
//ow.WriteOption("mssql.max_links", "MaxConnections", -1, global.MaxConnections);
//ow.WriteOption("mssql.secure_connection", "NTAuthentication", false, global.NTAuthentication);
ow.WriteEnd();
}
/// <summary>
/// Registers legacy ini-options.
/// </summary>
internal static void RegisterLegacyOptions()
{
//const string s = ZlibLibraryDescriptor.ExtensionName;
//GetSetRestoreDelegate d = new GetSetRestoreDelegate(GetSetRestore);
//// global:
//IniOptions.Register("mssql.max_links", IniFlags.Supported | IniFlags.Global, d, s);
//IniOptions.Register("mssql.secure_connection", IniFlags.Supported | IniFlags.Global, d, s);
//IniOptions.Register("mssql.allow_persistent", IniFlags.Unsupported | IniFlags.Global, d, s);
//IniOptions.Register("mssql.max_persistent", IniFlags.Unsupported | IniFlags.Global, d, s);
//// local:
//IniOptions.Register("mssql.connect_timeout", IniFlags.Supported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.timeout", IniFlags.Supported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.batchsize", IniFlags.Supported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.min_error_severity", IniFlags.Unsupported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.min_message_severity", IniFlags.Unsupported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.compatability_mode", IniFlags.Unsupported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.textsize", IniFlags.Unsupported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.textlimit", IniFlags.Unsupported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.datetimeconvert", IniFlags.Unsupported | IniFlags.Local, d, s);
//IniOptions.Register("mssql.max_procs", IniFlags.Unsupported | IniFlags.Local, d, s);
}
#endregion
#region Configuration Getters
/// <summary>
/// Gets the library configuration associated with the current script context.
/// </summary>
public static XmlLocalConfig Local
{
get
{
return (XmlLocalConfig)Configuration.Local.GetLibraryConfig(XmlLibraryDescriptor.Singleton);
}
}
/// <summary>
/// Gets the default library configuration.
/// </summary>
public static XmlLocalConfig DefaultLocal
{
get
{
return (XmlLocalConfig)Configuration.DefaultLocal.GetLibraryConfig(XmlLibraryDescriptor.Singleton);
}
}
/// <summary>
/// Gets the global library configuration.
/// </summary>
public static XmlGlobalConfig Global
{
get
{
return (XmlGlobalConfig)Configuration.Global.GetLibraryConfig(XmlLibraryDescriptor.Singleton);
}
}
/// <summary>
/// Gets local configuration associated with a specified script context.
/// </summary>
/// <param name="context">Scritp context.</param>
/// <returns>Local library configuration.</returns>
public static XmlLocalConfig GetLocal(ScriptContext/*!*/ context)
{
if (context == null)
throw new ArgumentNullException("context");
return (XmlLocalConfig)context.Config.GetLibraryConfig(XmlLibraryDescriptor.Singleton);
}
#endregion
}
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.CloudFormation.Model
{
/// <summary>
/// <para>The StackResource data type.</para>
/// </summary>
public class StackResource
{
private string stackName;
private string stackId;
private string logicalResourceId;
private string physicalResourceId;
private string resourceType;
private DateTime? timestamp;
private string resourceStatus;
private string resourceStatusReason;
private string description;
/// <summary>
/// The name associated with the stack.
///
/// </summary>
public string StackName
{
get { return this.stackName; }
set { this.stackName = value; }
}
/// <summary>
/// Sets the StackName property
/// </summary>
/// <param name="stackName">The value to set for the StackName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithStackName(string stackName)
{
this.stackName = stackName;
return this;
}
// Check to see if StackName property is set
internal bool IsSetStackName()
{
return this.stackName != null;
}
/// <summary>
/// Unique identifier of the stack.
///
/// </summary>
public string StackId
{
get { return this.stackId; }
set { this.stackId = value; }
}
/// <summary>
/// Sets the StackId property
/// </summary>
/// <param name="stackId">The value to set for the StackId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithStackId(string stackId)
{
this.stackId = stackId;
return this;
}
// Check to see if StackId property is set
internal bool IsSetStackId()
{
return this.stackId != null;
}
/// <summary>
/// The logical name of the resource specified in the template.
///
/// </summary>
public string LogicalResourceId
{
get { return this.logicalResourceId; }
set { this.logicalResourceId = value; }
}
/// <summary>
/// Sets the LogicalResourceId property
/// </summary>
/// <param name="logicalResourceId">The value to set for the LogicalResourceId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithLogicalResourceId(string logicalResourceId)
{
this.logicalResourceId = logicalResourceId;
return this;
}
// Check to see if LogicalResourceId property is set
internal bool IsSetLogicalResourceId()
{
return this.logicalResourceId != null;
}
/// <summary>
/// The name or unique identifier that corresponds to a physical instance ID of a resource supported by AWS CloudFormation.
///
/// </summary>
public string PhysicalResourceId
{
get { return this.physicalResourceId; }
set { this.physicalResourceId = value; }
}
/// <summary>
/// Sets the PhysicalResourceId property
/// </summary>
/// <param name="physicalResourceId">The value to set for the PhysicalResourceId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithPhysicalResourceId(string physicalResourceId)
{
this.physicalResourceId = physicalResourceId;
return this;
}
// Check to see if PhysicalResourceId property is set
internal bool IsSetPhysicalResourceId()
{
return this.physicalResourceId != null;
}
/// <summary>
/// Type of the resource. (For more information, go to the <a href="http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide">AWS
/// CloudFormation User Guide</a>.)
///
/// </summary>
public string ResourceType
{
get { return this.resourceType; }
set { this.resourceType = value; }
}
/// <summary>
/// Sets the ResourceType property
/// </summary>
/// <param name="resourceType">The value to set for the ResourceType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithResourceType(string resourceType)
{
this.resourceType = resourceType;
return this;
}
// Check to see if ResourceType property is set
internal bool IsSetResourceType()
{
return this.resourceType != null;
}
/// <summary>
/// Time the status was updated.
///
/// </summary>
public DateTime Timestamp
{
get { return this.timestamp ?? default(DateTime); }
set { this.timestamp = value; }
}
/// <summary>
/// Sets the Timestamp property
/// </summary>
/// <param name="timestamp">The value to set for the Timestamp property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithTimestamp(DateTime timestamp)
{
this.timestamp = timestamp;
return this;
}
// Check to see if Timestamp property is set
internal bool IsSetTimestamp()
{
return this.timestamp.HasValue;
}
/// <summary>
/// Current status of the resource.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>CREATE_IN_PROGRESS, CREATE_FAILED, CREATE_COMPLETE, DELETE_IN_PROGRESS, DELETE_FAILED, DELETE_COMPLETE, UPDATE_IN_PROGRESS, UPDATE_FAILED, UPDATE_COMPLETE</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ResourceStatus
{
get { return this.resourceStatus; }
set { this.resourceStatus = value; }
}
/// <summary>
/// Sets the ResourceStatus property
/// </summary>
/// <param name="resourceStatus">The value to set for the ResourceStatus property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithResourceStatus(string resourceStatus)
{
this.resourceStatus = resourceStatus;
return this;
}
// Check to see if ResourceStatus property is set
internal bool IsSetResourceStatus()
{
return this.resourceStatus != null;
}
/// <summary>
/// Success/failure message associated with the resource.
///
/// </summary>
public string ResourceStatusReason
{
get { return this.resourceStatusReason; }
set { this.resourceStatusReason = value; }
}
/// <summary>
/// Sets the ResourceStatusReason property
/// </summary>
/// <param name="resourceStatusReason">The value to set for the ResourceStatusReason property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithResourceStatusReason(string resourceStatusReason)
{
this.resourceStatusReason = resourceStatusReason;
return this;
}
// Check to see if ResourceStatusReason property is set
internal bool IsSetResourceStatusReason()
{
return this.resourceStatusReason != null;
}
/// <summary>
/// User defined description associated with the resource.
///
/// </summary>
public string Description
{
get { return this.description; }
set { this.description = value; }
}
/// <summary>
/// Sets the Description property
/// </summary>
/// <param name="description">The value to set for the Description property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public StackResource WithDescription(string description)
{
this.description = description;
return this;
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this.description != null;
}
}
}
| |
using System;
using System.IO;
using System.Net;
using ServiceStack.Common.Web;
using ServiceStack.Service;
using ServiceStack.ServiceClient.Web;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Support.Mocks;
using ServiceStack.WebHost.Endpoints.Tests.Mocks;
namespace ServiceStack.WebHost.Endpoints.Tests.Support
{
public class DirectServiceClient : IServiceClient, IRestClient
{
ServiceManager ServiceManager { get; set; }
readonly HttpRequestMock httpReq = new HttpRequestMock();
readonly HttpResponseMock httpRes = new HttpResponseMock();
public DirectServiceClient(ServiceManager serviceManager)
{
this.ServiceManager = serviceManager;
}
public void SendOneWay(object request)
{
ServiceManager.Execute(request);
}
public void SendOneWay(string relativeOrAbsoluteUrl, object request)
{
ServiceManager.Execute(request);
}
private bool ApplyRequestFilters<TResponse>(object request)
{
if (EndpointHost.ApplyRequestFilters(httpReq, httpRes, request))
{
ThrowIfError<TResponse>(httpRes);
return true;
}
return false;
}
private void ThrowIfError<TResponse>(HttpResponseMock httpRes)
{
if (httpRes.StatusCode >= 400)
{
var webEx = new WebServiceException("WebServiceException, StatusCode: " + httpRes.StatusCode) {
StatusCode = httpRes.StatusCode,
StatusDescription = httpRes.StatusDescription,
};
try
{
var deserializer = EndpointHost.AppHost.ContentTypeFilters.GetStreamDeserializer(httpReq.ResponseContentType);
webEx.ResponseDto = deserializer(typeof(TResponse), httpRes.OutputStream);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
throw webEx;
}
}
private bool ApplyResponseFilters<TResponse>(object response)
{
if (EndpointHost.ApplyResponseFilters(httpReq, httpRes, response))
{
ThrowIfError<TResponse>(httpRes);
return true;
}
return false;
}
public TResponse Send<TResponse>(object request)
{
httpReq.HttpMethod = HttpMethods.Post;
if (ApplyRequestFilters<TResponse>(request)) return default(TResponse);
var response = ServiceManager.ServiceController.Execute(request,
new HttpRequestContext(httpReq, httpRes, request, EndpointAttributes.HttpPost));
if (ApplyResponseFilters<TResponse>(response)) return (TResponse)response;
return (TResponse)response;
}
public TResponse Send<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
public void Send(IReturnVoid request)
{
throw new NotImplementedException();
}
public TResponse Get<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
public void Get(IReturnVoid request)
{
throw new NotImplementedException();
}
public TResponse Get<TResponse>(string relativeOrAbsoluteUrl)
{
httpReq.HttpMethod = HttpMethods.Get;
var requestTypeName = typeof(TResponse).Namespace + "." + relativeOrAbsoluteUrl;
var requestType = typeof (TResponse).Assembly.GetType(requestTypeName);
if (requestType == null)
throw new ArgumentException("Type not found: " + requestTypeName);
var request = requestType.CreateInstance();
if (ApplyRequestFilters<TResponse>(request)) return default(TResponse);
var response = ServiceManager.ServiceController.Execute(request,
new HttpRequestContext(httpReq, httpRes, request, EndpointAttributes.HttpGet));
if (ApplyResponseFilters<TResponse>(response)) return (TResponse)response;
return (TResponse)response;
}
public TResponse Delete<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
public void Delete(IReturnVoid request)
{
throw new NotImplementedException();
}
public TResponse Delete<TResponse>(string relativeOrAbsoluteUrl)
{
throw new NotImplementedException();
}
public TResponse Post<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
public void Post(IReturnVoid request)
{
throw new NotImplementedException();
}
public TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request)
{
throw new NotImplementedException();
}
public TResponse Put<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
public void Put(IReturnVoid request)
{
throw new NotImplementedException();
}
public TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object request)
{
throw new NotImplementedException();
}
public TResponse Patch<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
public void Patch(IReturnVoid request)
{
throw new NotImplementedException();
}
public TResponse Patch<TResponse>(string relativeOrAbsoluteUrl, object request)
{
throw new NotImplementedException();
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType)
{
throw new NotImplementedException();
}
public void CustomMethod(string httpVerb, IReturnVoid request)
{
throw new NotImplementedException();
}
public TResponse CustomMethod<TResponse>(string httpVerb, IReturn<TResponse> request)
{
throw new NotImplementedException();
}
public HttpWebResponse Head(IReturn request)
{
throw new NotImplementedException();
}
public HttpWebResponse Head(string relativeOrAbsoluteUrl)
{
throw new NotImplementedException();
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileInfo, string mimeType)
{
throw new NotImplementedException();
}
public void SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
var response = default(TResponse);
try
{
try
{
if (ApplyRequestFilters<TResponse>(request))
{
onSuccess(default(TResponse));
return;
}
}
catch (Exception ex)
{
onError(default(TResponse), ex);
return;
}
response = this.Send<TResponse>(request);
try
{
if (ApplyResponseFilters<TResponse>(request))
{
onSuccess(response);
return;
}
}
catch (Exception ex)
{
onError(response, ex);
return;
}
onSuccess(response);
}
catch (Exception ex)
{
if (onError != null)
{
onError(response, ex);
return;
}
Console.WriteLine("Error: " + ex.Message);
}
}
public void SetCredentials(string userName, string password)
{
throw new NotImplementedException();
}
public void GetAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void DeleteAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PostAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PutAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void CustomMethodAsync<TResponse>(string httpVerb, IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void CancelAsync()
{
throw new NotImplementedException();
}
public void Dispose() { }
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request)
{
throw new NotImplementedException();
}
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request)
{
throw new NotImplementedException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
#if ES_BUILD_PCL
using System.Threading.Tasks;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// Provides the ability to collect statistics through EventSource
///
/// See https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.Tracing/documentation/EventCounterTutorial.md
/// for a tutorial guide.
///
/// See https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestEventCounter.cs
/// which shows tests, which are also useful in seeing actual use.
/// </summary>
public class EventCounter : IDisposable
{
/// <summary>
/// Initializes a new instance of the <see cref="EventCounter"/> class.
/// EVentCounters live as long as the EventSource that they are attached to unless they are
/// explicitly Disposed.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="eventSource">The event source.</param>
public EventCounter(string name, EventSource eventSource)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (eventSource == null)
{
throw new ArgumentNullException(nameof(eventSource));
}
InitializeBuffer();
_name = name;
_group = EventCounterGroup.GetEventCounterGroup(eventSource);
_group.Add(this);
_min = float.PositiveInfinity;
_max = float.NegativeInfinity;
}
/// <summary>
/// Writes 'value' to the stream of values tracked by the counter. This updates the sum and other statistics that will
/// be logged on the next timer interval.
/// </summary>
/// <param name="value">The value.</param>
public void WriteMetric(float value)
{
Enqueue(value);
}
/// <summary>
/// Removes the counter from set that the EventSource will report on. After being disposed, this
/// counter will do nothing and its resource will be reclaimed if all references to it are removed.
/// If an EventCounter is not explicitly disposed it will be cleaned up automatically when the
/// EventSource it is attached to dies.
/// </summary>
public void Dispose()
{
var group = _group;
if (group != null)
{
group.Remove(this);
_group = null;
}
}
public override string ToString()
{
return "EventCounter '" + _name + "' Count " + _count + " Mean " + (((double)_sum) / _count).ToString("n3");
}
#region private implementation
private readonly string _name;
private EventCounterGroup _group;
#region Buffer Management
// Values buffering
private const int BufferedSize = 10;
private const float UnusedBufferSlotValue = float.NegativeInfinity;
private const int UnsetIndex = -1;
private volatile float[] _bufferedValues;
private volatile int _bufferedValuesIndex;
// arbitrarily we use _bufferfValues as the lock object.
private object MyLock { get { return _bufferedValues; } }
private void InitializeBuffer()
{
_bufferedValues = new float[BufferedSize];
for (int i = 0; i < _bufferedValues.Length; i++)
{
_bufferedValues[i] = UnusedBufferSlotValue;
}
}
private void Enqueue(float value)
{
// It is possible that two threads read the same bufferedValuesIndex, but only one will be able to write the slot, so that is okay.
int i = _bufferedValuesIndex;
while (true)
{
float result = Interlocked.CompareExchange(ref _bufferedValues[i], value, UnusedBufferSlotValue);
i++;
if (_bufferedValues.Length <= i)
{
// It is possible that two threads both think the buffer is full, but only one get to actually flush it, the other
// will eventually enter this code path and potentially calling Flushing on a buffer that is not full, and that's okay too.
lock (MyLock) // Lock the counter
Flush();
i = 0;
}
if (result == UnusedBufferSlotValue)
{
// CompareExchange succeeded
_bufferedValuesIndex = i;
return;
}
}
}
private void Flush()
{
Debug.Assert(Monitor.IsEntered(MyLock));
for (int i = 0; i < _bufferedValues.Length; i++)
{
var value = Interlocked.Exchange(ref _bufferedValues[i], UnusedBufferSlotValue);
if (value != UnusedBufferSlotValue)
{
OnMetricWritten(value);
}
}
_bufferedValuesIndex = 0;
}
#endregion // Buffer Management
#region Statistics Calculation
// Statistics
private int _count;
private float _sum;
private float _sumSquared;
private float _min;
private float _max;
private void OnMetricWritten(float value)
{
Debug.Assert(Monitor.IsEntered(MyLock));
_sum += value;
_sumSquared += value * value;
if (value > _max)
_max = value;
if (value < _min)
_min = value;
_count++;
}
internal EventCounterPayload GetEventCounterPayload()
{
lock (MyLock) // Lock the counter
{
Flush();
EventCounterPayload result = new EventCounterPayload();
result.Name = _name;
result.Count = _count;
if (0 < _count)
{
result.Mean = _sum / _count;
result.StandardDeviation = (float)Math.Sqrt(_sumSquared / _count - _sum * _sum / _count / _count);
}
else
{
result.Mean = 0;
result.StandardDeviation = 0;
}
result.Min = _min;
result.Max = _max;
ResetStatistics();
return result;
}
}
private void ResetStatistics()
{
Debug.Assert(Monitor.IsEntered(MyLock));
_count = 0;
_sum = 0;
_sumSquared = 0;
_min = float.PositiveInfinity;
_max = float.NegativeInfinity;
}
#endregion // Statistics Calculation
#endregion // private implementation
}
#region internal supporting classes
[EventData]
internal class EventCounterPayload : IEnumerable<KeyValuePair<string, object>>
{
public string Name { get; set; }
public float Mean { get; set; }
public float StandardDeviation { get; set; }
public int Count { get; set; }
public float Min { get; set; }
public float Max { get; set; }
public float IntervalSec { get; internal set; }
#region Implementation of the IEnumerable interface
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return ForEnumeration.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ForEnumeration.GetEnumerator();
}
private IEnumerable<KeyValuePair<string, object>> ForEnumeration
{
get
{
yield return new KeyValuePair<string, object>("Name", Name);
yield return new KeyValuePair<string, object>("Mean", Mean);
yield return new KeyValuePair<string, object>("StandardDeviation", StandardDeviation);
yield return new KeyValuePair<string, object>("Count", Count);
yield return new KeyValuePair<string, object>("Min", Min);
yield return new KeyValuePair<string, object>("Max", Max);
}
}
#endregion // Implementation of the IEnumerable interface
}
internal class EventCounterGroup
{
private readonly EventSource _eventSource;
private readonly List<EventCounter> _eventCounters;
internal EventCounterGroup(EventSource eventSource)
{
_eventSource = eventSource;
_eventCounters = new List<EventCounter>();
RegisterCommandCallback();
}
internal void Add(EventCounter eventCounter)
{
lock (this) // Lock the EventCounterGroup
_eventCounters.Add(eventCounter);
}
internal void Remove(EventCounter eventCounter)
{
lock (this) // Lock the EventCounterGroup
_eventCounters.Remove(eventCounter);
}
#region EventSource Command Processing
private void RegisterCommandCallback()
{
// Old destktop runtimes don't have this
#if NO_EVENTCOMMANDEXECUTED_SUPPORT
// We could not build against the API that had the EventCommandExecuted but maybe it is there are runtime.
// use reflection to try to get it.
System.Reflection.MethodInfo method = typeof(EventSource).GetMethod("add_EventCommandExecuted");
if (method != null)
{
method.Invoke(_eventSource, new object[] { (EventHandler<EventCommandEventArgs>)OnEventSourceCommand });
}
else
{
string msg = "EventCounterError: Old Runtime that does not support EventSource.EventCommandExecuted. EventCounters not Supported";
_eventSource.Write(msg);
Debug.WriteLine(msg);
}
#else
_eventSource.EventCommandExecuted += OnEventSourceCommand;
#endif
}
private void OnEventSourceCommand(object sender, EventCommandEventArgs e)
{
if (e.Command == EventCommand.Enable || e.Command == EventCommand.Update)
{
string valueStr;
float value;
if (e.Arguments.TryGetValue("EventCounterIntervalSec", out valueStr) && float.TryParse(valueStr, out value))
{
// Recursion through EventSource callbacks possible. When we enable the timer
// we synchonously issue a EventSource.Write event, which in turn can call back
// to user code (in an EventListener) while holding this lock. This is dangerous
// because it mean this code might inadvertantly participate in a lock loop.
// The scenario seems very unlikely so we ignore that problem for now.
lock (this) // Lock the EventCounterGroup
{
EnableTimer(value);
}
}
}
}
#endregion // EventSource Command Processing
#region Global EventCounterGroup Array management
// We need eventCounters to 'attach' themselves to a particular EventSource.
// this table provides the mapping from EventSource -> EventCounterGroup
// which represents this 'attached' information.
private static WeakReference<EventCounterGroup>[] s_eventCounterGroups;
private static readonly object s_eventCounterGroupsLock = new object();
private static void EnsureEventSourceIndexAvailable(int eventSourceIndex)
{
Debug.Assert(Monitor.IsEntered(s_eventCounterGroupsLock));
if (EventCounterGroup.s_eventCounterGroups == null)
{
EventCounterGroup.s_eventCounterGroups = new WeakReference<EventCounterGroup>[eventSourceIndex + 1];
}
else if (eventSourceIndex >= EventCounterGroup.s_eventCounterGroups.Length)
{
WeakReference<EventCounterGroup>[] newEventCounterGroups = new WeakReference<EventCounterGroup>[eventSourceIndex + 1];
Array.Copy(EventCounterGroup.s_eventCounterGroups, 0, newEventCounterGroups, 0, EventCounterGroup.s_eventCounterGroups.Length);
EventCounterGroup.s_eventCounterGroups = newEventCounterGroups;
}
}
internal static EventCounterGroup GetEventCounterGroup(EventSource eventSource)
{
lock (s_eventCounterGroupsLock)
{
int eventSourceIndex = EventListener.EventSourceIndex(eventSource);
EnsureEventSourceIndexAvailable(eventSourceIndex);
WeakReference<EventCounterGroup> weakRef = EventCounterGroup.s_eventCounterGroups[eventSourceIndex];
EventCounterGroup ret = null;
if (weakRef == null || !weakRef.TryGetTarget(out ret))
{
ret = new EventCounterGroup(eventSource);
EventCounterGroup.s_eventCounterGroups[eventSourceIndex] = new WeakReference<EventCounterGroup>(ret);
}
return ret;
}
}
#endregion // Global EventCounterGroup Array management
#region Timer Processing
private DateTime _timeStampSinceCollectionStarted;
private int _pollingIntervalInMilliseconds;
private Timer _pollingTimer;
private void DisposeTimer()
{
Debug.Assert(Monitor.IsEntered(this));
if (_pollingTimer != null)
{
_pollingTimer.Dispose();
_pollingTimer = null;
}
}
private void EnableTimer(float pollingIntervalInSeconds)
{
Debug.Assert(Monitor.IsEntered(this));
if (pollingIntervalInSeconds <= 0)
{
DisposeTimer();
_pollingIntervalInMilliseconds = 0;
}
else if (_pollingIntervalInMilliseconds == 0 || pollingIntervalInSeconds * 1000 < _pollingIntervalInMilliseconds)
{
Debug.WriteLine("Polling interval changed at " + DateTime.UtcNow.ToString("mm.ss.ffffff"));
_pollingIntervalInMilliseconds = (int)(pollingIntervalInSeconds * 1000);
DisposeTimer();
_timeStampSinceCollectionStarted = DateTime.UtcNow;
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever
bool restoreFlow = false;
try
{
if (!ExecutionContext.IsFlowSuppressed())
{
ExecutionContext.SuppressFlow();
restoreFlow = true;
}
_pollingTimer = new Timer(s => ((EventCounterGroup)s).OnTimer(null), this, _pollingIntervalInMilliseconds, _pollingIntervalInMilliseconds);
}
finally
{
// Restore the current ExecutionContext
if (restoreFlow)
ExecutionContext.RestoreFlow();
}
}
// Always fire the timer event (so you see everything up to this time).
OnTimer(null);
}
private void OnTimer(object state)
{
Debug.WriteLine("Timer fired at " + DateTime.UtcNow.ToString("mm.ss.ffffff"));
lock (this) // Lock the EventCounterGroup
{
if (_eventSource.IsEnabled())
{
DateTime now = DateTime.UtcNow;
TimeSpan elapsed = now - _timeStampSinceCollectionStarted;
foreach (var eventCounter in _eventCounters)
{
EventCounterPayload payload = eventCounter.GetEventCounterPayload();
payload.IntervalSec = (float)elapsed.TotalSeconds;
_eventSource.Write("EventCounters", new EventSourceOptions() { Level = EventLevel.LogAlways }, new PayloadType(payload));
}
_timeStampSinceCollectionStarted = now;
}
else
{
DisposeTimer();
}
}
}
/// <summary>
/// This is the payload that is sent in the with EventSource.Write
/// </summary>
[EventData]
class PayloadType
{
public PayloadType(EventCounterPayload payload) { Payload = payload; }
public EventCounterPayload Payload { get; set; }
}
#region PCL timer hack
#if ES_BUILD_PCL
internal delegate void TimerCallback(object state);
internal sealed class Timer : CancellationTokenSource, IDisposable
{
private int _period;
private TimerCallback _callback;
private object _state;
internal Timer(TimerCallback callback, object state, int dueTime, int period)
{
_callback = callback;
_state = state;
_period = period;
Schedule(dueTime);
}
private void Schedule(int dueTime)
{
Task.Delay(dueTime, Token).ContinueWith(OnTimer, null, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
}
private void OnTimer(Task t, object s)
{
Schedule(_period);
_callback(_state);
}
public new void Dispose() { base.Cancel(); }
}
#endif
#endregion // PCL timer hack
#endregion // Timer Processing
}
#endregion // internal supporting classes
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Boundary;
using Microsoft.MixedReality.Toolkit.Diagnostics;
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.SpatialAwareness;
using Microsoft.MixedReality.Toolkit.Teleport;
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.EventSystems;
using Microsoft.MixedReality.Toolkit.SceneSystem;
using Microsoft.MixedReality.Toolkit.CameraSystem;
using Microsoft.MixedReality.Toolkit.Rendering;
#if UNITY_EDITOR
using Microsoft.MixedReality.Toolkit.Input.Editor;
using UnityEditor;
#endif
namespace Microsoft.MixedReality.Toolkit
{
/// <summary>
/// This class is responsible for coordinating the operation of the Mixed Reality Toolkit. It is the only Singleton in the entire project.
/// It provides a service registry for all active services that are used within a project as well as providing the active configuration profile for the project.
/// The Profile can be swapped out at any time to meet the needs of your project.
/// </summary>
[DisallowMultipleComponent]
[AddComponentMenu("Scripts/MRTK/Core/MixedRealityToolkit")]
public class MixedRealityToolkit : MonoBehaviour, IMixedRealityServiceRegistrar
{
private static bool isInitializing = false;
private static bool isApplicationQuitting = false;
private static bool internalShutdown = false;
private const string NoMRTKProfileErrorMessage = "No Mixed Reality Configuration Profile found, cannot initialize the Mixed Reality Toolkit";
#region Mixed Reality Toolkit Profile configuration
/// <summary>
/// Checks if there is a valid instance of the MixedRealityToolkit, then checks if there is there a valid Active Profile.
/// </summary>
public bool HasActiveProfile
{
get
{
if (!IsInitialized)
{
return false;
}
return ActiveProfile != null;
}
}
/// <summary>
/// Returns true if this is the active instance.
/// </summary>
public bool IsActiveInstance
{
get
{
return activeInstance == this;
}
}
private bool HasProfileAndIsInitialized => activeProfile != null && IsInitialized;
/// <summary>
/// The active profile of the Mixed Reality Toolkit which controls which services are active and their initial configuration.
/// *Note configuration is used on project initialization or replacement, changes to properties while it is running has no effect.
/// </summary>
[SerializeField]
[Tooltip("The current active configuration for the Mixed Reality project")]
private MixedRealityToolkitConfigurationProfile activeProfile = null;
/// <summary>
/// The public property of the Active Profile, ensuring events are raised on the change of the configuration
/// </summary>
public MixedRealityToolkitConfigurationProfile ActiveProfile
{
get
{
return activeProfile;
}
set
{
ResetConfiguration(value);
}
}
/// <summary>
/// When a configuration Profile is replaced with a new configuration, force all services to reset and read the new values
/// </summary>
public void ResetConfiguration(MixedRealityToolkitConfigurationProfile profile)
{
if (activeProfile != null)
{
// Services are only enabled when playing.
if (Application.IsPlaying(activeProfile))
{
DisableAllServices();
}
DestroyAllServices();
}
activeProfile = profile;
if (profile != null)
{
if (Application.IsPlaying(profile))
{
DisableAllServices();
}
DestroyAllServices();
}
InitializeServiceLocator();
if (profile != null && Application.IsPlaying(profile))
{
EnableAllServices();
}
}
#endregion Mixed Reality Toolkit Profile configuration
#region Mixed Reality runtime service registry
private static readonly Dictionary<Type, IMixedRealityService> activeSystems = new Dictionary<Type, IMixedRealityService>();
/// <summary>
/// Current active systems registered with the MixedRealityToolkit.
/// </summary>
/// <remarks>
/// Systems can only be registered once by <see cref="System.Type"/>
/// </remarks>
[Obsolete("Use CoreService, MixedRealityServiceRegistry, or GetService<T> instead")]
public IReadOnlyDictionary<Type, IMixedRealityService> ActiveSystems => new Dictionary<Type, IMixedRealityService>(activeSystems) as IReadOnlyDictionary<Type, IMixedRealityService>;
private static readonly List<Tuple<Type, IMixedRealityService>> registeredMixedRealityServices = new List<Tuple<Type, IMixedRealityService>>();
/// <summary>
/// Local service registry for the Mixed Reality Toolkit, to allow runtime use of the <see cref="Microsoft.MixedReality.Toolkit.IMixedRealityService"/>.
/// </summary>
[Obsolete("Use GetDataProvider<T> of MixedRealityService registering the desired IMixedRealityDataProvider")]
public IReadOnlyList<Tuple<Type, IMixedRealityService>> RegisteredMixedRealityServices => new List<Tuple<Type, IMixedRealityService>>(registeredMixedRealityServices) as IReadOnlyList<Tuple<Type, IMixedRealityService>>;
#endregion Mixed Reality runtime service registry
#region IMixedRealityServiceRegistrar implementation
/// <inheritdoc />
public bool RegisterService<T>(T serviceInstance) where T : IMixedRealityService
{
return RegisterServiceInternal<T>(serviceInstance);
}
/// <inheritdoc />
public bool RegisterService<T>(
Type concreteType,
SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
params object[] args) where T : IMixedRealityService
{
return RegisterServiceInternal<T>(
true, // Retry with an added IMixedRealityService parameter
concreteType,
supportedPlatforms,
args);
}
/// <summary>
/// Internal method that creates an instance of the specified concrete type and registers the service.
/// </summary>
private bool RegisterServiceInternal<T>(
bool retryWithRegistrar,
Type concreteType,
SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
params object[] args) where T : IMixedRealityService
{
if (isApplicationQuitting)
{
return false;
}
#if !UNITY_EDITOR
if (!Application.platform.IsPlatformSupported(supportedPlatforms))
#else
if (!EditorUserBuildSettings.activeBuildTarget.IsPlatformSupported(supportedPlatforms))
#endif
{
return false;
}
if (concreteType == null)
{
Debug.LogError($"Unable to register {typeof(T).Name} service with a null concrete type.");
return false;
}
if (!typeof(IMixedRealityService).IsAssignableFrom(concreteType))
{
Debug.LogError($"Unable to register the {concreteType.Name} service. It does not implement {typeof(IMixedRealityService)}.");
return false;
}
T serviceInstance;
try
{
serviceInstance = (T)Activator.CreateInstance(concreteType, args);
}
catch (Exception e)
{
if (retryWithRegistrar && (e is MissingMethodException))
{
Debug.LogWarning($"Failed to find an appropriate constructor for the {concreteType.Name} service. Adding the Registrar instance and re-attempting registration.");
List<object> updatedArgs = new List<object>();
updatedArgs.Add(this);
if (args != null)
{
updatedArgs.AddRange(args);
}
return RegisterServiceInternal<T>(
false, // Do NOT retry, we have already added the configured IMIxedRealityServiceRegistrar
concreteType,
supportedPlatforms,
updatedArgs.ToArray());
}
Debug.LogError($"Failed to register the {concreteType.Name} service: {e.GetType()} - {e.Message}");
// Failures to create the concrete type generally surface as nested exceptions - just logging
// the top level exception itself may not be helpful. If there is a nested exception (for example,
// null reference in the constructor of the object itself), it's helpful to also surface those here.
if (e.InnerException != null)
{
Debug.LogError("Underlying exception information: " + e.InnerException);
}
return false;
}
return RegisterServiceInternal<T>(serviceInstance);
}
/// <inheritdoc />
public bool UnregisterService<T>(string name = null) where T : IMixedRealityService
{
T serviceInstance = GetServiceByName<T>(name);
if (serviceInstance == null) { return false; }
return UnregisterService<T>(serviceInstance);
}
/// <inheritdoc />
public bool UnregisterService<T>(T serviceInstance) where T : IMixedRealityService
{
Type interfaceType = typeof(T);
if (IsInitialized)
{
serviceInstance.Disable();
serviceInstance.Destroy();
}
if (IsCoreSystem(interfaceType))
{
activeSystems.Remove(interfaceType);
CoreServices.ResetCacheReference(interfaceType);
return true;
}
return MixedRealityServiceRegistry.RemoveService<T>(serviceInstance, this);
}
/// <inheritdoc />
public bool IsServiceRegistered<T>(string name = null) where T : IMixedRealityService
{
Type interfaceType = typeof(T);
if (typeof(IMixedRealityDataProvider).IsAssignableFrom(interfaceType))
{
Debug.LogWarning($"Unable to check a service of type {typeof(IMixedRealityDataProvider).Name}. Inquire with the MixedRealityService that registered the DataProvider type in question");
return false;
}
T service;
MixedRealityServiceRegistry.TryGetService<T>(out service, name);
return service != null;
}
/// <inheritdoc />
public T GetService<T>(string name = null, bool showLogs = true) where T : IMixedRealityService
{
Type interfaceType = typeof(T);
T serviceInstance = GetServiceByName<T>(name);
if ((serviceInstance == null) && showLogs)
{
Debug.LogError($"Unable to find {(string.IsNullOrWhiteSpace(name) ? interfaceType.Name : name)} service.");
}
return serviceInstance;
}
/// <inheritdoc />
public IReadOnlyList<T> GetServices<T>(string name = null) where T : IMixedRealityService
{
return GetAllServicesByNameInternal<T>(typeof(T), name);
}
#endregion IMixedRealityServiceRegistrar implementation
/// <summary>
/// Once all services are registered and properties updated, the Mixed Reality Toolkit will initialize all active services.
/// This ensures all services can reference each other once started.
/// </summary>
private void InitializeServiceLocator()
{
isInitializing = true;
// If the Mixed Reality Toolkit is not configured, stop.
if (ActiveProfile == null)
{
if (!Application.isPlaying)
{
// Log as warning if in edit mode. Likely user is making changes etc.
Debug.LogWarning(NoMRTKProfileErrorMessage);
}
else
{
Debug.LogError(NoMRTKProfileErrorMessage);
}
return;
}
#if UNITY_EDITOR
if (activeSystems.Count > 0)
{
activeSystems.Clear();
}
if (registeredMixedRealityServices.Count > 0)
{
registeredMixedRealityServices.Clear();
}
EnsureEditorSetup();
#endif
CoreServices.ResetCacheReferences();
EnsureMixedRealityRequirements();
#region Services Registration
// If the Input system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsInputSystemEnabled)
{
#if UNITY_EDITOR
// Make sure unity axis mappings are set.
InputMappingAxisUtility.CheckUnityInputManagerMappings(ControllerMappingLibrary.UnityInputManagerAxes);
#endif
object[] args = { ActiveProfile.InputSystemProfile };
if (!RegisterService<IMixedRealityInputSystem>(ActiveProfile.InputSystemType, args: args) || CoreServices.InputSystem == null)
{
Debug.LogError("Failed to start the Input System!");
}
args = new object[] { ActiveProfile.InputSystemProfile };
if (!RegisterService<IMixedRealityFocusProvider>(ActiveProfile.InputSystemProfile.FocusProviderType, args: args))
{
Debug.LogError("Failed to register the focus provider! The input system will not function without it.");
return;
}
args = new object[] { ActiveProfile.InputSystemProfile };
if (!RegisterService<IMixedRealityRaycastProvider>(ActiveProfile.InputSystemProfile.RaycastProviderType, args: args))
{
Debug.LogError("Failed to register the raycast provider! The input system will not function without it.");
return;
}
}
else
{
#if UNITY_EDITOR
InputMappingAxisUtility.RemoveMappings(ControllerMappingLibrary.UnityInputManagerAxes);
#endif
}
// If the Boundary system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsBoundarySystemEnabled)
{
object[] args = { ActiveProfile.BoundaryVisualizationProfile, ActiveProfile.TargetExperienceScale };
if (!RegisterService<IMixedRealityBoundarySystem>(ActiveProfile.BoundarySystemSystemType, args: args) || CoreServices.BoundarySystem == null)
{
Debug.LogError("Failed to start the Boundary System!");
}
}
// If the Camera system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsCameraSystemEnabled)
{
object[] args = { ActiveProfile.CameraProfile };
if (!RegisterService<IMixedRealityCameraSystem>(ActiveProfile.CameraSystemType, args: args) || CoreServices.CameraSystem == null)
{
Debug.LogError("Failed to start the Camera System!");
}
}
// If the Spatial Awareness system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsSpatialAwarenessSystemEnabled)
{
object[] args = { ActiveProfile.SpatialAwarenessSystemProfile };
if (!RegisterService<IMixedRealitySpatialAwarenessSystem>(ActiveProfile.SpatialAwarenessSystemSystemType, args: args) && CoreServices.SpatialAwarenessSystem != null)
{
Debug.LogError("Failed to start the Spatial Awareness System!");
}
}
// If the Teleport system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsTeleportSystemEnabled)
{
if (!RegisterService<IMixedRealityTeleportSystem>(ActiveProfile.TeleportSystemSystemType) || CoreServices.TeleportSystem == null)
{
Debug.LogError("Failed to start the Teleport System!");
}
}
if (ActiveProfile.IsDiagnosticsSystemEnabled)
{
object[] args = { ActiveProfile.DiagnosticsSystemProfile };
if (!RegisterService<IMixedRealityDiagnosticsSystem>(ActiveProfile.DiagnosticsSystemSystemType, args: args) || CoreServices.DiagnosticsSystem == null)
{
Debug.LogError("Failed to start the Diagnostics System!");
}
}
if (ActiveProfile.IsSceneSystemEnabled)
{
object[] args = { ActiveProfile.SceneSystemProfile };
if (!RegisterService<IMixedRealitySceneSystem>(ActiveProfile.SceneSystemSystemType, args: args) || CoreServices.SceneSystem == null)
{
Debug.LogError("Failed to start the Scene System!");
}
}
if (ActiveProfile.RegisteredServiceProvidersProfile != null)
{
for (int i = 0; i < ActiveProfile.RegisteredServiceProvidersProfile.Configurations?.Length; i++)
{
var configuration = ActiveProfile.RegisteredServiceProvidersProfile.Configurations[i];
if (typeof(IMixedRealityExtensionService).IsAssignableFrom(configuration.ComponentType.Type))
{
object[] args = { configuration.ComponentName, configuration.Priority, configuration.Profile };
RegisterService<IMixedRealityExtensionService>(configuration.ComponentType, configuration.RuntimePlatform, args);
}
}
}
#endregion Service Registration
InitializeAllServices();
isInitializing = false;
}
private void EnsureEditorSetup()
{
if (ActiveProfile.RenderDepthBuffer)
{
CameraCache.Main.gameObject.EnsureComponent<DepthBufferRenderer>();
}
}
private void EnsureMixedRealityRequirements()
{
// There's lots of documented cases that if the camera doesn't start at 0,0,0, things break with the WMR SDK specifically.
// We'll enforce that here, then tracking can update it to the appropriate position later.
CameraCache.Main.transform.position = Vector3.zero;
CameraCache.Main.transform.rotation = Quaternion.identity;
// This will create the playspace
_ = MixedRealityPlayspace.Transform;
bool addedComponents = false;
if (!Application.isPlaying)
{
var eventSystems = FindObjectsOfType<EventSystem>();
if (eventSystems.Length == 0)
{
CameraCache.Main.gameObject.EnsureComponent<EventSystem>();
addedComponents = true;
}
else
{
bool raiseWarning;
if (eventSystems.Length == 1)
{
raiseWarning = eventSystems[0].gameObject != CameraCache.Main.gameObject;
}
else
{
raiseWarning = true;
}
if (raiseWarning)
{
Debug.LogWarning("Found an existing event system in your scene. The Mixed Reality Toolkit requires only one, and must be found on the main camera.");
}
}
}
if (!addedComponents)
{
CameraCache.Main.gameObject.EnsureComponent<EventSystem>();
}
}
#region MonoBehaviour Implementation
private static MixedRealityToolkit activeInstance;
private static bool newInstanceBeingInitialized = false;
#if UNITY_EDITOR
/// <summary>
/// Returns the Singleton instance of the classes type.
/// </summary>
public static MixedRealityToolkit Instance
{
get
{
if (activeInstance != null)
{
return activeInstance;
}
// It's possible for MRTK to exist in the scene but for activeInstance to be
// null when a custom editor component accesses Instance before the MRTK
// object has clicked on in object hierarchy (see https://github.com/microsoft/MixedRealityToolkit-Unity/pull/4618)
//
// To avoid returning null in this case, make sure to search the scene for MRTK.
// We do this only when in editor to avoid any performance cost at runtime.
List<MixedRealityToolkit> mrtks = new List<MixedRealityToolkit>(FindObjectsOfType<MixedRealityToolkit>());
// Sort the list by instance ID so we get deterministic results when selecting our next active instance
mrtks.Sort(delegate (MixedRealityToolkit i1, MixedRealityToolkit i2) { return i1.GetInstanceID().CompareTo(i2.GetInstanceID()); });
for (int i = 0; i < mrtks.Count; i++)
{
RegisterInstance(mrtks[i]);
}
return activeInstance;
}
}
#else
/// <summary>
/// Returns the Singleton instance of the classes type.
/// </summary>
public static MixedRealityToolkit Instance => activeInstance;
#endif
private void InitializeInstance()
{
if (newInstanceBeingInitialized)
{
return;
}
newInstanceBeingInitialized = true;
gameObject.SetActive(true);
if (HasActiveProfile)
{
InitializeServiceLocator();
}
newInstanceBeingInitialized = false;
}
/// <summary>
/// Expose an assertion whether the MixedRealityToolkit class is initialized.
/// </summary>
public static void AssertIsInitialized()
{
Debug.Assert(IsInitialized, "The MixedRealityToolkit has not been initialized.");
}
/// <summary>
/// Returns whether the instance has been initialized or not.
/// </summary>
public static bool IsInitialized => activeInstance != null;
/// <summary>
/// Static function to determine if the MixedRealityToolkit class has been initialized or not.
/// </summary>
public static bool ConfirmInitialized()
{
// ReSharper disable once UnusedVariable
// Assigning the Instance to access is used Implicitly.
MixedRealityToolkit access = Instance;
return IsInitialized;
}
private void Awake()
{
RegisterInstance(this);
}
private void OnEnable()
{
if (IsActiveInstance)
{
EnableAllServices();
}
}
private void Update()
{
if (IsActiveInstance)
{
UpdateAllServices();
}
}
private void LateUpdate()
{
if (IsActiveInstance)
{
LateUpdateAllServices();
}
}
private void OnDisable()
{
if (IsActiveInstance)
{
DisableAllServices();
}
}
private void OnDestroy()
{
UnregisterInstance(this);
}
#endregion MonoBehaviour Implementation
#region Instance Registration
private const string activeInstanceGameObjectName = "MixedRealityToolkit";
private const string inactiveInstanceGameObjectName = "MixedRealityToolkit (Inactive)";
private static List<MixedRealityToolkit> toolkitInstances = new List<MixedRealityToolkit>();
public static void SetActiveInstance(MixedRealityToolkit toolkitInstance)
{
if (MixedRealityToolkit.isApplicationQuitting)
{ // Don't register instances while application is quitting
return;
}
if (toolkitInstance == activeInstance)
{ // Don't do anything
return;
}
// Disable the old instance
SetInstanceInactive(activeInstance);
// Immediately register the new instance
RegisterInstance(toolkitInstance, true);
}
private static void RegisterInstance(MixedRealityToolkit toolkitInstance, bool setAsActiveInstance = false)
{
if (MixedRealityToolkit.isApplicationQuitting || toolkitInstance == null)
{ // Don't register instances while application is quitting
return;
}
internalShutdown = false;
if (!toolkitInstances.Contains(toolkitInstance))
{ // If we're already registered, no need to proceed
// Add to list
toolkitInstances.Add(toolkitInstance);
// Sort the list by instance ID so we get deterministic results when selecting our next active instance
toolkitInstances.Sort(delegate (MixedRealityToolkit i1, MixedRealityToolkit i2) { return i1.GetInstanceID().CompareTo(i2.GetInstanceID()); });
}
if (activeInstance == null)
{
// If we don't have an active instance, either set this instance
// to be the active instance if requested, or get the first valid remaining instance
// in the list.
if (setAsActiveInstance)
{
activeInstance = toolkitInstance;
}
else
{
for (int i = 0; i < toolkitInstances.Count; i++)
{
if (toolkitInstances[i] != null)
{
activeInstance = toolkitInstances[i];
break;
}
}
}
activeInstance.DestroyAllServices();
activeInstance.InitializeInstance();
}
// Update instance's Name so it's clear who is the active instance
for (int i = toolkitInstances.Count - 1; i >= 0; i--)
{
if (toolkitInstances[i] == null)
{
toolkitInstances.RemoveAt(i);
}
else
{
toolkitInstances[i].name = toolkitInstances[i].IsActiveInstance ? activeInstanceGameObjectName : inactiveInstanceGameObjectName;
}
}
}
private static void UnregisterInstance(MixedRealityToolkit toolkitInstance)
{
// We are shutting an instance down.
internalShutdown = true;
toolkitInstances.Remove(toolkitInstance);
// Sort the list by instance ID so we get deterministic results when selecting our next active instance
toolkitInstances.Sort(delegate (MixedRealityToolkit i1, MixedRealityToolkit i2) { return i1.GetInstanceID().CompareTo(i2.GetInstanceID()); });
if (MixedRealityToolkit.activeInstance == toolkitInstance)
{ // If this is the active instance, we need to break it down
toolkitInstance.DestroyAllServices();
CoreServices.ResetCacheReferences();
// If this was the active instance, unregister the active instance
MixedRealityToolkit.activeInstance = null;
if (MixedRealityToolkit.isApplicationQuitting)
{ // Don't search for additional instances if we're quitting
return;
}
for (int i = 0; i < toolkitInstances.Count; i++)
{
if (toolkitInstances[i] == null)
{ // This may have been a mass-deletion - be wary of soon-to-be-unregistered instances
continue;
}
// Select the first available instance and register it immediately
RegisterInstance(toolkitInstances[i]);
break;
}
}
}
public static void SetInstanceInactive(MixedRealityToolkit toolkitInstance)
{
if (toolkitInstance == null)
{ // Don't do anything.
return;
}
if (toolkitInstance == activeInstance)
{ // If this was the active instance, un-register the active instance
// Break down all services
if (Application.isPlaying)
{
toolkitInstance.DisableAllServices();
}
toolkitInstance.DestroyAllServices();
CoreServices.ResetCacheReferences();
// If this was the active instance, unregister the active instance
MixedRealityToolkit.activeInstance = null;
}
}
#endregion Instance Registration
#region Service Container Management
#region Registration
// NOTE: This method intentionally does not add to the registry. This is actually mostly a helper function for RegisterServiceInternal<T>.
private bool RegisterServiceInternal(Type interfaceType, IMixedRealityService serviceInstance)
{
if (serviceInstance == null)
{
Debug.LogWarning($"Unable to register a {interfaceType.Name} service with a null instance.");
return false;
}
if (typeof(IMixedRealityDataProvider).IsAssignableFrom(interfaceType))
{
Debug.LogWarning($"Unable to register a service of type {typeof(IMixedRealityDataProvider).Name}. Register this DataProvider with the MixedRealityService that depends on it.");
return false;
}
if (!CanGetService(interfaceType))
{
return false;
}
IMixedRealityService preExistingService = GetServiceByNameInternal(interfaceType, serviceInstance.Name);
if (preExistingService != null)
{
Debug.LogError($"There's already a {interfaceType.Name}.{preExistingService.Name} registered!");
return false;
}
if (IsCoreSystem(interfaceType))
{
activeSystems.Add(interfaceType, serviceInstance);
}
if (!isInitializing)
{
serviceInstance.Initialize();
}
return true;
}
/// <summary>
/// Internal service registration.
/// </summary>
/// <param name="interfaceType">The interface type for the system to be registered.</param>
/// <param name="serviceInstance">Instance of the service.</param>
/// <returns>True if registration is successful, false otherwise.</returns>
private bool RegisterServiceInternal<T>(T serviceInstance) where T : IMixedRealityService
{
Type interfaceType = typeof(T);
if (RegisterServiceInternal(interfaceType, serviceInstance))
{
MixedRealityServiceRegistry.AddService<T>(serviceInstance, this);
return true;
}
return false;
}
#endregion Registration
#region Multiple Service Management
/// <summary>
/// Enable all services in the Mixed Reality Toolkit active service registry for a given type
/// </summary>
/// <param name="interfaceType">The interface type for the system to be enabled. E.G. InputSystem, BoundarySystem</param>
public void EnableAllServicesByType(Type interfaceType)
{
EnableAllServicesByTypeAndName(interfaceType, string.Empty);
}
/// <summary>
/// Enable all services in the Mixed Reality Toolkit active service registry for a given type and name
/// </summary>
/// <param name="interfaceType">The interface type for the system to be enabled. E.G. InputSystem, BoundarySystem</param>
/// <param name="serviceName">Name of the specific service</param>
public void EnableAllServicesByTypeAndName(Type interfaceType, string serviceName)
{
if (interfaceType == null)
{
Debug.LogError("Unable to enable null service type.");
return;
}
IReadOnlyList<IMixedRealityService> services = GetAllServicesByNameInternal<IMixedRealityService>(interfaceType, serviceName);
for (int i = 0; i < services.Count; i++)
{
services[i].Enable();
}
}
/// <summary>
/// Disable all services in the Mixed Reality Toolkit active service registry for a given type
/// </summary>
/// <param name="interfaceType">The interface type for the system to be removed. E.G. InputSystem, BoundarySystem</param>
public void DisableAllServicesByType(Type interfaceType)
{
DisableAllServicesByTypeAndName(interfaceType, string.Empty);
}
/// <summary>
/// Disable all services in the Mixed Reality Toolkit active service registry for a given type and name
/// </summary>
/// <param name="interfaceType">The interface type for the system to be disabled. E.G. InputSystem, BoundarySystem</param>
/// <param name="serviceName">Name of the specific service</param>
public void DisableAllServicesByTypeAndName(Type interfaceType, string serviceName)
{
if (interfaceType == null)
{
Debug.LogError("Unable to disable null service type.");
return;
}
IReadOnlyList<IMixedRealityService> services = GetAllServicesByNameInternal<IMixedRealityService>(interfaceType, serviceName);
for (int i = 0; i < services.Count; i++)
{
services[i].Disable();
}
}
private void InitializeAllServices()
{
// Initialize all systems
ExecuteOnAllServicesInOrder(service => service.Initialize());
}
private void ResetAllServices()
{
// Reset all systems
ExecuteOnAllServicesInOrder(service => service.Reset());
}
private void EnableAllServices()
{
// Enable all systems
ExecuteOnAllServicesInOrder(service => service.Enable());
}
private static readonly ProfilerMarker UpdateAllServicesPerfMarker = new ProfilerMarker("[MRTK] MixedRealityToolkit.UpdateAllServices");
private void UpdateAllServices()
{
using (UpdateAllServicesPerfMarker.Auto())
{
// Update all systems
ExecuteOnAllServicesInOrder(service => service.Update());
}
}
private static readonly ProfilerMarker LateUpdateAllServicesPerfMarker = new ProfilerMarker("[MRTK] MixedRealityToolkit.LateUpdateAllServices");
private void LateUpdateAllServices()
{
using (LateUpdateAllServicesPerfMarker.Auto())
{
// If the Mixed Reality Toolkit is not configured, stop.
if (activeProfile == null) { return; }
// If the Mixed Reality Toolkit is not initialized, stop.
if (!IsInitialized) { return; }
// Update all systems
ExecuteOnAllServicesInOrder(service => service.LateUpdate());
}
}
private void DisableAllServices()
{
// Disable all systems
ExecuteOnAllServicesReverseOrder(service => service.Disable());
}
private void DestroyAllServices()
{
// Unregister core services (active systems)
// We need to destroy services in backwards order as those which are initialized
// later may rely on those which are initialized first.
var orderedActiveSystems = activeSystems.OrderByDescending(m => m.Value.Priority);
foreach (var service in orderedActiveSystems)
{
Type type = service.Key;
if (typeof(IMixedRealityBoundarySystem).IsAssignableFrom(type))
{
UnregisterService<IMixedRealityBoundarySystem>();
}
else if (typeof(IMixedRealityCameraSystem).IsAssignableFrom(type))
{
UnregisterService<IMixedRealityCameraSystem>();
}
else if (typeof(IMixedRealityDiagnosticsSystem).IsAssignableFrom(type))
{
UnregisterService<IMixedRealityDiagnosticsSystem>();
}
else if (typeof(IMixedRealityFocusProvider).IsAssignableFrom(type))
{
UnregisterService<IMixedRealityFocusProvider>();
}
else if (typeof(IMixedRealityInputSystem).IsAssignableFrom(type))
{
UnregisterService<IMixedRealityInputSystem>();
}
else if (typeof(IMixedRealitySpatialAwarenessSystem).IsAssignableFrom(type))
{
UnregisterService<IMixedRealitySpatialAwarenessSystem>();
}
else if (typeof(IMixedRealityTeleportSystem).IsAssignableFrom(type))
{
UnregisterService<IMixedRealityTeleportSystem>();
}
}
activeSystems.Clear();
CoreServices.ResetCacheReferences();
MixedRealityServiceRegistry.ClearAllServices();
}
private static readonly ProfilerMarker ExecuteOnAllServicesInOrderPerfMarker = new ProfilerMarker("[MRTK] MixedRealityToolkit.ExecuteOnAllServicesInOrder");
private bool ExecuteOnAllServicesInOrder(Action<IMixedRealityService> execute)
{
using (ExecuteOnAllServicesInOrderPerfMarker.Auto())
{
if (!HasProfileAndIsInitialized)
{
return false;
}
var services = MixedRealityServiceRegistry.GetAllServices();
int length = services.Count;
for (int i = 0; i < length; i++)
{
execute(services[i]);
}
return true;
}
}
private static readonly ProfilerMarker ExecuteOnAllServicesReverseOrderPerfMarker = new ProfilerMarker("[MRTK] MixedRealityToolkit.ExecuteOnAllServicesReverseOrder");
private bool ExecuteOnAllServicesReverseOrder(Action<IMixedRealityService> execute)
{
using (ExecuteOnAllServicesReverseOrderPerfMarker.Auto())
{
if (!HasProfileAndIsInitialized)
{
return false;
}
var services = MixedRealityServiceRegistry.GetAllServices();
int length = services.Count;
for (int i = length - 1; i >= 0; i--)
{
execute(services[i]);
}
return true;
}
}
#endregion Multiple Service Management
#region Service Utilities
/// <summary>
/// Generic function used to interrogate the Mixed Reality Toolkit active system registry for the existence of a core system.
/// </summary>
/// <typeparam name="T">The interface type for the system to be retrieved. E.G. InputSystem, BoundarySystem.</typeparam>
/// <remarks>
/// Note: type should be the Interface of the system to be retrieved and not the concrete class itself.
/// </remarks>
/// <returns>True, there is a system registered with the selected interface, False, no system found for that interface</returns>
[Obsolete("Use IsServiceRegistered instead")]
public bool IsSystemRegistered<T>() where T : IMixedRealityService
{
if (!IsCoreSystem(typeof(T))) return false;
T service;
MixedRealityServiceRegistry.TryGetService<T>(out service);
if (service == null)
{
IMixedRealityService activeSerivce;
activeSystems.TryGetValue(typeof(T), out activeSerivce);
return activeSerivce != null;
}
return service != null;
}
private static bool IsCoreSystem(Type type)
{
if (type == null)
{
Debug.LogWarning("Null cannot be a core system.");
return false;
}
return typeof(IMixedRealityInputSystem).IsAssignableFrom(type) ||
typeof(IMixedRealityCameraSystem).IsAssignableFrom(type) ||
typeof(IMixedRealityFocusProvider).IsAssignableFrom(type) ||
typeof(IMixedRealityRaycastProvider).IsAssignableFrom(type) ||
typeof(IMixedRealityTeleportSystem).IsAssignableFrom(type) ||
typeof(IMixedRealityBoundarySystem).IsAssignableFrom(type) ||
typeof(IMixedRealitySpatialAwarenessSystem).IsAssignableFrom(type) ||
typeof(IMixedRealityDiagnosticsSystem).IsAssignableFrom(type) ||
typeof(IMixedRealitySceneSystem).IsAssignableFrom(type);
}
private IMixedRealityService GetServiceByNameInternal(Type interfaceType, string serviceName)
{
if (typeof(IMixedRealityDataProvider).IsAssignableFrom(interfaceType))
{
Debug.LogWarning($"Unable to get a service of type {typeof(IMixedRealityDataProvider).Name}.");
return null;
}
if (!CanGetService(interfaceType)) { return null; }
IMixedRealityService service;
MixedRealityServiceRegistry.TryGetService(interfaceType, out service, out _, serviceName);
if (service != null)
{
return service;
}
return null;
}
/// <summary>
/// Retrieve the first service from the registry that meets the selected type and name
/// </summary>
/// <param name="interfaceType">Interface type of the service being requested</param>
/// <param name="serviceName">Name of the specific service</param>
/// <param name="serviceInstance">return parameter of the function</param>
private T GetServiceByName<T>(string serviceName) where T : IMixedRealityService
{
return (T)GetServiceByNameInternal(typeof(T), serviceName);
}
/// <summary>
/// Gets all services by type and name.
/// </summary>
/// <param name="serviceName">The name of the service to search for. If the string is empty than any matching <see cref="interfaceType"/> will be added to the <see cref="services"/> list.</param>
private IReadOnlyList<T> GetAllServicesByNameInternal<T>(Type interfaceType, string serviceName) where T : IMixedRealityService
{
List<T> services = new List<T>();
if (!CanGetService(interfaceType)) { return new List<T>() as IReadOnlyList<T>; }
bool isNullServiceName = string.IsNullOrEmpty(serviceName);
var systems = MixedRealityServiceRegistry.GetAllServices();
int length = systems.Count;
for (int i = 0; i < length; i++)
{
IMixedRealityService service = systems[i];
if (service is T && (isNullServiceName || service.Name == serviceName))
{
services.Add((T)service);
}
}
return services;
}
/// <summary>
/// Check if the interface type and name matches the registered interface type and service instance found.
/// </summary>
/// <param name="interfaceType">The interface type of the service to check.</param>
/// <param name="serviceName">The name of the service to check.</param>
/// <param name="registeredInterfaceType">The registered interface type.</param>
/// <param name="serviceInstance">The instance of the registered service.</param>
/// <returns>True, if the registered service contains the interface type and name.</returns>
private static bool CheckServiceMatch(Type interfaceType, string serviceName, Type registeredInterfaceType, IMixedRealityService serviceInstance)
{
bool isValid = string.IsNullOrEmpty(serviceName) || serviceInstance.Name == serviceName;
if ((registeredInterfaceType.Name == interfaceType.Name || serviceInstance.GetType().Name == interfaceType.Name) && isValid)
{
return true;
}
var interfaces = serviceInstance.GetType().GetInterfaces();
for (int i = 0; i < interfaces.Length; i++)
{
if (interfaces[i].Name == interfaceType.Name && isValid)
{
return true;
}
}
return false;
}
/// <summary>
/// Checks if the system is ready to get a service.
/// </summary>
/// <param name="interfaceType">The interface type of the service being checked.</param>
private static bool CanGetService(Type interfaceType)
{
if (isApplicationQuitting && !internalShutdown)
{
return false;
}
if (!IsInitialized)
{
Debug.LogError("The Mixed Reality Toolkit has not been initialized!");
return false;
}
if (interfaceType == null)
{
Debug.LogError($"Interface type is null.");
return false;
}
if (!typeof(IMixedRealityService).IsAssignableFrom(interfaceType))
{
Debug.LogError($"{interfaceType.Name} does not implement {typeof(IMixedRealityService).Name}.");
return false;
}
return true;
}
#endregion Service Utilities
#endregion Service Container Management
#region Core System Accessors
/// <summary>
/// The current Input System registered with the Mixed Reality Toolkit.
/// </summary>
[Obsolete("Utilize CoreServices.InputSystem instead")]
public static IMixedRealityInputSystem InputSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
return CoreServices.InputSystem;
}
}
/// <summary>
/// The current Boundary System registered with the Mixed Reality Toolkit.
/// </summary>
[Obsolete("Utilize CoreServices.BoundarySystem instead")]
public static IMixedRealityBoundarySystem BoundarySystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
return CoreServices.BoundarySystem;
}
}
/// <summary>
/// The current Camera System registered with the Mixed Reality Toolkit.
/// </summary>
[Obsolete("Utilize CoreServices.CameraSystem instead")]
public static IMixedRealityCameraSystem CameraSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
return CoreServices.CameraSystem;
}
}
/// <summary>
/// The current Spatial Awareness System registered with the Mixed Reality Toolkit.
/// </summary>
[Obsolete("Utilize CoreServices.SpatialAwarenessSystem instead")]
public static IMixedRealitySpatialAwarenessSystem SpatialAwarenessSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
return CoreServices.SpatialAwarenessSystem;
}
}
/// <summary>
/// Returns true if the MixedRealityToolkit exists and has an active profile that has Teleport system enabled.
/// </summary>
public static bool IsTeleportSystemEnabled => IsInitialized && Instance.HasActiveProfile && Instance.ActiveProfile.IsTeleportSystemEnabled;
/// <summary>
/// The current Teleport System registered with the Mixed Reality Toolkit.
/// </summary>
[Obsolete("Utilize CoreServices.TeleportSystem instead")]
public static IMixedRealityTeleportSystem TeleportSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
return CoreServices.TeleportSystem;
}
}
/// <summary>
/// The current Diagnostics System registered with the Mixed Reality Toolkit.
/// </summary>
[Obsolete("Utilize CoreServices.DiagnosticsSystem instead")]
public static IMixedRealityDiagnosticsSystem DiagnosticsSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
return CoreServices.DiagnosticsSystem;
}
}
/// <summary>
/// Returns true if the MixedRealityToolkit exists and has an active profile that has Scene system enabled.
/// </summary>
public static bool IsSceneSystemEnabled => IsInitialized && Instance.HasActiveProfile && Instance.ActiveProfile.IsSceneSystemEnabled;
/// <summary>
/// The current Scene System registered with the Mixed Reality Toolkit.
/// </summary>
[Obsolete("Utilize CoreServices.SceneSystem instead")]
public static IMixedRealitySceneSystem SceneSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
return CoreServices.SceneSystem;
}
}
#endregion Core System Accessors
#region Application Event Listeners
/// <summary>
/// Registers once on startup and sets isApplicationQuitting to true when quit event is detected.
/// </summary>
[RuntimeInitializeOnLoadMethod]
private static void RegisterRuntimePlayModeListener()
{
Application.quitting += () =>
{
isApplicationQuitting = true;
};
}
#if UNITY_EDITOR
/// <summary>
/// Static class whose constructor is called once on startup. Listens for editor events.
/// Removes the need for individual instances to listen for events.
/// </summary>
[InitializeOnLoad]
private static class EditorEventListener
{
private const string WarnUser_EmptyActiveProfile = "WarnUser_EmptyActiveProfile";
static EditorEventListener()
{
// Detect when we enter edit mode so we can reset isApplicationQuitting
EditorApplication.playModeStateChanged += playModeState =>
{
switch (playModeState)
{
case PlayModeStateChange.EnteredEditMode:
isApplicationQuitting = false;
break;
case PlayModeStateChange.ExitingEditMode:
isApplicationQuitting = false;
if (activeInstance != null && activeInstance.activeProfile == null)
{
// If we have an active instance, and its profile is null,
// Alert the user that we don't have an active profile
// Keep track though whether user has instructed to ignore this warning
if (SessionState.GetBool(WarnUser_EmptyActiveProfile, true))
{
if (EditorUtility.DisplayDialog("Warning!", "Mixed Reality Toolkit cannot initialize because no Active Profile has been assigned.", "OK", "Ignore"))
{
// Stop play mode as changes done in play mode will be lost
EditorApplication.isPlaying = false;
Selection.activeObject = Instance;
EditorGUIUtility.PingObject(Instance);
}
else
{
SessionState.SetBool(WarnUser_EmptyActiveProfile, false);
}
}
}
break;
default:
break;
}
};
EditorApplication.hierarchyChanged += () =>
{
// These checks are only necessary in edit mode
if (!Application.isPlaying)
{
// Clean the toolkit instances hierarchy in case instances were deleted.
for (int i = toolkitInstances.Count - 1; i >= 0; i--)
{
if (toolkitInstances[i] == null)
{
// If it has been destroyed, remove it
toolkitInstances.RemoveAt(i);
}
}
// If the active instance is null, it may not have been set, or it may have been deleted.
if (activeInstance == null)
{
// Do a search for a new active instance
MixedRealityToolkit instanceCheck = Instance;
}
}
for (int i = toolkitInstances.Count - 1; i >= 0; i--)
{
// Make sure MRTK is not parented under anything
Debug.Assert(toolkitInstances[i].transform.parent == null, "MixedRealityToolkit instances should not be parented under any other GameObject.");
}
};
}
}
private void OnValidate()
{
EditorApplication.delayCall += DelayOnValidate; // This is a workaround for a known unity issue when calling refresh assetdatabase from inside a on validate scope.
}
/// <summary>
/// Used to register newly created instances in edit mode.
/// Initially handled by using ExecuteAlways, but this attribute causes the instance to be destroyed as we enter play mode, which is disruptive to services.
/// </summary>
private void DelayOnValidate()
{
EditorApplication.delayCall -= DelayOnValidate;
// This check is only necessary in edit mode. This can also get called during player builds as well,
// and shouldn't be run during that time.
if (EditorApplication.isPlayingOrWillChangePlaymode ||
EditorApplication.isCompiling ||
BuildPipeline.isBuildingPlayer)
{
return;
}
RegisterInstance(this);
}
#endif // UNITY_EDITOR
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using CSharpMath.Atom;
using CSharpMath.Rendering.FrontEnd;
using CSharpMath.Structures;
using Typography.OpenFont;
// X stands for Xaml
#if Avalonia
using XCanvas = CSharpMath.Avalonia.AvaloniaCanvas;
using XCanvasColor = Avalonia.Media.Color;
using XColor = Avalonia.Media.Color;
using XControl = Avalonia.Controls.Control;
using XInheritControl = Avalonia.Controls.Control;
using XProperty = Avalonia.AvaloniaProperty;
namespace CSharpMath.Avalonia {
#elif Forms
using XCanvas = SkiaSharp.SKCanvas;
using XCanvasColor = SkiaSharp.SKColor;
using XColor = Xamarin.Forms.Color;
using XControl = Xamarin.Forms.View;
using XInheritControl = SkiaSharp.Views.Forms.SKCanvasView;
using XProperty = Xamarin.Forms.BindableProperty;
using MathPainter = CSharpMath.SkiaSharp.MathPainter;
using TextPainter = CSharpMath.SkiaSharp.TextPainter;
namespace CSharpMath.Forms {
[Xamarin.Forms.ContentProperty(nameof(LaTeX))]
#endif
public class BaseView<TPainter, TContent> : XInheritControl, ICSharpMathAPI<TContent, XColor>
where TPainter : Painter<XCanvas, TContent, XCanvasColor>, new() where TContent : class {
public TPainter Painter { get; } = new TPainter();
protected static readonly TPainter staticPainter = new TPainter();
public static XProperty CreateProperty<TThis, TValue>(
string propertyName,
bool affectsMeasure,
Func<TPainter, TValue> defaultValueGet,
Action<TPainter, TValue> propertySet,
Action<TThis, TValue>? updateOtherProperty = null)
where TThis : BaseView<TPainter, TContent> {
var defaultValue = defaultValueGet(staticPainter);
void PropertyChanged(TThis @this, object? newValue) {
// We need to support nullable classes and structs, so we cannot forbid null here
// So this use of the null-forgiving operator should be blamed on non-generic PropertyChanged handlers
var @new = (TValue)newValue!;
propertySet(@this.Painter, @new);
updateOtherProperty?.Invoke(@this, @new);
if (affectsMeasure) @this.InvalidateMeasure();
// Redraw immediately! No deferred drawing
#if Avalonia
@this.InvalidateVisual();
}
var prop = XProperty.Register<TThis, TValue>(propertyName, defaultValue);
global::Avalonia.AvaloniaObjectExtensions.AddClassHandler<TThis>(prop.Changed, (t, e) => PropertyChanged(t, e.NewValue));
return prop;
}
public BaseView() {
// Respect built-in styles
Styles.Add(new global::Avalonia.Styling.Style(global::Avalonia.Styling.Selectors.Is<BaseView<TPainter, TContent>>) {
Setters =
{
new global::Avalonia.Styling.Setter(TextColorProperty, new global::Avalonia.Markup.Xaml.MarkupExtensions.DynamicResourceExtension("SystemBaseHighColor"))
}
});
}
protected override global::Avalonia.Size MeasureOverride(global::Avalonia.Size availableSize) =>
Painter.Measure((float)availableSize.Width) is { } rect
? new global::Avalonia.Size(rect.Width, rect.Height)
: base.MeasureOverride(availableSize);
struct ReadOnlyProperty<TThis, TValue> where TThis : BaseView<TPainter, TContent> {
public ReadOnlyProperty(string propertyName,
Func<TPainter, TValue> getter) {
Property = XProperty.RegisterDirect<TThis, TValue>(propertyName, b => getter(b.Painter), null, getter(staticPainter));
_value = getter(staticPainter);
}
TValue _value;
public global::Avalonia.DirectProperty<TThis, TValue> Property;
public void SetValue(TThis @this, TValue value) => @this.SetAndRaise(Property, ref _value, value);
}
static XCanvasColor XColorToXCanvasColor(XColor color) => color;
static XColor XCanvasColorToXColor(XCanvasColor color) => color;
global::Avalonia.Point _origin;
protected override void OnPointerPressed(global::Avalonia.Input.PointerPressedEventArgs e) {
var point = e.GetCurrentPoint(this);
if (point.Properties.IsLeftButtonPressed && EnablePanning) {
_origin = point.Position;
}
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(global::Avalonia.Input.PointerEventArgs e) {
var point = e.GetCurrentPoint(this);
if (point.Properties.IsLeftButtonPressed && EnablePanning) {
var displacement = point.Position - _origin;
_origin = point.Position;
DisplacementX += (float)displacement.X;
DisplacementY += (float)displacement.Y;
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(global::Avalonia.Input.PointerReleasedEventArgs e) {
var point = e.GetCurrentPoint(this);
if (point.Properties.IsLeftButtonPressed && EnablePanning) {
_origin = point.Position;
}
base.OnPointerReleased(e);
}
public override void Render(global::Avalonia.Media.DrawingContext context) {
base.Render(context);
var canvas = new XCanvas(context, Bounds.Size);
#elif Forms
@this.InvalidateSurface();
}
return XProperty.Create(propertyName, typeof(TValue), typeof(TThis), defaultValue,
propertyChanged: (b, o, n) => PropertyChanged((TThis)b, n));
}
protected override Xamarin.Forms.SizeRequest OnMeasure(double widthConstraint, double heightConstraint) =>
Painter.Measure((float)widthConstraint) is { } rect
? new Xamarin.Forms.SizeRequest(new Xamarin.Forms.Size(rect.Width, rect.Height))
: base.OnMeasure(widthConstraint, heightConstraint);
struct ReadOnlyProperty<TThis, TValue> where TThis : BaseView<TPainter, TContent> {
public ReadOnlyProperty(string propertyName,
Func<TPainter, TValue> getter) {
_key = XProperty.CreateReadOnly(propertyName, typeof(TValue), typeof(TThis), getter(staticPainter));
}
readonly Xamarin.Forms.BindablePropertyKey _key;
public XProperty Property => _key.BindableProperty;
public void SetValue(TThis @this, TValue value) => @this.SetValue(_key, value);
}
private protected static XCanvasColor XColorToXCanvasColor(XColor color) => global::SkiaSharp.Views.Forms.Extensions.ToSKColor(color);
private protected static XColor XCanvasColorToXColor(XCanvasColor color) => global::SkiaSharp.Views.Forms.Extensions.ToFormsColor(color);
global::SkiaSharp.SKPoint _origin;
protected override void OnTouch(global::SkiaSharp.Views.Forms.SKTouchEventArgs e) {
if (e.InContact && EnablePanning) {
switch (e.ActionType) {
case global::SkiaSharp.Views.Forms.SKTouchAction.Pressed:
_origin = e.Location;
e.Handled = true;
break;
case global::SkiaSharp.Views.Forms.SKTouchAction.Moved:
var displacement = e.Location - _origin;
_origin = e.Location;
DisplacementX += displacement.X;
DisplacementY += displacement.Y;
e.Handled = true;
break;
case global::SkiaSharp.Views.Forms.SKTouchAction.Released:
_origin = e.Location;
e.Handled = true;
break;
case global::SkiaSharp.Views.Forms.SKTouchAction.Entered:
case global::SkiaSharp.Views.Forms.SKTouchAction.Cancelled:
case global::SkiaSharp.Views.Forms.SKTouchAction.Exited:
default:
break;
}
}
base.OnTouch(e);
}
protected sealed override void OnPaintSurface(global::SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e) {
base.OnPaintSurface(e);
var canvas = e.Surface.Canvas;
canvas.Clear();
// https://github.com/verybadcat/CSharpMath/issues/136 and https://github.com/verybadcat/CSharpMath/issues/137
// SkiaSharp deals with raw pixels as opposed to Xamarin.Forms's device-independent units.
// We should scale to occupy the full view size.
canvas.Scale(e.Info.Width / (float)Width);
#endif
Painter.Draw(canvas, TextAlignment, Padding, DisplacementX, DisplacementY);
}
/// <summary>Requires touch events to be enabled in SkiaSharp/Xamarin.Forms</summary>
public bool EnablePanning { get => (bool)GetValue(DisablePanningProperty); set => SetValue(DisablePanningProperty, value); }
public static readonly XProperty DisablePanningProperty = CreateProperty<BaseView<TPainter, TContent>, bool>(nameof(EnablePanning), false, _ => false, (_, __) => { });
static readonly System.Reflection.ParameterInfo[] drawMethodParams = typeof(TPainter)
.GetMethod(nameof(Painter<XCanvas, TContent, XColor>.Draw),
new[] { typeof(XCanvas), typeof(TextAlignment), typeof(Thickness), typeof(float), typeof(float) }).GetParameters();
static T? Nullable<T>(T value) where T : struct => new T?(value);
public (XColor glyph, XColor textRun)? GlyphBoxColor { get => ((XColor glyph, XColor textRun)?)GetValue(GlyphBoxColorProperty); set => SetValue(GlyphBoxColorProperty, value); }
public static readonly XProperty GlyphBoxColorProperty = CreateProperty<BaseView<TPainter, TContent>, (XColor glyph, XColor textRun)?>(nameof(GlyphBoxColor), false,
p => p.GlyphBoxColor is var (glyph, textRun) ? Nullable((XCanvasColorToXColor(glyph), XCanvasColorToXColor(textRun))) : null,
(p, v) => p.GlyphBoxColor = v is var (glyph, textRun) ? Nullable((XColorToXCanvasColor(glyph), XColorToXCanvasColor(textRun))) : null);
public TContent? Content { get => (TContent)GetValue(ContentProperty); set => SetValue(ContentProperty, value); }
public static readonly XProperty ContentProperty = CreateProperty<BaseView<TPainter, TContent>, TContent?>(nameof(Content), true, p => p.Content, (p, v) => p.Content = v, (b, v) => { if (b.Painter.ErrorMessage == null) b.LaTeX = b.Painter.LaTeX; });
#if Avalonia
[global::Avalonia.Metadata.Content]
#endif
public string? LaTeX { get => (string?)GetValue(LaTeXProperty); set => SetValue(LaTeXProperty, value); }
public static readonly XProperty LaTeXProperty = CreateProperty<BaseView<TPainter, TContent>, string?>(nameof(LaTeX), true, p => p.LaTeX, (p, v) => p.LaTeX = v, (b, v) => (b.Content, b.ErrorMessage) = (b.Painter.Content, b.Painter.ErrorMessage));
public bool DisplayErrorInline { get => (bool)GetValue(DisplayErrorInlineProperty); set => SetValue(DisplayErrorInlineProperty, value); }
public static readonly XProperty DisplayErrorInlineProperty = CreateProperty<BaseView<TPainter, TContent>, bool>(nameof(DisplayErrorInline), true, p => p.DisplayErrorInline, (p, v) => p.DisplayErrorInline = v);
/// <summary>Unit of measure: points</summary>
public float FontSize { get => (float)GetValue(FontSizeProperty); set => SetValue(FontSizeProperty, value); }
public static readonly XProperty FontSizeProperty = CreateProperty<BaseView<TPainter, TContent>, float>(nameof(FontSize), true, p => p.FontSize, (p, v) => p.FontSize = v);
/// <summary>Unit of measure: points; Defaults to <see cref="FontSize"/>.</summary>
public float? ErrorFontSize { get => (float?)GetValue(ErrorFontSizeProperty); set => SetValue(ErrorFontSizeProperty, value); }
public static readonly XProperty ErrorFontSizeProperty = CreateProperty<BaseView<TPainter, TContent>, float?>(nameof(ErrorFontSize), true, p => p.ErrorFontSize, (p, v) => p.ErrorFontSize = v);
public IEnumerable<Typeface> LocalTypefaces { get => (IEnumerable<Typeface>)GetValue(LocalTypefacesProperty); set => SetValue(LocalTypefacesProperty, value); }
public static readonly XProperty LocalTypefacesProperty = CreateProperty<BaseView<TPainter, TContent>, IEnumerable<Typeface>>(nameof(LocalTypefaces), true, p => p.LocalTypefaces, (p, v) => p.LocalTypefaces = v);
public XColor TextColor { get => (XColor)GetValue(TextColorProperty); set => SetValue(TextColorProperty, value); }
public static readonly XProperty TextColorProperty = CreateProperty<BaseView<TPainter, TContent>, XColor>(nameof(TextColor), false, p => XCanvasColorToXColor(p.TextColor), (p, v) => p.TextColor = XColorToXCanvasColor(v));
public XColor HighlightColor { get => (XColor)GetValue(HighlightColorProperty); set => SetValue(HighlightColorProperty, value); }
public static readonly XProperty HighlightColorProperty = CreateProperty<BaseView<TPainter, TContent>, XColor>(nameof(HighlightColor), false, p => XCanvasColorToXColor(p.HighlightColor), (p, v) => p.HighlightColor = XColorToXCanvasColor(v));
public XColor ErrorColor { get => (XColor)GetValue(ErrorColorProperty); set => SetValue(ErrorColorProperty, value); }
public static readonly XProperty ErrorColorProperty = CreateProperty<BaseView<TPainter, TContent>, XColor>(nameof(ErrorColor), false, p => XCanvasColorToXColor(p.ErrorColor), (p, v) => p.ErrorColor = XColorToXCanvasColor(v));
public TextAlignment TextAlignment { get => (TextAlignment)GetValue(TextAlignmentProperty); set => SetValue(TextAlignmentProperty, value); }
public static readonly XProperty TextAlignmentProperty = CreateProperty<BaseView<TPainter, TContent>, TextAlignment>(nameof(Rendering.FrontEnd.TextAlignment), false, p => (TextAlignment)drawMethodParams[1].DefaultValue, (p, v) => { });
public Thickness Padding { get => (Thickness)GetValue(PaddingProperty); set => SetValue(PaddingProperty, value); }
public static readonly XProperty PaddingProperty = CreateProperty<BaseView<TPainter, TContent>, Thickness>(nameof(Padding), false, p => (Thickness)(drawMethodParams[2].DefaultValue ?? new Thickness()), (p, v) => { });
public float DisplacementX { get => (float)GetValue(DisplacementXProperty); set => SetValue(DisplacementXProperty, value); }
public static readonly XProperty DisplacementXProperty = CreateProperty<BaseView<TPainter, TContent>, float>(nameof(DisplacementX), false, p => (float)drawMethodParams[3].DefaultValue, (p, v) => { });
public float DisplacementY { get => (float)GetValue(DisplacementYProperty); set => SetValue(DisplacementYProperty, value); }
public static readonly XProperty DisplacementYProperty = CreateProperty<BaseView<TPainter, TContent>, float>(nameof(DisplacementY), false, p => (float)drawMethodParams[4].DefaultValue, (p, v) => { });
public float Magnification { get => (float)GetValue(MagnificationProperty); set => SetValue(MagnificationProperty, value); }
public static readonly XProperty MagnificationProperty = CreateProperty<BaseView<TPainter, TContent>, float>(nameof(Magnification), false, p => p.Magnification, (p, v) => p.Magnification = v);
public PaintStyle PaintStyle { get => (PaintStyle)GetValue(PaintStyleProperty); set => SetValue(PaintStyleProperty, value); }
public static readonly XProperty PaintStyleProperty = CreateProperty<BaseView<TPainter, TContent>, PaintStyle>(nameof(PaintStyle), false, p => p.PaintStyle, (p, v) => p.PaintStyle = v);
public LineStyle LineStyle { get => (LineStyle)GetValue(LineStyleProperty); set => SetValue(LineStyleProperty, value); }
public static readonly XProperty LineStyleProperty = CreateProperty<BaseView<TPainter, TContent>, LineStyle>(nameof(LineStyle), false, p => p.LineStyle, (p, v) => p.LineStyle = v);
public string? ErrorMessage { get => (string?)GetValue(ErrorMessageProperty); private set => ErrorMessagePropertyKey.SetValue(this, value); }
private static readonly ReadOnlyProperty<BaseView<TPainter, TContent>, string?> ErrorMessagePropertyKey = new ReadOnlyProperty<BaseView<TPainter, TContent>, string?>(nameof(ErrorMessage), p => p.ErrorMessage);
public static readonly XProperty ErrorMessageProperty = ErrorMessagePropertyKey.Property;
}
public class MathView : BaseView<MathPainter, MathList> { }
public class TextView : BaseView<TextPainter, Rendering.Text.TextAtom> { }
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp
{
internal partial class Controller
{
internal partial class Session
{
public void ComputeModel(
ImmutableArray<ISignatureHelpProvider> providers,
SignatureHelpTriggerInfo triggerInfo)
{
AssertIsForeground();
var caretPosition = Controller.TextView.GetCaretPoint(Controller.SubjectBuffer).Value;
var disconnectedBufferGraph = new DisconnectedBufferGraph(Controller.SubjectBuffer, Controller.TextView.TextBuffer);
// If this is a retrigger command then update the retrigger-id. This way
// any in-flight retrigger-updates will immediately bail out.
if (IsNonTypeCharRetrigger(triggerInfo))
{
Interlocked.Increment(ref _retriggerId);
}
var localId = _retriggerId;
// If we've already computed a model, then just use that. Otherwise, actually
// compute a new model and send that along.
Computation.ChainTaskAndNotifyControllerWhenFinished(
(model, cancellationToken) => ComputeModelInBackgroundAsync(
localId, model, providers, caretPosition,
disconnectedBufferGraph, triggerInfo, cancellationToken));
}
private static bool IsNonTypeCharRetrigger(SignatureHelpTriggerInfo triggerInfo)
=> triggerInfo.TriggerReason == SignatureHelpTriggerReason.RetriggerCommand &&
triggerInfo.TriggerCharacter == null;
private async Task<Model> ComputeModelInBackgroundAsync(
int localRetriggerId,
Model currentModel,
ImmutableArray<ISignatureHelpProvider> providers,
SnapshotPoint caretPosition,
DisconnectedBufferGraph disconnectedBufferGraph,
SignatureHelpTriggerInfo triggerInfo,
CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.SignatureHelp_ModelComputation_ComputeModelInBackground, cancellationToken))
{
AssertIsBackground();
cancellationToken.ThrowIfCancellationRequested();
var document = await Controller.DocumentProvider.GetDocumentAsync(caretPosition.Snapshot, cancellationToken).ConfigureAwait(false);
if (document == null)
{
return currentModel;
}
if (triggerInfo.TriggerReason == SignatureHelpTriggerReason.RetriggerCommand)
{
if (currentModel == null)
{
return null;
}
if (triggerInfo.TriggerCharacter.HasValue &&
!currentModel.Provider.IsRetriggerCharacter(triggerInfo.TriggerCharacter.Value))
{
return currentModel;
}
}
// first try to query the providers that can trigger on the specified character
var providerAndItemsOpt = await ComputeItemsAsync(
localRetriggerId, providers, caretPosition,
triggerInfo, document, cancellationToken).ConfigureAwait(false);
if (providerAndItemsOpt == null)
{
// Another retrigger was enqueued while we were inflight. Just
// stop all work and return the last computed model. We'll compute
// the correct model when we process the other retrigger task.
return currentModel;
}
var (provider, items) = providerAndItemsOpt.Value;
if (provider == null)
{
// No provider produced items. So we can't produce a model
return null;
}
if (currentModel != null &&
currentModel.Provider == provider &&
currentModel.GetCurrentSpanInSubjectBuffer(disconnectedBufferGraph.SubjectBufferSnapshot).Span.Start == items.ApplicableSpan.Start &&
currentModel.ArgumentIndex == items.ArgumentIndex &&
currentModel.ArgumentCount == items.ArgumentCount &&
currentModel.ArgumentName == items.ArgumentName)
{
// The new model is the same as the current model. Return the currentModel
// so we keep the active selection.
return currentModel;
}
var selectedItem = GetSelectedItem(currentModel, items, provider);
var model = new Model(disconnectedBufferGraph, items.ApplicableSpan, provider,
items.Items, selectedItem, items.ArgumentIndex, items.ArgumentCount, items.ArgumentName,
selectedParameter: 0);
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
var isCaseSensitive = syntaxFactsService == null || syntaxFactsService.IsCaseSensitive;
var selection = DefaultSignatureHelpSelector.GetSelection(model.Items,
model.SelectedItem, model.ArgumentIndex, model.ArgumentCount, model.ArgumentName, isCaseSensitive);
return model.WithSelectedItem(selection.SelectedItem)
.WithSelectedParameter(selection.SelectedParameter);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static bool SequenceEquals(IEnumerable<string> s1, IEnumerable<string> s2)
{
if (s1 == s2)
{
return true;
}
return s1 != null && s2 != null && s1.SequenceEqual(s2);
}
private static SignatureHelpItem GetSelectedItem(Model currentModel, SignatureHelpItems items, ISignatureHelpProvider provider)
{
// Try to find the most appropriate item in the list to select by default.
// If the provider specified one a selected item, then always stick with that one.
if (items.SelectedItemIndex.HasValue)
{
return items.Items[items.SelectedItemIndex.Value];
}
// If the provider did not pick a default, and it's the same provider as the previous
// model we have, then try to return the same item that we had before.
if (currentModel != null && currentModel.Provider == provider)
{
return items.Items.FirstOrDefault(i => DisplayPartsMatch(i, currentModel.SelectedItem)) ?? items.Items.First();
}
// Otherwise, just pick the first item we have.
return items.Items.First();
}
private static bool DisplayPartsMatch(SignatureHelpItem i1, SignatureHelpItem i2)
=> i1.GetAllParts().SequenceEqual(i2.GetAllParts(), CompareParts);
private static bool CompareParts(TaggedText p1, TaggedText p2)
=> p1.ToString() == p2.ToString();
/// <summary>
/// Returns <code>null</code> if our work was preempted and we want to return the
/// previous model we've computed.
/// </summary>
private async Task<(ISignatureHelpProvider provider, SignatureHelpItems items)?> ComputeItemsAsync(
int localRetriggerId,
ImmutableArray<ISignatureHelpProvider> providers,
SnapshotPoint caretPosition,
SignatureHelpTriggerInfo triggerInfo,
Document document,
CancellationToken cancellationToken)
{
try
{
ISignatureHelpProvider bestProvider = null;
SignatureHelpItems bestItems = null;
// TODO(cyrusn): We're calling into extensions, we need to make ourselves resilient
// to the extension crashing.
foreach (var provider in providers)
{
// If this is a retrigger command, and another retrigger command has already
// been issued then we can bail out immediately.
if (IsNonTypeCharRetrigger(triggerInfo) &&
localRetriggerId != _retriggerId)
{
return null;
}
cancellationToken.ThrowIfCancellationRequested();
var currentItems = await provider.GetItemsAsync(document, caretPosition, triggerInfo, cancellationToken).ConfigureAwait(false);
if (currentItems != null && currentItems.ApplicableSpan.IntersectsWith(caretPosition.Position))
{
// If another provider provides sig help items, then only take them if they
// start after the last batch of items. i.e. we want the set of items that
// conceptually are closer to where the caret position is. This way if you have:
//
// Foo(new Bar($$
//
// Then invoking sig help will only show the items for "new Bar(" and not also
// the items for "Foo(..."
if (IsBetter(bestItems, currentItems.ApplicableSpan))
{
bestItems = currentItems;
bestProvider = provider;
}
}
}
return (bestProvider, bestItems);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private bool IsBetter(SignatureHelpItems bestItems, TextSpan? currentTextSpan)
{
// If we have no best text span, then this span is definitely better.
if (bestItems == null)
{
return true;
}
// Otherwise we want the one that is conceptually the innermost signature. So it's
// only better if the distance from it to the caret position is less than the best
// one so far.
return currentTextSpan.Value.Start > bestItems.ApplicableSpan.Start;
}
}
}
}
| |
namespace Epi.Windows.Analysis.Dialogs
{
/// <summary>
/// Help Dialog
/// </summary>
partial class HelpDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HelpDialog));
this.btnBrowse = new System.Windows.Forms.Button();
this.cmbAnchor = new System.Windows.Forms.ComboBox();
this.txtFilename = new System.Windows.Forms.TextBox();
this.lblAnchor = new System.Windows.Forms.Label();
this.lblFilename = new System.Windows.Forms.Label();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
//
// btnBrowse
//
this.btnBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnBrowse.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnBrowse.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnBrowse.Location = new System.Drawing.Point(391, 29);
this.btnBrowse.Name = "btnBrowse";
this.btnBrowse.Size = new System.Drawing.Size(24, 23);
this.btnBrowse.TabIndex = 16;
this.btnBrowse.Text = "...";
this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
//
// cmbAnchor
//
this.cmbAnchor.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cmbAnchor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbAnchor.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.cmbAnchor.Location = new System.Drawing.Point(22, 73);
this.cmbAnchor.Name = "cmbAnchor";
this.cmbAnchor.Size = new System.Drawing.Size(329, 21);
this.cmbAnchor.TabIndex = 18;
this.cmbAnchor.TextChanged += new System.EventHandler(this.txtFilename_TextChanged);
//
// txtFilename
//
this.txtFilename.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtFilename.BackColor = System.Drawing.SystemColors.Window;
this.txtFilename.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.txtFilename.Location = new System.Drawing.Point(22, 30);
this.txtFilename.Name = "txtFilename";
this.txtFilename.ReadOnly = true;
this.txtFilename.Size = new System.Drawing.Size(379, 20);
this.txtFilename.TabIndex = 15;
this.txtFilename.TextChanged += new System.EventHandler(this.txtFilename_TextChanged);
//
// lblAnchor
//
this.lblAnchor.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblAnchor.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.lblAnchor.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblAnchor.Location = new System.Drawing.Point(22, 55);
this.lblAnchor.Name = "lblAnchor";
this.lblAnchor.Size = new System.Drawing.Size(329, 13);
this.lblAnchor.TabIndex = 17;
this.lblAnchor.Text = "&Anchor";
//
// lblFilename
//
this.lblFilename.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblFilename.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.lblFilename.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblFilename.Location = new System.Drawing.Point(22, 14);
this.lblFilename.Name = "lblFilename";
this.lblFilename.Size = new System.Drawing.Size(379, 13);
this.lblFilename.TabIndex = 14;
this.lblFilename.Text = "&FileName";
this.lblFilename.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnSaveOnly
//
this.btnSaveOnly.Enabled = false;
this.btnSaveOnly.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnSaveOnly.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnSaveOnly.Location = new System.Drawing.Point(22, 120);
this.btnSaveOnly.Name = "btnSaveOnly";
this.btnSaveOnly.Size = new System.Drawing.Size(75, 23);
this.btnSaveOnly.TabIndex = 39;
this.btnSaveOnly.Text = "&Save Only";
//
// btnHelp
//
this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnHelp.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnHelp.Location = new System.Drawing.Point(342, 120);
this.btnHelp.Name = "btnHelp"; btnHelp.Enabled = false;
this.btnHelp.Size = new System.Drawing.Size(75, 23);
this.btnHelp.TabIndex = 38;
this.btnHelp.Text = "&Help";
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnCancel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnCancel.Location = new System.Drawing.Point(182, 120);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 36;
this.btnCancel.Text = "Cancel";
//
// btnOK
//
this.btnOK.Enabled = false;
this.btnOK.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnOK.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnOK.Location = new System.Drawing.Point(102, 120);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 35;
this.btnOK.Text = "OK";
//
// btnClear
//
this.btnClear.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnClear.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnClear.Location = new System.Drawing.Point(262, 120);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(75, 23);
this.btnClear.TabIndex = 37;
this.btnClear.Text = "C&lear";
//
// HelpDialog
//
this.ClientSize = new System.Drawing.Size(439, 155);
this.Controls.Add(this.btnSaveOnly);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnBrowse);
this.Controls.Add(this.cmbAnchor);
this.Controls.Add(this.txtFilename);
this.Controls.Add(this.lblAnchor);
this.Controls.Add(this.lblFilename);
this.Name = "HelpDialog";
this.Text = "Help";
this.Load += new System.EventHandler(this.HelpDialog_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnBrowse;
private System.Windows.Forms.ComboBox cmbAnchor;
private System.Windows.Forms.TextBox txtFilename;
private System.Windows.Forms.Label lblAnchor;
private System.Windows.Forms.Label lblFilename;
private System.Windows.Forms.Button btnSaveOnly;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnClear;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSLInteger = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass
{
// LSL CONSTANTS
public static readonly LSLInteger TRUE = new LSLInteger(1);
public static readonly LSLInteger FALSE = new LSLInteger(0);
public const int STATUS_PHYSICS = 1;
public const int STATUS_ROTATE_X = 2;
public const int STATUS_ROTATE_Y = 4;
public const int STATUS_ROTATE_Z = 8;
public const int STATUS_PHANTOM = 16;
public const int STATUS_SANDBOX = 32;
public const int STATUS_BLOCK_GRAB = 64;
public const int STATUS_DIE_AT_EDGE = 128;
public const int STATUS_RETURN_AT_EDGE = 256;
public const int STATUS_CAST_SHADOWS = 512;
public const int AGENT = 1;
public const int AGENT_BY_LEGACY_NAME = 1;
public const int AGENT_BY_USERNAME = 0x10;
public const int NPC = 0x20;
public const int ACTIVE = 2;
public const int PASSIVE = 4;
public const int SCRIPTED = 8;
public const int OS_NPC = 0x01000000;
public const int CONTROL_FWD = 1;
public const int CONTROL_BACK = 2;
public const int CONTROL_LEFT = 4;
public const int CONTROL_RIGHT = 8;
public const int CONTROL_UP = 16;
public const int CONTROL_DOWN = 32;
public const int CONTROL_ROT_LEFT = 256;
public const int CONTROL_ROT_RIGHT = 512;
public const int CONTROL_LBUTTON = 268435456;
public const int CONTROL_ML_LBUTTON = 1073741824;
//Permissions
public const int PERMISSION_DEBIT = 2;
public const int PERMISSION_TAKE_CONTROLS = 4;
public const int PERMISSION_REMAP_CONTROLS = 8;
public const int PERMISSION_TRIGGER_ANIMATION = 16;
public const int PERMISSION_ATTACH = 32;
public const int PERMISSION_RELEASE_OWNERSHIP = 64;
public const int PERMISSION_CHANGE_LINKS = 128;
public const int PERMISSION_CHANGE_JOINTS = 256;
public const int PERMISSION_CHANGE_PERMISSIONS = 512;
public const int PERMISSION_TRACK_CAMERA = 1024;
public const int PERMISSION_CONTROL_CAMERA = 2048;
public const int AGENT_FLYING = 1;
public const int AGENT_ATTACHMENTS = 2;
public const int AGENT_SCRIPTED = 4;
public const int AGENT_MOUSELOOK = 8;
public const int AGENT_SITTING = 16;
public const int AGENT_ON_OBJECT = 32;
public const int AGENT_AWAY = 64;
public const int AGENT_WALKING = 128;
public const int AGENT_IN_AIR = 256;
public const int AGENT_TYPING = 512;
public const int AGENT_CROUCHING = 1024;
public const int AGENT_BUSY = 2048;
public const int AGENT_ALWAYS_RUN = 4096;
//Particle Systems
public const int PSYS_PART_INTERP_COLOR_MASK = 1;
public const int PSYS_PART_INTERP_SCALE_MASK = 2;
public const int PSYS_PART_BOUNCE_MASK = 4;
public const int PSYS_PART_WIND_MASK = 8;
public const int PSYS_PART_FOLLOW_SRC_MASK = 16;
public const int PSYS_PART_FOLLOW_VELOCITY_MASK = 32;
public const int PSYS_PART_TARGET_POS_MASK = 64;
public const int PSYS_PART_TARGET_LINEAR_MASK = 128;
public const int PSYS_PART_EMISSIVE_MASK = 256;
public const int PSYS_PART_RIBBON_MASK = 1024;
public const int PSYS_PART_FLAGS = 0;
public const int PSYS_PART_START_COLOR = 1;
public const int PSYS_PART_START_ALPHA = 2;
public const int PSYS_PART_END_COLOR = 3;
public const int PSYS_PART_END_ALPHA = 4;
public const int PSYS_PART_START_SCALE = 5;
public const int PSYS_PART_END_SCALE = 6;
public const int PSYS_PART_MAX_AGE = 7;
public const int PSYS_SRC_ACCEL = 8;
public const int PSYS_SRC_PATTERN = 9;
public const int PSYS_SRC_INNERANGLE = 10;
public const int PSYS_SRC_OUTERANGLE = 11;
public const int PSYS_SRC_TEXTURE = 12;
public const int PSYS_SRC_BURST_RATE = 13;
public const int PSYS_SRC_BURST_PART_COUNT = 15;
public const int PSYS_SRC_BURST_RADIUS = 16;
public const int PSYS_SRC_BURST_SPEED_MIN = 17;
public const int PSYS_SRC_BURST_SPEED_MAX = 18;
public const int PSYS_SRC_MAX_AGE = 19;
public const int PSYS_SRC_TARGET_KEY = 20;
public const int PSYS_SRC_OMEGA = 21;
public const int PSYS_SRC_ANGLE_BEGIN = 22;
public const int PSYS_SRC_ANGLE_END = 23;
public const int PSYS_PART_BLEND_FUNC_SOURCE = 24;
public const int PSYS_PART_BLEND_FUNC_DEST = 25;
public const int PSYS_PART_START_GLOW = 26;
public const int PSYS_PART_END_GLOW = 27;
public const int PSYS_PART_BF_ONE = 0;
public const int PSYS_PART_BF_ZERO = 1;
public const int PSYS_PART_BF_DEST_COLOR = 2;
public const int PSYS_PART_BF_SOURCE_COLOR = 3;
public const int PSYS_PART_BF_ONE_MINUS_DEST_COLOR = 4;
public const int PSYS_PART_BF_ONE_MINUS_SOURCE_COLOR = 5;
public const int PSYS_PART_BF_SOURCE_ALPHA = 7;
public const int PSYS_PART_BF_ONE_MINUS_SOURCE_ALPHA = 9;
public const int PSYS_SRC_PATTERN_DROP = 1;
public const int PSYS_SRC_PATTERN_EXPLODE = 2;
public const int PSYS_SRC_PATTERN_ANGLE = 4;
public const int PSYS_SRC_PATTERN_ANGLE_CONE = 8;
public const int PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16;
public const int VEHICLE_TYPE_NONE = 0;
public const int VEHICLE_TYPE_SLED = 1;
public const int VEHICLE_TYPE_CAR = 2;
public const int VEHICLE_TYPE_BOAT = 3;
public const int VEHICLE_TYPE_AIRPLANE = 4;
public const int VEHICLE_TYPE_BALLOON = 5;
public const int VEHICLE_LINEAR_FRICTION_TIMESCALE = 16;
public const int VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17;
public const int VEHICLE_LINEAR_MOTOR_DIRECTION = 18;
public const int VEHICLE_LINEAR_MOTOR_OFFSET = 20;
public const int VEHICLE_ANGULAR_MOTOR_DIRECTION = 19;
public const int VEHICLE_HOVER_HEIGHT = 24;
public const int VEHICLE_HOVER_EFFICIENCY = 25;
public const int VEHICLE_HOVER_TIMESCALE = 26;
public const int VEHICLE_BUOYANCY = 27;
public const int VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28;
public const int VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29;
public const int VEHICLE_LINEAR_MOTOR_TIMESCALE = 30;
public const int VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31;
public const int VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32;
public const int VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33;
public const int VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34;
public const int VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35;
public const int VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36;
public const int VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37;
public const int VEHICLE_BANKING_EFFICIENCY = 38;
public const int VEHICLE_BANKING_MIX = 39;
public const int VEHICLE_BANKING_TIMESCALE = 40;
public const int VEHICLE_REFERENCE_FRAME = 44;
public const int VEHICLE_RANGE_BLOCK = 45;
public const int VEHICLE_ROLL_FRAME = 46;
public const int VEHICLE_FLAG_NO_DEFLECTION_UP = 1;
public const int VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2;
public const int VEHICLE_FLAG_HOVER_WATER_ONLY = 4;
public const int VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8;
public const int VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16;
public const int VEHICLE_FLAG_HOVER_UP_ONLY = 32;
public const int VEHICLE_FLAG_LIMIT_MOTOR_UP = 64;
public const int VEHICLE_FLAG_MOUSELOOK_STEER = 128;
public const int VEHICLE_FLAG_MOUSELOOK_BANK = 256;
public const int VEHICLE_FLAG_CAMERA_DECOUPLED = 512;
public const int VEHICLE_FLAG_NO_X = 1024;
public const int VEHICLE_FLAG_NO_Y = 2048;
public const int VEHICLE_FLAG_NO_Z = 4096;
public const int VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192;
public const int VEHICLE_FLAG_NO_DEFLECTION = 16392;
public const int VEHICLE_FLAG_LOCK_ROTATION = 32784;
public const int INVENTORY_ALL = -1;
public const int INVENTORY_NONE = -1;
public const int INVENTORY_TEXTURE = 0;
public const int INVENTORY_SOUND = 1;
public const int INVENTORY_LANDMARK = 3;
public const int INVENTORY_CLOTHING = 5;
public const int INVENTORY_OBJECT = 6;
public const int INVENTORY_NOTECARD = 7;
public const int INVENTORY_SCRIPT = 10;
public const int INVENTORY_BODYPART = 13;
public const int INVENTORY_ANIMATION = 20;
public const int INVENTORY_GESTURE = 21;
public const int ATTACH_CHEST = 1;
public const int ATTACH_HEAD = 2;
public const int ATTACH_LSHOULDER = 3;
public const int ATTACH_RSHOULDER = 4;
public const int ATTACH_LHAND = 5;
public const int ATTACH_RHAND = 6;
public const int ATTACH_LFOOT = 7;
public const int ATTACH_RFOOT = 8;
public const int ATTACH_BACK = 9;
public const int ATTACH_PELVIS = 10;
public const int ATTACH_MOUTH = 11;
public const int ATTACH_CHIN = 12;
public const int ATTACH_LEAR = 13;
public const int ATTACH_REAR = 14;
public const int ATTACH_LEYE = 15;
public const int ATTACH_REYE = 16;
public const int ATTACH_NOSE = 17;
public const int ATTACH_RUARM = 18;
public const int ATTACH_RLARM = 19;
public const int ATTACH_LUARM = 20;
public const int ATTACH_LLARM = 21;
public const int ATTACH_RHIP = 22;
public const int ATTACH_RULEG = 23;
public const int ATTACH_RLLEG = 24;
public const int ATTACH_LHIP = 25;
public const int ATTACH_LULEG = 26;
public const int ATTACH_LLLEG = 27;
public const int ATTACH_BELLY = 28;
public const int ATTACH_RPEC = 29;
public const int ATTACH_LPEC = 30;
public const int ATTACH_LEFT_PEC = 29; // Same value as ATTACH_RPEC, see https://jira.secondlife.com/browse/SVC-580
public const int ATTACH_RIGHT_PEC = 30; // Same value as ATTACH_LPEC, see https://jira.secondlife.com/browse/SVC-580
public const int ATTACH_HUD_CENTER_2 = 31;
public const int ATTACH_HUD_TOP_RIGHT = 32;
public const int ATTACH_HUD_TOP_CENTER = 33;
public const int ATTACH_HUD_TOP_LEFT = 34;
public const int ATTACH_HUD_CENTER_1 = 35;
public const int ATTACH_HUD_BOTTOM_LEFT = 36;
public const int ATTACH_HUD_BOTTOM = 37;
public const int ATTACH_HUD_BOTTOM_RIGHT = 38;
public const int ATTACH_NECK = 39;
public const int ATTACH_AVATAR_CENTER = 40;
#region osMessageAttachments constants
/// <summary>
/// Instructs osMessageAttachements to send the message to attachments
/// on every point.
/// </summary>
/// <remarks>
/// One might expect this to be named OS_ATTACH_ALL, but then one might
/// also expect functions designed to attach or detach or get
/// attachments to work with it too. Attaching a no-copy item to
/// many attachments could be dangerous.
/// when combined with OS_ATTACH_MSG_INVERT_POINTS, will prevent the
/// message from being sent.
/// if combined with OS_ATTACH_MSG_OBJECT_CREATOR or
/// OS_ATTACH_MSG_SCRIPT_CREATOR, could result in no message being
/// sent- this is expected behaviour.
/// </remarks>
public const int OS_ATTACH_MSG_ALL = -65535;
/// <summary>
/// Instructs osMessageAttachements to invert how the attachment points
/// list should be treated (e.g. go from inclusive operation to
/// exclusive operation).
/// </summary>
/// <remarks>
/// This might be used if you want to deliver a message to one set of
/// attachments and a different message to everything else. With
/// this flag, you only need to build one explicit list for both calls.
/// </remarks>
public const int OS_ATTACH_MSG_INVERT_POINTS = 1;
/// <summary>
/// Instructs osMessageAttachments to only send the message to
/// attachments with a CreatorID that matches the host object CreatorID
/// </summary>
/// <remarks>
/// This would be used if distributed in an object vendor/updater server.
/// </remarks>
public const int OS_ATTACH_MSG_OBJECT_CREATOR = 2;
/// <summary>
/// Instructs osMessageAttachments to only send the message to
/// attachments with a CreatorID that matches the sending script CreatorID
/// </summary>
/// <remarks>
/// This might be used if the script is distributed independently of a
/// containing object.
/// </remarks>
public const int OS_ATTACH_MSG_SCRIPT_CREATOR = 4;
#endregion
public const int LAND_LEVEL = 0;
public const int LAND_RAISE = 1;
public const int LAND_LOWER = 2;
public const int LAND_SMOOTH = 3;
public const int LAND_NOISE = 4;
public const int LAND_REVERT = 5;
public const int LAND_SMALL_BRUSH = 1;
public const int LAND_MEDIUM_BRUSH = 2;
public const int LAND_LARGE_BRUSH = 3;
//Agent Dataserver
public const int DATA_ONLINE = 1;
public const int DATA_NAME = 2;
public const int DATA_BORN = 3;
public const int DATA_RATING = 4;
public const int DATA_SIM_POS = 5;
public const int DATA_SIM_STATUS = 6;
public const int DATA_SIM_RATING = 7;
public const int DATA_PAYINFO = 8;
public const int DATA_SIM_RELEASE = 128;
public const int ANIM_ON = 1;
public const int LOOP = 2;
public const int REVERSE = 4;
public const int PING_PONG = 8;
public const int SMOOTH = 16;
public const int ROTATE = 32;
public const int SCALE = 64;
public const int ALL_SIDES = -1;
public const int LINK_SET = -1;
public const int LINK_ROOT = 1;
public const int LINK_ALL_OTHERS = -2;
public const int LINK_ALL_CHILDREN = -3;
public const int LINK_THIS = -4;
public const int CHANGED_INVENTORY = 1;
public const int CHANGED_COLOR = 2;
public const int CHANGED_SHAPE = 4;
public const int CHANGED_SCALE = 8;
public const int CHANGED_TEXTURE = 16;
public const int CHANGED_LINK = 32;
public const int CHANGED_ALLOWED_DROP = 64;
public const int CHANGED_OWNER = 128;
public const int CHANGED_REGION = 256;
public const int CHANGED_TELEPORT = 512;
public const int CHANGED_REGION_RESTART = 1024;
public const int CHANGED_REGION_START = 1024; //LL Changed the constant from CHANGED_REGION_RESTART
public const int CHANGED_MEDIA = 2048;
public const int CHANGED_ANIMATION = 16384;
public const int TYPE_INVALID = 0;
public const int TYPE_INTEGER = 1;
public const int TYPE_FLOAT = 2;
public const int TYPE_STRING = 3;
public const int TYPE_KEY = 4;
public const int TYPE_VECTOR = 5;
public const int TYPE_ROTATION = 6;
//XML RPC Remote Data Channel
public const int REMOTE_DATA_CHANNEL = 1;
public const int REMOTE_DATA_REQUEST = 2;
public const int REMOTE_DATA_REPLY = 3;
//llHTTPRequest
public const int HTTP_METHOD = 0;
public const int HTTP_MIMETYPE = 1;
public const int HTTP_BODY_MAXLENGTH = 2;
public const int HTTP_VERIFY_CERT = 3;
public const int HTTP_VERBOSE_THROTTLE = 4;
public const int HTTP_CUSTOM_HEADER = 5;
public const int HTTP_PRAGMA_NO_CACHE = 6;
// llSetContentType
public const int CONTENT_TYPE_TEXT = 0; //text/plain
public const int CONTENT_TYPE_HTML = 1; //text/html
public const int CONTENT_TYPE_XML = 2; //application/xml
public const int CONTENT_TYPE_XHTML = 3; //application/xhtml+xml
public const int CONTENT_TYPE_ATOM = 4; //application/atom+xml
public const int CONTENT_TYPE_JSON = 5; //application/json
public const int CONTENT_TYPE_LLSD = 6; //application/llsd+xml
public const int CONTENT_TYPE_FORM = 7; //application/x-www-form-urlencoded
public const int CONTENT_TYPE_RSS = 8; //application/rss+xml
public const int PRIM_MATERIAL = 2;
public const int PRIM_PHYSICS = 3;
public const int PRIM_TEMP_ON_REZ = 4;
public const int PRIM_PHANTOM = 5;
public const int PRIM_POSITION = 6;
public const int PRIM_SIZE = 7;
public const int PRIM_ROTATION = 8;
public const int PRIM_TYPE = 9;
public const int PRIM_TEXTURE = 17;
public const int PRIM_COLOR = 18;
public const int PRIM_BUMP_SHINY = 19;
public const int PRIM_FULLBRIGHT = 20;
public const int PRIM_FLEXIBLE = 21;
public const int PRIM_TEXGEN = 22;
public const int PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake
public const int PRIM_POINT_LIGHT = 23; // Huh?
public const int PRIM_GLOW = 25;
public const int PRIM_TEXT = 26;
public const int PRIM_NAME = 27;
public const int PRIM_DESC = 28;
public const int PRIM_ROT_LOCAL = 29;
public const int PRIM_OMEGA = 32;
public const int PRIM_POS_LOCAL = 33;
public const int PRIM_LINK_TARGET = 34;
public const int PRIM_SLICE = 35;
public const int PRIM_SPECULAR = 36;
public const int PRIM_NORMAL = 37;
public const int PRIM_ALPHA_MODE = 38;
public const int PRIM_TEXGEN_DEFAULT = 0;
public const int PRIM_TEXGEN_PLANAR = 1;
public const int PRIM_TYPE_BOX = 0;
public const int PRIM_TYPE_CYLINDER = 1;
public const int PRIM_TYPE_PRISM = 2;
public const int PRIM_TYPE_SPHERE = 3;
public const int PRIM_TYPE_TORUS = 4;
public const int PRIM_TYPE_TUBE = 5;
public const int PRIM_TYPE_RING = 6;
public const int PRIM_TYPE_SCULPT = 7;
public const int PRIM_HOLE_DEFAULT = 0;
public const int PRIM_HOLE_CIRCLE = 16;
public const int PRIM_HOLE_SQUARE = 32;
public const int PRIM_HOLE_TRIANGLE = 48;
public const int PRIM_MATERIAL_STONE = 0;
public const int PRIM_MATERIAL_METAL = 1;
public const int PRIM_MATERIAL_GLASS = 2;
public const int PRIM_MATERIAL_WOOD = 3;
public const int PRIM_MATERIAL_FLESH = 4;
public const int PRIM_MATERIAL_PLASTIC = 5;
public const int PRIM_MATERIAL_RUBBER = 6;
public const int PRIM_MATERIAL_LIGHT = 7;
public const int PRIM_SHINY_NONE = 0;
public const int PRIM_SHINY_LOW = 1;
public const int PRIM_SHINY_MEDIUM = 2;
public const int PRIM_SHINY_HIGH = 3;
public const int PRIM_BUMP_NONE = 0;
public const int PRIM_BUMP_BRIGHT = 1;
public const int PRIM_BUMP_DARK = 2;
public const int PRIM_BUMP_WOOD = 3;
public const int PRIM_BUMP_BARK = 4;
public const int PRIM_BUMP_BRICKS = 5;
public const int PRIM_BUMP_CHECKER = 6;
public const int PRIM_BUMP_CONCRETE = 7;
public const int PRIM_BUMP_TILE = 8;
public const int PRIM_BUMP_STONE = 9;
public const int PRIM_BUMP_DISKS = 10;
public const int PRIM_BUMP_GRAVEL = 11;
public const int PRIM_BUMP_BLOBS = 12;
public const int PRIM_BUMP_SIDING = 13;
public const int PRIM_BUMP_LARGETILE = 14;
public const int PRIM_BUMP_STUCCO = 15;
public const int PRIM_BUMP_SUCTION = 16;
public const int PRIM_BUMP_WEAVE = 17;
public const int PRIM_SCULPT_TYPE_SPHERE = 1;
public const int PRIM_SCULPT_TYPE_TORUS = 2;
public const int PRIM_SCULPT_TYPE_PLANE = 3;
public const int PRIM_SCULPT_TYPE_CYLINDER = 4;
public const int PRIM_SCULPT_FLAG_INVERT = 64;
public const int PRIM_SCULPT_FLAG_MIRROR = 128;
public const int PROFILE_NONE = 0;
public const int PROFILE_SCRIPT_MEMORY = 1;
public const int MASK_BASE = 0;
public const int MASK_OWNER = 1;
public const int MASK_GROUP = 2;
public const int MASK_EVERYONE = 3;
public const int MASK_NEXT = 4;
public const int PERM_TRANSFER = 8192;
public const int PERM_MODIFY = 16384;
public const int PERM_COPY = 32768;
public const int PERM_MOVE = 524288;
public const int PERM_ALL = 2147483647;
public const int PARCEL_MEDIA_COMMAND_STOP = 0;
public const int PARCEL_MEDIA_COMMAND_PAUSE = 1;
public const int PARCEL_MEDIA_COMMAND_PLAY = 2;
public const int PARCEL_MEDIA_COMMAND_LOOP = 3;
public const int PARCEL_MEDIA_COMMAND_TEXTURE = 4;
public const int PARCEL_MEDIA_COMMAND_URL = 5;
public const int PARCEL_MEDIA_COMMAND_TIME = 6;
public const int PARCEL_MEDIA_COMMAND_AGENT = 7;
public const int PARCEL_MEDIA_COMMAND_UNLOAD = 8;
public const int PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9;
public const int PARCEL_MEDIA_COMMAND_TYPE = 10;
public const int PARCEL_MEDIA_COMMAND_SIZE = 11;
public const int PARCEL_MEDIA_COMMAND_DESC = 12;
public const int PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying
public const int PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts
public const int PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created
public const int PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land
public const int PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage
public const int PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects
public const int PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group
public const int PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents
public const int PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info
public const int PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased
public const int PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel
public const int PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject
public const int PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group
public const int PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation
public const int PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter
public const int PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter
public const int REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled
public const int REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position
public const int REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled
public const int REGION_FLAG_SANDBOX = 0x100; // region is a sandbox
public const int REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions
public const int REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics
public const int REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying
public const int REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports
public const int REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject
//llManageEstateAccess
public const int ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0;
public const int ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1;
public const int ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2;
public const int ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3;
public const int ESTATE_ACCESS_BANNED_AGENT_ADD = 4;
public const int ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5;
public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1);
public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2);
public const string NULL_KEY = "00000000-0000-0000-0000-000000000000";
public const string EOF = "\n\n\n";
public const double PI = 3.14159274f;
public const double TWO_PI = 6.28318548f;
public const double PI_BY_TWO = 1.57079637f;
public const double DEG_TO_RAD = 0.01745329238f;
public const double RAD_TO_DEG = 57.29578f;
public const double SQRT2 = 1.414213538f;
public const int STRING_TRIM_HEAD = 1;
public const int STRING_TRIM_TAIL = 2;
public const int STRING_TRIM = 3;
public const int LIST_STAT_RANGE = 0;
public const int LIST_STAT_MIN = 1;
public const int LIST_STAT_MAX = 2;
public const int LIST_STAT_MEAN = 3;
public const int LIST_STAT_MEDIAN = 4;
public const int LIST_STAT_STD_DEV = 5;
public const int LIST_STAT_SUM = 6;
public const int LIST_STAT_SUM_SQUARES = 7;
public const int LIST_STAT_NUM_COUNT = 8;
public const int LIST_STAT_GEOMETRIC_MEAN = 9;
public const int LIST_STAT_HARMONIC_MEAN = 100;
//ParcelPrim Categories
public const int PARCEL_COUNT_TOTAL = 0;
public const int PARCEL_COUNT_OWNER = 1;
public const int PARCEL_COUNT_GROUP = 2;
public const int PARCEL_COUNT_OTHER = 3;
public const int PARCEL_COUNT_SELECTED = 4;
public const int PARCEL_COUNT_TEMP = 5;
public const int DEBUG_CHANNEL = 0x7FFFFFFF;
public const int PUBLIC_CHANNEL = 0x00000000;
// Constants for llGetObjectDetails
public const int OBJECT_UNKNOWN_DETAIL = -1;
public const int OBJECT_NAME = 1;
public const int OBJECT_DESC = 2;
public const int OBJECT_POS = 3;
public const int OBJECT_ROT = 4;
public const int OBJECT_VELOCITY = 5;
public const int OBJECT_OWNER = 6;
public const int OBJECT_GROUP = 7;
public const int OBJECT_CREATOR = 8;
public const int OBJECT_RUNNING_SCRIPT_COUNT = 9;
public const int OBJECT_TOTAL_SCRIPT_COUNT = 10;
public const int OBJECT_SCRIPT_MEMORY = 11;
public const int OBJECT_SCRIPT_TIME = 12;
public const int OBJECT_PRIM_EQUIVALENCE = 13;
public const int OBJECT_SERVER_COST = 14;
public const int OBJECT_STREAMING_COST = 15;
public const int OBJECT_PHYSICS_COST = 16;
public const int OBJECT_CHARACTER_TIME = 17;
public const int OBJECT_ROOT = 18;
public const int OBJECT_ATTACHED_POINT = 19;
public const int OBJECT_PATHFINDING_TYPE = 20;
public const int OBJECT_PHYSICS = 21;
public const int OBJECT_PHANTOM = 22;
public const int OBJECT_TEMP_ON_REZ = 23;
// Pathfinding types
public const int OPT_OTHER = -1;
public const int OPT_LEGACY_LINKSET = 0;
public const int OPT_AVATAR = 1;
public const int OPT_CHARACTER = 2;
public const int OPT_WALKABLE = 3;
public const int OPT_STATIC_OBSTACLE = 4;
public const int OPT_MATERIAL_VOLUME = 5;
public const int OPT_EXCLUSION_VOLUME = 6;
// for llGetAgentList
public const int AGENT_LIST_PARCEL = 1;
public const int AGENT_LIST_PARCEL_OWNER = 2;
public const int AGENT_LIST_REGION = 4;
// Can not be public const?
public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0);
public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0);
// constants for llSetCameraParams
public const int CAMERA_PITCH = 0;
public const int CAMERA_FOCUS_OFFSET = 1;
public const int CAMERA_FOCUS_OFFSET_X = 2;
public const int CAMERA_FOCUS_OFFSET_Y = 3;
public const int CAMERA_FOCUS_OFFSET_Z = 4;
public const int CAMERA_POSITION_LAG = 5;
public const int CAMERA_FOCUS_LAG = 6;
public const int CAMERA_DISTANCE = 7;
public const int CAMERA_BEHINDNESS_ANGLE = 8;
public const int CAMERA_BEHINDNESS_LAG = 9;
public const int CAMERA_POSITION_THRESHOLD = 10;
public const int CAMERA_FOCUS_THRESHOLD = 11;
public const int CAMERA_ACTIVE = 12;
public const int CAMERA_POSITION = 13;
public const int CAMERA_POSITION_X = 14;
public const int CAMERA_POSITION_Y = 15;
public const int CAMERA_POSITION_Z = 16;
public const int CAMERA_FOCUS = 17;
public const int CAMERA_FOCUS_X = 18;
public const int CAMERA_FOCUS_Y = 19;
public const int CAMERA_FOCUS_Z = 20;
public const int CAMERA_POSITION_LOCKED = 21;
public const int CAMERA_FOCUS_LOCKED = 22;
// constants for llGetParcelDetails
public const int PARCEL_DETAILS_NAME = 0;
public const int PARCEL_DETAILS_DESC = 1;
public const int PARCEL_DETAILS_OWNER = 2;
public const int PARCEL_DETAILS_GROUP = 3;
public const int PARCEL_DETAILS_AREA = 4;
public const int PARCEL_DETAILS_ID = 5;
public const int PARCEL_DETAILS_SEE_AVATARS = 6; // not implemented
//osSetParcelDetails
public const int PARCEL_DETAILS_CLAIMDATE = 10;
// constants for llSetClickAction
public const int CLICK_ACTION_NONE = 0;
public const int CLICK_ACTION_TOUCH = 0;
public const int CLICK_ACTION_SIT = 1;
public const int CLICK_ACTION_BUY = 2;
public const int CLICK_ACTION_PAY = 3;
public const int CLICK_ACTION_OPEN = 4;
public const int CLICK_ACTION_PLAY = 5;
public const int CLICK_ACTION_OPEN_MEDIA = 6;
public const int CLICK_ACTION_ZOOM = 7;
// constants for the llDetectedTouch* functions
public const int TOUCH_INVALID_FACE = -1;
public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0);
public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR;
// constants for llGetPrimMediaParams/llSetPrimMediaParams
public const int PRIM_MEDIA_ALT_IMAGE_ENABLE = 0;
public const int PRIM_MEDIA_CONTROLS = 1;
public const int PRIM_MEDIA_CURRENT_URL = 2;
public const int PRIM_MEDIA_HOME_URL = 3;
public const int PRIM_MEDIA_AUTO_LOOP = 4;
public const int PRIM_MEDIA_AUTO_PLAY = 5;
public const int PRIM_MEDIA_AUTO_SCALE = 6;
public const int PRIM_MEDIA_AUTO_ZOOM = 7;
public const int PRIM_MEDIA_FIRST_CLICK_INTERACT = 8;
public const int PRIM_MEDIA_WIDTH_PIXELS = 9;
public const int PRIM_MEDIA_HEIGHT_PIXELS = 10;
public const int PRIM_MEDIA_WHITELIST_ENABLE = 11;
public const int PRIM_MEDIA_WHITELIST = 12;
public const int PRIM_MEDIA_PERMS_INTERACT = 13;
public const int PRIM_MEDIA_PERMS_CONTROL = 14;
public const int PRIM_MEDIA_CONTROLS_STANDARD = 0;
public const int PRIM_MEDIA_CONTROLS_MINI = 1;
public const int PRIM_MEDIA_PERM_NONE = 0;
public const int PRIM_MEDIA_PERM_OWNER = 1;
public const int PRIM_MEDIA_PERM_GROUP = 2;
public const int PRIM_MEDIA_PERM_ANYONE = 4;
public const int PRIM_PHYSICS_SHAPE_TYPE = 30;
public const int PRIM_PHYSICS_SHAPE_PRIM = 0;
public const int PRIM_PHYSICS_SHAPE_CONVEX = 2;
public const int PRIM_PHYSICS_SHAPE_NONE = 1;
public const int PRIM_PHYSICS_MATERIAL = 31;
public const int DENSITY = 1;
public const int FRICTION = 2;
public const int RESTITUTION = 4;
public const int GRAVITY_MULTIPLIER = 8;
// extra constants for llSetPrimMediaParams
public static readonly LSLInteger LSL_STATUS_OK = new LSLInteger(0);
public static readonly LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSLInteger(1000);
public static readonly LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSLInteger(1001);
public static readonly LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSLInteger(1002);
public static readonly LSLInteger LSL_STATUS_NOT_FOUND = new LSLInteger(1003);
public static readonly LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSLInteger(1004);
public static readonly LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSLInteger(1999);
public static readonly LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSLInteger(2001);
// Constants for default textures
public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f";
public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f";
public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f";
public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903";
public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361";
// Constants for osGetRegionStats
public const int STATS_TIME_DILATION = 0;
public const int STATS_SIM_FPS = 1;
public const int STATS_PHYSICS_FPS = 2;
public const int STATS_AGENT_UPDATES = 3;
public const int STATS_ROOT_AGENTS = 4;
public const int STATS_CHILD_AGENTS = 5;
public const int STATS_TOTAL_PRIMS = 6;
public const int STATS_ACTIVE_PRIMS = 7;
public const int STATS_FRAME_MS = 8;
public const int STATS_NET_MS = 9;
public const int STATS_PHYSICS_MS = 10;
public const int STATS_IMAGE_MS = 11;
public const int STATS_OTHER_MS = 12;
public const int STATS_IN_PACKETS_PER_SECOND = 13;
public const int STATS_OUT_PACKETS_PER_SECOND = 14;
public const int STATS_UNACKED_BYTES = 15;
public const int STATS_AGENT_MS = 16;
public const int STATS_PENDING_DOWNLOADS = 17;
public const int STATS_PENDING_UPLOADS = 18;
public const int STATS_ACTIVE_SCRIPTS = 19;
public const int STATS_SCRIPT_LPS = 20;
// Constants for osNpc* functions
public const int OS_NPC_FLY = 0;
public const int OS_NPC_NO_FLY = 1;
public const int OS_NPC_LAND_AT_TARGET = 2;
public const int OS_NPC_RUNNING = 4;
public const int OS_NPC_SIT_NOW = 0;
public const int OS_NPC_CREATOR_OWNED = 0x1;
public const int OS_NPC_NOT_OWNED = 0x2;
public const int OS_NPC_SENSE_AS_AGENT = 0x4;
public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED";
public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED";
public static readonly LSLInteger RC_REJECT_TYPES = 0;
public static readonly LSLInteger RC_DETECT_PHANTOM = 1;
public static readonly LSLInteger RC_DATA_FLAGS = 2;
public static readonly LSLInteger RC_MAX_HITS = 3;
public static readonly LSLInteger RC_REJECT_AGENTS = 1;
public static readonly LSLInteger RC_REJECT_PHYSICAL = 2;
public static readonly LSLInteger RC_REJECT_NONPHYSICAL = 4;
public static readonly LSLInteger RC_REJECT_LAND = 8;
public static readonly LSLInteger RC_GET_NORMAL = 1;
public static readonly LSLInteger RC_GET_ROOT_KEY = 2;
public static readonly LSLInteger RC_GET_LINK_NUM = 4;
public static readonly LSLInteger RCERR_UNKNOWN = -1;
public static readonly LSLInteger RCERR_SIM_PERF_LOW = -2;
public static readonly LSLInteger RCERR_CAST_TIME_EXCEEDED = 3;
public const int KFM_MODE = 1;
public const int KFM_LOOP = 1;
public const int KFM_REVERSE = 3;
public const int KFM_FORWARD = 0;
public const int KFM_PING_PONG = 2;
public const int KFM_DATA = 2;
public const int KFM_TRANSLATION = 2;
public const int KFM_ROTATION = 1;
public const int KFM_COMMAND = 0;
public const int KFM_CMD_PLAY = 0;
public const int KFM_CMD_STOP = 1;
public const int KFM_CMD_PAUSE = 2;
/// <summary>
/// process name parameter as regex
/// </summary>
public const int OS_LISTEN_REGEX_NAME = 0x1;
/// <summary>
/// process message parameter as regex
/// </summary>
public const int OS_LISTEN_REGEX_MESSAGE = 0x2;
}
}
| |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 Google.Api.Ads.AdManager.Lib;
using Google.Api.Ads.AdManager.Util.v202108;
using Google.Api.Ads.AdManager.v202108;
using DateTime = Google.Api.Ads.AdManager.v202108.DateTime;
namespace Google.Api.Ads.AdManager.Examples.CSharp.v202108
{
/// <summary>
/// This code example gets a forecast for a prospective line item.
/// </summary>
public class GetAvailabilityForecast : SampleBase
{
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return "This code example gets a forecast for a prospective line item.";
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
public static void Main()
{
GetAvailabilityForecast codeExample = new GetAvailabilityForecast();
Console.WriteLine(codeExample.Description);
codeExample.Run(new AdManagerUser());
}
/// <summary>
/// Run the code example.
/// </summary>
public void Run(AdManagerUser user)
{
using (ForecastService forecastService = user.GetService<ForecastService>())
using (NetworkService networkService = user.GetService<NetworkService>())
{
// Set the ID of the advertiser (company) to forecast for. Setting an advertiser
// will cause the forecast to apply the appropriate unified blocking rules.
long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));
String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;
System.DateTime tomorrow = System.DateTime.Now.AddDays(1);
// Create prospective line item.
LineItem lineItem = new LineItem()
{
targeting = new Targeting()
{
inventoryTargeting = new InventoryTargeting()
{
targetedAdUnits = new AdUnitTargeting[] {
new AdUnitTargeting()
{
adUnitId = rootAdUnitId,
includeDescendants = true
}
}
}
},
creativePlaceholders = new CreativePlaceholder[] {
new CreativePlaceholder()
{
size = new Size()
{
width = 300,
height = 250
}
}
},
lineItemType = LineItemType.SPONSORSHIP,
// Set the line item to run for 5 days.
startDateTime = DateTimeUtilities.FromDateTime(
tomorrow, "America/New_York"),
endDateTime = DateTimeUtilities.FromDateTime(
tomorrow.AddDays(5), "America/New_York"),
// Set the cost type to match the unit type.
costType = CostType.CPM,
primaryGoal = new Goal()
{
goalType = GoalType.DAILY,
unitType = UnitType.IMPRESSIONS,
units = 50L
}
};
try
{
// Get availability forecast.
AvailabilityForecastOptions options = new AvailabilityForecastOptions()
{
includeContendingLineItems = true,
// Targeting criteria breakdown can only be included if breakdowns
// are not speficied.
includeTargetingCriteriaBreakdown = false,
breakdown = new ForecastBreakdownOptions
{
timeWindows = new DateTime[] {
lineItem.startDateTime,
DateTimeUtilities.FromDateTime(tomorrow.AddDays(1),
"America/New_York"),
DateTimeUtilities.FromDateTime(tomorrow.AddDays(2),
"America/New_York"),
DateTimeUtilities.FromDateTime(tomorrow.AddDays(3),
"America/New_York"),
DateTimeUtilities.FromDateTime(tomorrow.AddDays(4),
"America/New_York"),
lineItem.endDateTime
},
targets = new ForecastBreakdownTarget[] {
new ForecastBreakdownTarget()
{
// Optional name field to identify this breakdown
// in the response.
name = "United States",
targeting = new Targeting()
{
inventoryTargeting = new InventoryTargeting()
{
targetedAdUnits = new AdUnitTargeting[] {
new AdUnitTargeting()
{
adUnitId = rootAdUnitId,
includeDescendants = true
}
}
},
geoTargeting = new GeoTargeting()
{
targetedLocations = new Location[] {
new Location() { id = 2840L }
}
}
}
}, new ForecastBreakdownTarget()
{
// Optional name field to identify this breakdown
// in the response.
name = "Geneva",
targeting = new Targeting()
{
inventoryTargeting = new InventoryTargeting()
{
targetedAdUnits = new AdUnitTargeting[] {
new AdUnitTargeting()
{
adUnitId = rootAdUnitId,
includeDescendants = true
}
}
},
geoTargeting = new GeoTargeting()
{
targetedLocations = new Location[] {
new Location () { id = 20133L }
}
}
}
}
}
}
};
ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem()
{
advertiserId = advertiserId,
lineItem = lineItem
};
AvailabilityForecast forecast =
forecastService.getAvailabilityForecast(prospectiveLineItem, options);
// Display results.
long matched = forecast.matchedUnits;
double availablePercent =
(double)(forecast.availableUnits / (matched * 1.0)) * 100;
String unitType = forecast.unitType.ToString().ToLower();
Console.WriteLine($"{matched} {unitType} matched.");
Console.WriteLine($"{availablePercent}% {unitType} available.");
if (forecast.possibleUnitsSpecified)
{
double possiblePercent =
(double)(forecast.possibleUnits / (matched * 1.0)) * 100;
Console.WriteLine($"{possiblePercent}% {unitType} possible.");
}
var contendingLineItems =
forecast.contendingLineItems ?? new ContendingLineItem[] { };
Console.WriteLine($"{contendingLineItems.Length} contending line items.");
if (forecast.breakdowns != null)
{
foreach (ForecastBreakdown breakdown in forecast.breakdowns)
{
Console.WriteLine("Forecast breakdown for {0} to {1}",
DateTimeUtilities.ToString(breakdown.startTime, "yyyy-MM-dd"),
DateTimeUtilities.ToString(breakdown.endTime, "yyyy-MM-dd"));
foreach (ForecastBreakdownEntry entry in breakdown.breakdownEntries)
{
Console.WriteLine($"\t{entry.name}");
long breakdownMatched = entry.forecast.matched;
Console.WriteLine($"\t\t{breakdownMatched} {unitType} matched.");
if (breakdownMatched > 0)
{
long breakdownAvailable = entry.forecast.available;
double breakdownAvailablePercent =
(double)(breakdownAvailable / (breakdownMatched * 1.0)) * 100;
Console.WriteLine(
$"\t\t{breakdownAvailablePercent}% {unitType} available");
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message);
}
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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 Alachisoft.NCache.Caching;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Monitoring;
using System.Collections.Generic;
using Alachisoft.NCache.Runtime.Events;
using Runtime = Alachisoft.NCache.Runtime;
using System.Text;
using Alachisoft.NCache.SocketServer.RuntimeLogging;
using System.Diagnostics;
using Alachisoft.NCache.Common.Locking;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common.Protobuf;
using Alachisoft.NCache.Common.Pooling;
using Alachisoft.NCache.Util;
using Alachisoft.NCache.SocketServer.Util;
namespace Alachisoft.NCache.SocketServer.Command
{
class DeleteCommand : CommandBase
{
protected struct CommandInfo
{
public bool DoAsync;
public long RequestId;
public string Key;
public BitSet FlagMap;
public short DsItemRemovedId;
public object LockId;
public ulong Version;
public string ProviderName;
public LockAccessType LockAccessType;
}
private OperationResult _removeResult = OperationResult.Success;
CommandInfo cmdInfo;
internal override OperationResult OperationResult
{
get
{
return _removeResult;
}
}
public override bool CanHaveLargedata
{
get
{
return true;
}
}
public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
{
int overload;
string exception = null;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
try
{
try
{
overload = command.MethodOverload;
cmdInfo = ParseCommand(command, clientManager);
}
catch (System.Exception exc)
{
_removeResult = OperationResult.Failure;
if (!base.immatureId.Equals("-2"))
{
//PROTOBUF:RESPONSE
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion));
}
return;
}
NCache nCache = clientManager.CmdExecuter as NCache;
if (!cmdInfo.DoAsync)
{
try
{
Notifications notification = null;
if (cmdInfo.DsItemRemovedId != -1)
{
notification = new Notifications(clientManager.ClientID, -1, -1, -1, -1, cmdInfo.DsItemRemovedId
, Runtime.Events.EventDataFilter.None, Runtime.Events.EventDataFilter.None); //DataFilter not required
}
OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
operationContext.Add(OperationContextFieldName.RaiseCQNotification, true);
operationContext.Add(OperationContextFieldName.MethodOverload, overload);
operationContext.Add(OperationContextFieldName.ClientId, clientManager.ClientID);
CommandsUtil.PopulateClientIdInContext(ref operationContext, clientManager.ClientAddress);
nCache.Cache.Delete(cmdInfo.Key, cmdInfo.FlagMap, notification, cmdInfo.LockId, cmdInfo.Version, cmdInfo.LockAccessType, operationContext);
stopWatch.Stop();
//PROTOBUF: RESPONSE
DeleteResponse deleteResponse = new DeleteResponse();
if (clientManager.ClientVersion >= 5000)
{
ResponseHelper.SetResponse(deleteResponse, command.requestID, command.commandID);
_serializedResponsePackets.Add(ResponseHelper.SerializeResponse(deleteResponse, Response.Type.DELETE));
}
else
{
//PROTOBUF:RESPONSE
Response response = new Response();
response.deleteResponse = deleteResponse;
ResponseHelper.SetResponse(response, command.requestID, command.commandID, Response.Type.DELETE);
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
}
}
catch (System.Exception exc)
{
_removeResult = OperationResult.Failure;
exception = exc.ToString();
//PROTOBUF:RESPONSE
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion));
}
finally
{
TimeSpan executionTime = stopWatch.Elapsed;
try
{
if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
{
APILogItemBuilder log = new APILogItemBuilder(MethodsName.DELETE.ToLower());
log.GenerateDeleteAPILogItem(cmdInfo.Key, cmdInfo.FlagMap, cmdInfo.LockId, (long)cmdInfo.Version, cmdInfo.LockAccessType, cmdInfo.ProviderName, cmdInfo.DsItemRemovedId, overload, exception, executionTime, clientManager.ClientID.ToLower(), clientManager.ClientSocketId.ToString());
}
}
catch { }
}
}
else
{
object[] package = null;
if (cmdInfo.RequestId != -1 || cmdInfo.DsItemRemovedId != -1)
{
package = new object[] { cmdInfo.Key, cmdInfo.FlagMap, new Notifications(clientManager.ClientID,
Convert.ToInt32(cmdInfo.RequestId),
-1,
-1,
(short)(cmdInfo.RequestId == -1 ? -1 : 0),
cmdInfo.DsItemRemovedId,
EventDataFilter.None, EventDataFilter.None) }; //DataFilter not required
}
else
{
package = new object[] { cmdInfo.Key, cmdInfo.FlagMap, null, cmdInfo.ProviderName };
}
OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
operationContext.Add(OperationContextFieldName.RaiseCQNotification, true);
operationContext.Add(OperationContextFieldName.MethodOverload, overload);
nCache.Cache.RemoveAsync(package, operationContext);
stopWatch.Stop();
TimeSpan executionTime = stopWatch.Elapsed;
try
{
if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
{
APILogItemBuilder log = new APILogItemBuilder(MethodsName.DELETEASYNC.ToLower());
log.GenerateDeleteAPILogItem(cmdInfo.Key, cmdInfo.FlagMap, cmdInfo.LockId, (long)cmdInfo.Version, cmdInfo.LockAccessType, cmdInfo.ProviderName, cmdInfo.DsItemRemovedId, overload, exception, executionTime, clientManager.ClientID.ToLower(), clientManager.ClientSocketId.ToString());
}
}
catch { }
}
}
finally
{
MiscUtil.ReturnBitsetToPool(cmdInfo.FlagMap, clientManager.CacheTransactionalPool);
cmdInfo.FlagMap.MarkFree(NCModulesConstants.SocketServer);
}
}
private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager)
{
CommandInfo cmdInfo = new CommandInfo();
Alachisoft.NCache.Common.Protobuf.DeleteCommand removeCommand = command.deleteCommand;
cmdInfo.DoAsync = removeCommand.isAsync;
cmdInfo.DsItemRemovedId = (short)removeCommand.datasourceItemRemovedCallbackId;
BitSet bitset = BitSet.CreateAndMarkInUse(clientManager.CacheTransactionalPool, NCModulesConstants.SocketServer);
bitset.Data = ((byte)removeCommand.flag);
cmdInfo.FlagMap = bitset;
cmdInfo.Key = clientManager.CacheTransactionalPool.StringPool.GetString(removeCommand.key);
cmdInfo.LockAccessType = (LockAccessType)removeCommand.lockAccessType;
cmdInfo.LockId = removeCommand.lockId;
cmdInfo.RequestId = removeCommand.requestId;
cmdInfo.Version = removeCommand.version;
cmdInfo.ProviderName = !string.IsNullOrEmpty(removeCommand.providerName) ? removeCommand.providerName : null;
return cmdInfo;
}
}
}
| |
// $Id$
//
// 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;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Org.Apache.Etch.Bindings.Csharp.Msg;
using Org.Apache.Etch.Bindings.Csharp.Support;
using Org.Apache.Etch.Bindings.Csharp.Util;
using NUnit.Framework;
namespace Org.Apache.Etch.Bindings.Csharp.Transport
{
[TestFixture]
public class TestPlainMailbox : MailboxManager
{
[SetUp]
public void Init()
{
unregistered = false;
// AlarmManager.SetAlarmManager(null);
redelivered = new List<Element>();
vf = new MyValueFactory();
mt_foo = new XType("foo");
foo_msg = new Message(mt_foo, vf);
fred_who = new WhoAmI();
mt_bar = new XType("bar");
bar_msg = new Message(mt_bar, vf);
alice_who = new WhoAmI();
notify = new MyNotify();
notify1x = new MyNotify();
}
[Test]
public void construct1()
{
testConstruct(1L);
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void construct2()
{
new PlainMailbox(null, 1L);
}
[Test]
public void closeDelivery1()
{
// open mailbox and close it for delivery while empty.
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkCloseDelivery(mb, true);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void closeDelivery2()
{
// open mailbox and close it for delivery while not empty.
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkDeliver(mb, true, alice_who, foo_msg);
checkMailbox(mb, false, true, false, false, 0);
checkCloseDelivery(mb, true);
checkMailbox(mb, false, true, true, true, 0);
}
[Test]
public void closeDelivery3()
{
// open mailbox and close it for delivery twice.
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkCloseDelivery(mb, true);
checkMailbox(mb, true, false, true, true, 0);
checkCloseDelivery(mb, false);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void closeRead1()
{
// open mailbox and close it for reading while empty.
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkCloseRead(mb, true);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void closeRead2()
{
// open mailbox and close it for reading while not empty.
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkDeliver(mb, true, alice_who, foo_msg);
checkMailbox(mb, false, true, false, false, 0);
checkCloseRead(mb, true);
checkMailbox(mb, true, false, true, true, 1);
checkRedelivered(0, alice_who, foo_msg);
}
[Test]
public void closeRead3()
{
// open mailbox and close it for reading twice while empty.
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkCloseRead(mb, true);
checkMailbox(mb, true, false, true, true, 0);
checkCloseRead(mb, false);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void closeRead4()
{
// open mailbox and close it for reading twice while not empty.
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkDeliver(mb, true, alice_who, foo_msg);
checkMailbox(mb, false, true, false, false, 0);
checkCloseRead(mb, true);
checkMailbox(mb, true, false, true, true, 1);
checkRedelivered(0, alice_who, foo_msg);
checkCloseRead(mb, false);
checkMailbox(mb, true, false, true, true, 1);
checkRedelivered(0, alice_who, foo_msg);
}
[Test]
public void full1()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkDeliver(mb, true, fred_who, foo_msg);
checkMailbox(mb, false, true, false, false, 0);
checkDeliver(mb, false, alice_who, bar_msg);
checkMailbox(mb, false, true, false, false, 0);
}
[Test]
public void full2()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkDeliver(mb, true, fred_who, foo_msg);
checkMailbox(mb, false, true, false, false, 0);
checkDeliver(mb, false, alice_who, bar_msg);
checkMailbox(mb, false, true, false, false, 0);
checkDeliver(mb, false, fred_who, bar_msg);
checkMailbox(mb, false, true, false, false, 0);
}
[Test]
public void read1()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkDeliver(mb, true, alice_who, bar_msg);
checkMailbox(mb, false, true, false, false, 0);
checkRead(mb, true, alice_who, bar_msg);
checkMailbox(mb, true, false, false, false, 0);
checkCloseDelivery(mb, true);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void read2()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkDeliver(mb, true, alice_who, bar_msg);
checkMailbox(mb, false, true, false, false, 0);
checkCloseDelivery(mb, true);
checkMailbox(mb, false, true, true, true, 0);
checkRead(mb, true, alice_who, bar_msg);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void read3()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkDeliver(mb, true, alice_who, bar_msg);
checkMailbox(mb, false, true, false, false, 0);
checkCloseDelivery(mb, true);
checkMailbox(mb, false, true, true, true, 0);
checkRead(mb, true, alice_who, bar_msg);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void read4()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkCloseDelivery(mb, true);
checkMailbox(mb, true, false, true, true, 0);
checkRead(mb, false, null, null);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
[Ignore]
public void read5()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
Thread.Sleep(1000);
checkRead(mb, false, null, null);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
[Ignore]
public void read6()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkRead(mb, false, null, null);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void read7()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkRead(mb, -1, false, null, null);
checkMailbox(mb, true, false, false, false, 0);
}
[Test]
public void read8()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkRead(mb, 1, false, null, null);
checkMailbox(mb, true, false, false, false, 0);
}
[Test]
public void deliver1()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
checkMailbox(mb, true, false, false, false, 0);
checkCloseDelivery(mb, true);
checkMailbox(mb, true, false, true, true, 0);
checkDeliver(mb, false, fred_who, bar_msg);
checkMailbox(mb, true, false, true, true, 0);
}
[Test]
public void notify1()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
notify.checkMailboxStatus(false, null, null, false);
Object state = new Object();
mb.RegisterNotify(notify, state, 0);
notify.checkMailboxStatus(false, null, null, false);
checkCloseDelivery(mb, true);
notify.checkMailboxStatus(true, mb, state, true);
}
[Test]
public void notify2()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
notify.checkMailboxStatus(false, null, null, false);
Object state = new Object();
mb.RegisterNotify(notify, state, 1000);
notify.checkMailboxStatus(false, null, null, false);
Thread.Sleep(2000);
notify.checkMailboxStatus(true, mb, state, true);
}
[Test]
public void notify3()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
notify.checkMailboxStatus(false, null, null, false);
Object state = new Object();
mb.RegisterNotify(notify, state, 0);
notify.checkMailboxStatus(false, null, null, false);
Thread.Sleep(2000);
notify.checkMailboxStatus(false, null, null, false);
}
[Test]
public void notify4()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
notify.checkMailboxStatus(false, null, null, false);
Object state = new Object();
mb.RegisterNotify(notify, state, 0);
notify.checkMailboxStatus(false, null, null, false);
mb.Message(alice_who, foo_msg);
notify.checkMailboxStatus(true, mb, state, false);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void reg1()
{
// notify == null
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(null, null, 0);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void reg2()
{
// maxDelay < 0
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, -1);
}
[Test]
public void reg3()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, 0);
}
[Test]
[ExpectedException(typeof(Exception))]
public void reg4()
{
// this.notify != null
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, 0);
mb.RegisterNotify(notify, null, 0);
}
[Test]
[ExpectedException(typeof(Exception))]
public void reg5()
{
// this.notify != null
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, 0);
mb.RegisterNotify(notify1x, null, 0);
}
[Test]
public void unreg1()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.UnregisterNotify(notify);
}
[Test]
public void unreg2()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, 0);
mb.UnregisterNotify(notify);
}
[Test]
public void unreg3()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, 0);
mb.UnregisterNotify(notify);
mb.UnregisterNotify(notify);
mb.UnregisterNotify(notify1x);
}
[Test]
public void unreg4()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, 0);
mb.UnregisterNotify(notify);
mb.RegisterNotify(notify, null, 0);
mb.UnregisterNotify(notify);
mb.RegisterNotify(notify1x, null, 0);
mb.UnregisterNotify(notify1x);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void unreg5()
{
// notify != this.notify
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, 0);
mb.UnregisterNotify(notify1x);
}
[Test]
public void unreg6()
{
PlainMailbox mb = new PlainMailbox(this, 1L);
mb.RegisterNotify(notify, null, 30);
mb.UnregisterNotify(notify);
}
///////////////////
// HELPFUL STUFF //
///////////////////
private static ValueFactory vf;
private static XType mt_foo;
private Message foo_msg;
private Who fred_who;
private static XType mt_bar;
private Message bar_msg;
private Who alice_who;
private MyNotify notify;
private MyNotify notify1x;
private void testConstruct(long messageId)
{
PlainMailbox mb = new PlainMailbox(this, messageId);
Assert.AreEqual(this, mb.GetMailboxManager());
Assert.AreEqual(messageId, mb.GetMessageId());
}
private void checkDeliver(PlainMailbox mb, bool handled, Who who,
Message msg)
{
Assert.AreEqual(handled, mb.Message(who, msg));
}
private void checkRead(PlainMailbox mb, bool present, Who who, Message msg)
{
Element e = mb.Read();
if (present)
checkElement(e, who, msg);
else
Assert.IsNull(e);
}
private void checkRead(PlainMailbox mb, int maxDelay, bool present,
Who who, Message msg)
{
Element e = mb.Read(maxDelay);
if (present)
checkElement(e, who, msg);
else
Assert.IsNull(e);
}
private void checkRedelivered(int index, Who who, Message msg)
{
Element e = redelivered[index];
checkElement(e, who, msg);
}
private void checkElement(Element e, Who who, Message msg)
{
Assert.IsNotNull(e);
Assert.AreSame(who, e.sender);
Assert.AreSame(msg, e.msg);
}
private void checkMailbox(PlainMailbox mb, bool empty, bool full,
bool closed, bool unreg, int size)
{
Assert.AreEqual(empty, mb.IsEmpty());
Assert.AreEqual(full, mb.IsFull());
Assert.AreEqual(closed, mb.IsClosed());
Assert.AreEqual(unreg, unregistered);
Assert.AreEqual(size, redelivered.Count);
}
private void checkCloseRead(PlainMailbox mb, bool closed)
{
Assert.AreEqual(closed, mb.CloseRead());
}
private void checkCloseDelivery(PlainMailbox mb, bool closed)
{
Assert.AreEqual(closed, mb.CloseDelivery());
}
////////////////////////////////
// MailboxManagerIntf methods //
////////////////////////////////
public void Redeliver(Who sender, Message msg)
{
redelivered.Add(new Element(sender, msg));
}
private List<Element> redelivered;
public void Unregister(Mailbox mb)
{
unregistered = true;
}
private bool unregistered;
////////////////////
// MyValueFactory //
////////////////////
public class MyValueFactory : ValueFactory
{
public StructValue ExportCustomValue(Object value)
{
throw new NotSupportedException();
}
public XType GetCustomStructType(Type c)
{
throw new NotSupportedException();
}
public long? GetInReplyTo(Message msg)
{
throw new NotSupportedException();
}
public long? GetMessageId(Message msg)
{
throw new NotSupportedException();
}
public Encoding GetStringEncoding()
{
throw new NotSupportedException();
}
public XType GetType(int id)
{
throw new NotSupportedException();
}
public XType GetType(String name)
{
throw new NotSupportedException();
}
public ICollection<XType> GetTypes()
{
throw new NotSupportedException(); ;
}
public XType Get_mt__Etch_AuthException()
{
throw new NotSupportedException();
}
public XType Get_mt__Etch_RuntimeException()
{
throw new NotSupportedException(); ;
}
public XType get_mt__exception()
{
throw new NotSupportedException();
}
public Object ImportCustomValue(StructValue sv)
{
throw new NotSupportedException();
}
public void SetInReplyTo(Message msg, long? msgid)
{
throw new NotSupportedException(); ;
}
public void SetMessageId(Message msg, long? msgid)
{
throw new NotSupportedException(); ;
}
public void AddType(XType type)
{
throw new Exception("The method or operation is not implemented.");
}
public void LockDynamicTypes()
{
throw new Exception("The method or operation is not implemented.");
}
public void UnlockDynamicTypes()
{
throw new Exception("The method or operation is not implemented.");
}
public Field Get_mf__messageId()
{
throw new Exception("The method or operation is not implemented.");
}
public Field Get_mf__inReplyTo()
{
throw new Exception("The method or operation is not implemented.");
}
public Validator.Level GetLevel()
{
return Validator.Level.FULL;
}
public Validator.Level SetLevel(Validator.Level level)
{
throw new Exception("The method or operation is not implemented.");
}
}
public class WhoAmI : Who
{
}
public class MyNotify : Notify
{
public void mailboxStatus(Mailbox mb, Object state, bool closed)
{
mailboxStatus1 = true;
this.mailbox = mb;
this.state = state;
this.closed = closed;
}
private bool mailboxStatus1;
private Mailbox mailbox;
private Object state;
private bool closed;
public void checkMailboxStatus(bool mailboxStatus, Mailbox mailbox,
Object state, bool closed)
{
Assert.AreEqual(mailboxStatus, this.mailboxStatus1);
Assert.AreSame(mailbox, this.mailbox);
Assert.AreSame(state, this.state);
Assert.AreEqual(closed, this.closed);
}
}
#region MailboxManager Members
public Mailbox TransportCall(Who recipient, Message msg)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region TransportMessage Members
public void TransportMessage(Who recipient, Message msg)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region Transport<SessionMessage> Members
public object TransportQuery(object query)
{
throw new Exception("The method or operation is not implemented.");
}
public void TransportControl(object control, object value)
{
throw new Exception("The method or operation is not implemented.");
}
public void TransportNotify(object eventObj)
{
throw new Exception("The method or operation is not implemented.");
}
public void SetSession(SessionMessage session)
{
throw new Exception("The method or operation is not implemented.");
}
public SessionMessage GetSession()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region SessionMessage Members
public bool SessionMessage(Who sender, Message msg)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region Session Members
public object SessionQuery(object query)
{
throw new Exception("The method or operation is not implemented.");
}
public void SessionControl(object control, object value)
{
throw new Exception("The method or operation is not implemented.");
}
public void SessionNotify(object eventObj)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
// 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 Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class SetItemStrStrTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
string itm; // item
// [] initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
// [] set Item() on empty collection
//
nvc.Clear();
nvc[null] = "nullItem";
if (nvc.Count != 1)
{
Assert.False(true, "Error, failed to add item");
}
if (nvc[null] == null)
{
Assert.False(true, "Error, returned null");
}
else
{
if (String.Compare(nvc[null], "nullItem") != 0)
{
Assert.False(true, "Error, wrong value");
}
}
nvc.Clear();
nvc["some_string"] = "someItem";
if (nvc.Count != 1)
{
Assert.False(true, "Error, failed to add item");
}
if (nvc["some_string"] == null)
{
Assert.False(true, "Error, returned null");
}
else
{
if (String.Compare(nvc["some_string"], "someItem") != 0)
{
Assert.False(true, "Error, wrong value");
}
}
// [] set Item(string) on collection filled with simple strings
//
nvc.Clear();
cnt = nvc.Count;
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
if (nvc.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
}
//
for (int i = 0; i < len; i++)
{
nvc[keys[i]] = "Item" + i;
if (String.Compare(nvc[keys[i]], "Item" + i) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], "Item" + i));
}
}
//
// Intl strings
// [] set Item(string) on collection filled with Intl strings
//
string[] intlValues = new string[len * 3];
// fill array with unique strings
//
for (int i = 0; i < len * 3; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]);
}
if (nvc.Count != (len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
}
for (int i = 0; i < len; i++)
{
//
nvc[intlValues[i + len]] = intlValues[i + len * 2];
if (String.Compare(nvc[intlValues[i + len]], intlValues[i + len * 2]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i + len * 2]));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
}
// lowercase key
if (String.Compare(nvc[intlValuesLower[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc[intlValuesLower[i + len]], intlValues[i]));
}
if (!caseInsensitive && String.Compare(nvc[intlValues[i + len]], intlValuesLower[i]) == 0)
{
Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i));
}
// set to lowercase value
nvc[intlValues[i + len]] = intlValuesLower[i];
// uppercase key
if (!caseInsensitive && String.Compare(nvc[intlValues[i + len]], intlValues[i]) == 0)
{
Assert.False(true, string.Format("Error, failed to set to uppercase value", i));
}
// lowercase key
if (!caseInsensitive && String.Compare(nvc[intlValuesLower[i + len]], intlValues[i]) == 0)
{
Assert.False(true, string.Format("Error, failed to set to lowercase value", i));
}
if (String.Compare(nvc[intlValues[i + len]], intlValuesLower[i]) != 0)
{
Assert.False(true, string.Format("Error, returned uppercase when set to lowercase", i));
}
}
// [] set Item(string) on filled collection - multiple items with the same key
//
nvc.Clear();
len = values.Length;
string k = "keykey";
string k1 = "hm1";
string exp = "";
string exp1 = "";
string newVal = "nEw1,nEw2";
string newVal1 = "Hello,hello,hELLo";
for (int i = 0; i < len; i++)
{
nvc.Add(k, "Value" + i);
nvc.Add(k1, "iTem" + i);
if (i < len - 1)
{
exp += "Value" + i + ",";
exp1 += "iTem" + i + ",";
}
else
{
exp += "Value" + i;
exp1 += "iTem" + i;
}
}
if (nvc.Count != 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
}
if (String.Compare(nvc[k], exp) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc[k], exp));
}
nvc[k] = newVal;
if (String.Compare(nvc[k], newVal) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc[k], newVal));
}
// Values array should contain 1 item
if (nvc.GetValues(k).Length != 1)
{
Assert.False(true, string.Format("Error, number of values is {0} instead of 1", nvc.GetValues(k).Length));
}
if (String.Compare(nvc[k1], exp1) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc[k1], exp1));
}
nvc[k1] = newVal1;
if (String.Compare(nvc[k1], newVal1) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc[k1], newVal1));
}
// Values array should contain 1 item
if (nvc.GetValues(k1).Length != 1)
{
Assert.False(true, string.Format("Error, number of values is {0} instead of 1", nvc.GetValues(k).Length));
}
//
// [] set Item(null) - when there is an item with null key
//
cnt = nvc.Count;
nvc.Add(null, "nullValue");
if (String.Compare(nvc[null], "nullValue") != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc[null], "nullValue"));
}
nvc[null] = "newnewValue";
if (String.Compare(nvc[null], "newnewValue") != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc[null], "newnewValue"));
}
//
// [] set Item(null) - when no item with null key
//
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
nvc[null] = "newNullValue";
itm = nvc[null];
if (String.Compare(itm, "newNullValue") != 0)
{
Assert.False(true, "Error, returned unexpected value ");
}
}
}
}
| |
// 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.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for all Streams. Provides
** default implementations of asynchronous reads & writes, in
** terms of the synchronous reads & writes (and vice versa).
**
**
===========================================================*/
using System;
using System.Buffers;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace System.IO {
[Serializable]
[ComVisible(true)]
public abstract class Stream : MarshalByRefObject, IDisposable {
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int _DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
[NonSerialized]
private ReadWriteTask _activeReadWriteTask;
[NonSerialized]
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead {
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek {
[Pure]
get;
}
[ComVisible(false)]
public virtual bool CanTimeout {
[Pure]
get {
return false;
}
}
public abstract bool CanWrite {
[Pure]
get;
}
public abstract long Length {
get;
}
public abstract long Position {
get;
set;
}
[ComVisible(false)]
public virtual int ReadTimeout {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
set {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
}
[ComVisible(false)]
public virtual int WriteTimeout {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
set {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
}
[ComVisible(false)]
public Task CopyToAsync(Stream destination)
{
int bufferSize = _DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// If we go down this branch, it means there are
// no bytes left in this stream.
// Ideally we would just return Task.CompletedTask here,
// but CopyToAsync(Stream, int, CancellationToken) was already
// virtual at the time this optimization was introduced. So
// if it does things like argument validation (checking if destination
// is null and throwing an exception), then await fooStream.CopyToAsync(null)
// would no longer throw if there were no bytes left. On the other hand,
// we also can't roll our own argument validation and return Task.CompletedTask,
// because it would be a breaking change if the stream's override didn't throw before,
// or in a different order. So for simplicity, we just set the bufferSize to 1
// (not 0 since the default implementation throws for 0) and forward to the virtual method.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
return CopyToAsync(destination, bufferSize);
}
[ComVisible(false)]
public Task CopyToAsync(Stream destination, Int32 bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
[ComVisible(false)]
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
Contract.Requires(destination != null);
Contract.Requires(bufferSize > 0);
Contract.Requires(CanRead);
Contract.Requires(destination.CanWrite);
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine
try
{
while (true)
{
int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0) break;
if (bytesRead > bufferSize) bufferSize = bytesRead;
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
}
}
finally
{
Array.Clear(buffer, 0, bufferSize); // clear only the most we used
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = _DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// No bytes left in stream
// Call the other overload with a bufferSize of 1,
// in case it's made virtual in the future
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
CopyTo(destination, bufferSize);
}
public virtual void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
int highwaterMark = 0;
try
{
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
{
if (read > highwaterMark) highwaterMark = read;
destination.Write(buffer, 0, read);
}
}
finally
{
Array.Clear(buffer, 0, highwaterMark); // clear only the most we used
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
}
// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable. However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern. We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup starting in V2.
public virtual void Close()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public abstract void Flush();
[ComVisible(false)]
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
[ComVisible(false)]
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
Contract.Ensures(Contract.Result<WaitHandle>() != null);
return new ManualResetEvent(false);
}
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginReadInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanRead) __Error.ReadNotSupported();
// To avoid a race with a stream's position pointer & generating race conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync();
}
else
{
semaphore.Wait();
}
// Create the task to asynchronously do a Read. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Read.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Read and return the number of bytes read
return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
public virtual int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
var readTask = _activeReadWriteTask;
if (readTask == null)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
else if (readTask != asyncResult)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
else if (!readTask._isRead)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
finally
{
FinishTrackingAsyncOperation();
}
}
[ComVisible(false)]
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
[ComVisible(false)]
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<int>(cancellationToken)
: BeginEndReadAsync(buffer, offset, count);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndRead();
private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndRead())
{
// If the Stream does not override Begin/EndRead, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task<Int32>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<Int32>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler
}
private struct ReadWriteParameters // struct for arguments to Read and Write calls
{
internal byte[] Buffer;
internal int Offset;
internal int Count;
}
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginWriteInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanWrite) __Error.WriteNotSupported();
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block
}
else
{
semaphore.Wait(); // synchronously wait here
}
// Create the task to asynchronously do a Write. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Write.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Write
thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
// preconditions in async methods that await.
Debug.Assert(asyncWaiter != null); // Ditto
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
Debug.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) => {
Debug.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Contract.Requires(readWriteTask != null);
Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
// two interlocked operations. However, if ReadWriteTask is ever changed to use
// a cancellation token, this should be changed to use Start.
_activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one
readWriteTask.m_taskScheduler = TaskScheduler.Default;
readWriteTask.ScheduleAndStart(needsProtection: false);
}
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult==null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
var writeTask = _activeReadWriteTask;
if (writeTask == null)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
else if (writeTask != asyncResult)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
else if (writeTask._isRead)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
FinishTrackingAsyncOperation();
}
}
// Task used by BeginRead / BeginWrite to do Read / Write asynchronously.
// A single instance of this task serves four purposes:
// 1. The work item scheduled to run the Read / Write operation
// 2. The state holding the arguments to be passed to Read / Write
// 3. The IAsyncResult returned from BeginRead / BeginWrite
// 4. The completion action that runs to invoke the user-provided callback.
// This last item is a bit tricky. Before the AsyncCallback is invoked, the
// IAsyncResult must have completed, so we can't just invoke the handler
// from within the task, since it is the IAsyncResult, and thus it's not
// yet completed. Instead, we use AddCompletionAction to install this
// task as its own completion handler. That saves the need to allocate
// a separate completion handler, it guarantees that the task will
// have completed by the time the handler is invoked, and it allows
// the handler to be invoked synchronously upon the completion of the
// task. This all enables BeginRead / BeginWrite to be implemented
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream _stream;
internal byte [] _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback _callback;
private ExecutionContext _context;
internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC
{
_stream = null;
_buffer = null;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public ReadWriteTask(
bool isRead,
bool apm,
Func<object,int> function, object state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
Contract.Requires(function != null);
Contract.Requires(stream != null);
Contract.Requires(buffer != null);
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// Store the arguments
_isRead = isRead;
_apm = apm;
_stream = stream;
_buffer = buffer;
_offset = offset;
_count = count;
// If a callback was provided, we need to:
// - Store the user-provided handler
// - Capture an ExecutionContext under which to invoke the handler
// - Add this task as its own completion handler so that the Invoke method
// will run the callback when this task completes.
if (callback != null)
{
_callback = callback;
_context = ExecutionContext.Capture(ref stackMark,
ExecutionContext.CaptureOptions.OptimizeDefaultCase | ExecutionContext.CaptureOptions.IgnoreSyncCtx);
base.AddCompletionAction(this);
}
}
private static void InvokeAsyncCallback(object completedTask)
{
var rwc = (ReadWriteTask)completedTask;
var callback = rwc._callback;
rwc._callback = null;
callback(rwc);
}
private static ContextCallback s_invokeAsyncCallback;
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
var context = _context;
if (context == null)
{
var callback = _callback;
_callback = null;
callback(completingTask);
}
else
{
_context = null;
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
using(context) ExecutionContext.Run(context, invokeAsyncCallback, this, true);
}
}
bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
}
[ComVisible(false)]
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
[ComVisible(false)]
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: BeginEndWriteAsync(buffer, offset, count);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndWrite();
private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndWrite())
{
// If the Stream does not override Begin/EndWrite, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer=buffer, Offset=offset, Count=count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default(VoidTaskResult);
});
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read([In, Out] byte[] buffer, int offset, int count);
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < 256);
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r==0)
return -1;
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
public static Stream Synchronized(Stream stream)
{
if (stream==null)
throw new ArgumentNullException(nameof(stream));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
// To avoid a race with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try {
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
catch (IOException ex) {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
if (callback != null) {
callback(asyncResult);
}
return asyncResult;
}
internal static int BlockingEndRead(IAsyncResult asyncResult)
{
Contract.Ensures(Contract.Result<int>() >= 0);
return SynchronousAsyncResult.EndRead(asyncResult);
}
internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try {
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
catch (IOException ex) {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
if (callback != null) {
callback(asyncResult);
}
return asyncResult;
}
internal static void BlockingEndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult.EndWrite(asyncResult);
}
[Serializable]
private sealed class NullStream : Stream
{
internal NullStream() {}
public override bool CanRead {
[Pure]
get { return true; }
}
public override bool CanWrite {
[Pure]
get { return true; }
}
public override bool CanSeek {
[Pure]
get { return true; }
}
public override long Length {
get { return 0; }
}
public override long Position {
get { return 0; }
set {}
}
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// After we validate arguments this is a nop.
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanRead) __Error.ReadNotSupported();
return BlockingBeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
return BlockingEndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanWrite) __Error.WriteNotSupported();
return BlockingBeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
BlockingEndWrite(asyncResult);
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
return 0;
}
[ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var nullReadTask = s_nullReadTask;
if (nullReadTask == null)
s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign race condition
return nullReadTask;
}
private static Task<int> s_nullReadTask;
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
internal sealed class SynchronousAsyncResult : IAsyncResult {
private readonly Object _stateObject;
private readonly bool _isWrite;
private ManualResetEvent _waitHandle;
private ExceptionDispatchInfo _exceptionInfo;
private bool _endXxxCalled;
private Int32 _bytesRead;
internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) {
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
//_isWrite = false;
}
internal SynchronousAsyncResult(Object asyncStateObject) {
_stateObject = asyncStateObject;
_isWrite = true;
}
internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) {
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
_isWrite = isWrite;
}
public bool IsCompleted {
// We never hand out objects of this type to the user before the synchronous IO completed:
get { return true; }
}
public WaitHandle AsyncWaitHandle {
get {
return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
}
}
public Object AsyncState {
get { return _stateObject; }
}
public bool CompletedSynchronously {
get { return true; }
}
internal void ThrowIfError() {
if (_exceptionInfo != null)
_exceptionInfo.Throw();
}
internal static Int32 EndRead(IAsyncResult asyncResult) {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndReadCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
return ar._bytesRead;
}
internal static void EndWrite(IAsyncResult asyncResult) {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || !ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndWriteCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
}
} // class SynchronousAsyncResult
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
[Serializable]
internal sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
Contract.EndContractBlock();
_stream = stream;
}
public override bool CanRead {
[Pure]
get { return _stream.CanRead; }
}
public override bool CanWrite {
[Pure]
get { return _stream.CanWrite; }
}
public override bool CanSeek {
[Pure]
get { return _stream.CanSeek; }
}
[ComVisible(false)]
public override bool CanTimeout {
[Pure]
get {
return _stream.CanTimeout;
}
}
public override long Length {
get {
lock(_stream) {
return _stream.Length;
}
}
}
public override long Position {
get {
lock(_stream) {
return _stream.Position;
}
}
set {
lock(_stream) {
_stream.Position = value;
}
}
}
[ComVisible(false)]
public override int ReadTimeout {
get {
return _stream.ReadTimeout;
}
set {
_stream.ReadTimeout = value;
}
}
[ComVisible(false)]
public override int WriteTimeout {
get {
return _stream.WriteTimeout;
}
set {
_stream.WriteTimeout = value;
}
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock(_stream) {
try {
_stream.Close();
}
finally {
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock(_stream) {
try {
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally {
base.Dispose(disposing);
}
}
}
public override void Flush()
{
lock(_stream)
_stream.Flush();
}
public override int Read([In, Out]byte[] bytes, int offset, int count)
{
lock(_stream)
return _stream.Read(bytes, offset, count);
}
public override int ReadByte()
{
lock(_stream)
return _stream.ReadByte();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
lock (_stream)
{
// If the Stream does have its own BeginRead implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginRead ?
_stream.BeginRead(buffer, offset, count, callback, state) :
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
lock(_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock(_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock(_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock(_stream)
_stream.Write(bytes, offset, count);
}
public override void WriteByte(byte b)
{
lock(_stream)
_stream.WriteByte(b);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
lock (_stream)
{
// If the Stream does have its own BeginWrite implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginWrite ?
_stream.BeginWrite(buffer, offset, count, callback, state) :
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
lock(_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// @Generated by gentest/gentest.rb from gentest/fixtures/YGAlignContentTest.html
using System;
using NUnit.Framework;
namespace Facebook.Yoga
{
[TestFixture]
public class YGAlignContentTest
{
[Test]
public void Test_align_content_flex_start()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Wrap = YogaWrap.Wrap;
root.Width = 130;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root_child2.Height = 10;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root_child3.Height = 10;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root_child4.Height = 10;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(130f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(10f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(10f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(20f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(130f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(80f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(30f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(80f, root_child2.LayoutX);
Assert.AreEqual(10f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
Assert.AreEqual(30f, root_child3.LayoutX);
Assert.AreEqual(10f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(80f, root_child4.LayoutX);
Assert.AreEqual(20f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_flex_start_without_height_on_children()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Wrap = YogaWrap.Wrap;
root.Width = 100;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root_child3.Height = 10;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(0f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(10f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(0f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(10f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(20f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(0f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(50f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(0f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(10f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(0f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(10f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(20f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(0f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_flex_start_with_flex()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Wrap = YogaWrap.Wrap;
root.Width = 100;
root.Height = 120;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 0.Percent();
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 1;
root_child1.FlexBasis = 0.Percent();
root_child1.Width = 50;
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.FlexGrow = 1;
root_child3.FlexShrink = 1;
root_child3.FlexBasis = 0.Percent();
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(120f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(40f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(40f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(40f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(80f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(0f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(80f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(40f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(120f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(0f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(120f, root.LayoutHeight);
Assert.AreEqual(50f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(40f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(40f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(40f, root_child1.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(80f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(0f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(80f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(40f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(120f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(0f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_flex_end()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.AlignContent = YogaAlign.FlexEnd;
root.Wrap = YogaWrap.Wrap;
root.Width = 100;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root_child2.Height = 10;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root_child3.Height = 10;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root_child4.Height = 10;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(10f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(20f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(30f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(40f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(50f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(10f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(20f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(30f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(40f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(0f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(0f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(0f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(0f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(0f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(0f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(0f, root_child0.LayoutHeight);
Assert.AreEqual(100f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
Assert.AreEqual(100f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(0f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(0f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(0f, root_child3.LayoutHeight);
Assert.AreEqual(100f, root_child4.LayoutX);
Assert.AreEqual(0f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(0f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_spacebetween()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.SpaceBetween;
root.Wrap = YogaWrap.Wrap;
root.Width = 130;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root_child2.Height = 10;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root_child3.Height = 10;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root_child4.Height = 10;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(130f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(45f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(45f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(90f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(130f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(80f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(30f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(80f, root_child2.LayoutX);
Assert.AreEqual(45f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
Assert.AreEqual(30f, root_child3.LayoutX);
Assert.AreEqual(45f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(80f, root_child4.LayoutX);
Assert.AreEqual(90f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_spacearound()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.SpaceAround;
root.Wrap = YogaWrap.Wrap;
root.Width = 140;
root.Height = 120;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root_child2.Height = 10;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root_child3.Height = 10;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root_child4.Height = 10;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(140f, root.LayoutWidth);
Assert.AreEqual(120f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(15f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(15f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(55f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(55f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(95f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(140f, root.LayoutWidth);
Assert.AreEqual(120f, root.LayoutHeight);
Assert.AreEqual(90f, root_child0.LayoutX);
Assert.AreEqual(15f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(40f, root_child1.LayoutX);
Assert.AreEqual(15f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(90f, root_child2.LayoutX);
Assert.AreEqual(55f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
Assert.AreEqual(40f, root_child3.LayoutX);
Assert.AreEqual(55f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(90f, root_child4.LayoutX);
Assert.AreEqual(95f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(50f, root_child1.LayoutHeight);
Assert.AreEqual(100f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(50f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(50f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(50f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_children()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.FlexGrow = 1;
root_child0_child0.FlexShrink = 1;
root_child0_child0.FlexBasis = 0.Percent();
root_child0.Insert(0, root_child0_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(50f, root_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(50f, root_child1.LayoutHeight);
Assert.AreEqual(100f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(50f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(50f, root_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(50f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(50f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_flex()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 1;
root_child1.FlexShrink = 1;
root_child1.FlexBasis = 0.Percent();
root_child1.Width = 50;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.FlexGrow = 1;
root_child3.FlexShrink = 1;
root_child3.FlexBasis = 0.Percent();
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(100f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(0f, root_child3.LayoutY);
Assert.AreEqual(0f, root_child3.LayoutWidth);
Assert.AreEqual(100f, root_child3.LayoutHeight);
Assert.AreEqual(100f, root_child4.LayoutX);
Assert.AreEqual(0f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(100f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(100f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(100f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(0f, root_child3.LayoutY);
Assert.AreEqual(0f, root_child3.LayoutWidth);
Assert.AreEqual(100f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(0f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(100f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_flex_no_shrink()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 1;
root_child1.FlexShrink = 1;
root_child1.FlexBasis = 0.Percent();
root_child1.Width = 50;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.FlexGrow = 1;
root_child3.FlexBasis = 0.Percent();
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(100f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(0f, root_child3.LayoutY);
Assert.AreEqual(0f, root_child3.LayoutWidth);
Assert.AreEqual(100f, root_child3.LayoutHeight);
Assert.AreEqual(100f, root_child4.LayoutX);
Assert.AreEqual(0f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(100f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(100f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(100f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(0f, root_child3.LayoutY);
Assert.AreEqual(0f, root_child3.LayoutWidth);
Assert.AreEqual(100f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(0f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(100f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_margin()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.MarginLeft = 10;
root_child1.MarginTop = 10;
root_child1.MarginRight = 10;
root_child1.MarginBottom = 10;
root_child1.Width = 50;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.MarginLeft = 10;
root_child3.MarginTop = 10;
root_child3.MarginRight = 10;
root_child3.MarginBottom = 10;
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(40f, root_child0.LayoutHeight);
Assert.AreEqual(60f, root_child1.LayoutX);
Assert.AreEqual(10f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(20f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(40f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(40f, root_child2.LayoutHeight);
Assert.AreEqual(60f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(20f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(80f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(20f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(40f, root_child0.LayoutHeight);
Assert.AreEqual(40f, root_child1.LayoutX);
Assert.AreEqual(10f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(20f, root_child1.LayoutHeight);
Assert.AreEqual(100f, root_child2.LayoutX);
Assert.AreEqual(40f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(40f, root_child2.LayoutHeight);
Assert.AreEqual(40f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(20f, root_child3.LayoutHeight);
Assert.AreEqual(100f, root_child4.LayoutX);
Assert.AreEqual(80f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(20f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_padding()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.PaddingLeft = 10;
root_child1.PaddingTop = 10;
root_child1.PaddingRight = 10;
root_child1.PaddingBottom = 10;
root_child1.Width = 50;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.PaddingLeft = 10;
root_child3.PaddingTop = 10;
root_child3.PaddingRight = 10;
root_child3.PaddingBottom = 10;
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(50f, root_child1.LayoutHeight);
Assert.AreEqual(100f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(50f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(50f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(50f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_single_row()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_fixed_height()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root_child1.Height = 60;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(80f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(60f, root_child1.LayoutHeight);
Assert.AreEqual(100f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(80f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(80f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(20f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(80f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(20f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(80f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(60f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(80f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(80f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(20f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(80f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(20f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_max_height()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root_child1.MaxHeight = 20;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(20f, root_child1.LayoutHeight);
Assert.AreEqual(100f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(50f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(20f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(50f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(50f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_row_with_min_height()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 150;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.Width = 50;
root_child1.MinHeight = 80;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Width = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Width = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(90f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(90f, root_child1.LayoutHeight);
Assert.AreEqual(100f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(90f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(90f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(90f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(150f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(100f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(90f, root_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(90f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(90f, root_child2.LayoutHeight);
Assert.AreEqual(100f, root_child3.LayoutX);
Assert.AreEqual(90f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(10f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(90f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(10f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_column()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.AlignContent = YogaAlign.Stretch;
root.Wrap = YogaWrap.Wrap;
root.Width = 100;
root.Height = 150;
YogaNode root_child0 = new YogaNode(config);
root_child0.Height = 50;
root.Insert(0, root_child0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.FlexGrow = 1;
root_child0_child0.FlexShrink = 1;
root_child0_child0.FlexBasis = 0.Percent();
root_child0.Insert(0, root_child0_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 1;
root_child1.FlexShrink = 1;
root_child1.FlexBasis = 0.Percent();
root_child1.Height = 50;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode(config);
root_child2.Height = 50;
root.Insert(2, root_child2);
YogaNode root_child3 = new YogaNode(config);
root_child3.Height = 50;
root.Insert(3, root_child3);
YogaNode root_child4 = new YogaNode(config);
root_child4.Height = 50;
root.Insert(4, root_child4);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(150f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(50f, root_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(50f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(50f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(0f, root_child3.LayoutX);
Assert.AreEqual(100f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(50f, root_child4.LayoutX);
Assert.AreEqual(0f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(150f, root.LayoutHeight);
Assert.AreEqual(50f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(50f, root_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0.LayoutHeight);
Assert.AreEqual(50f, root_child1.LayoutX);
Assert.AreEqual(50f, root_child1.LayoutY);
Assert.AreEqual(50f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(50f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(50f, root_child2.LayoutHeight);
Assert.AreEqual(50f, root_child3.LayoutX);
Assert.AreEqual(100f, root_child3.LayoutY);
Assert.AreEqual(50f, root_child3.LayoutWidth);
Assert.AreEqual(50f, root_child3.LayoutHeight);
Assert.AreEqual(0f, root_child4.LayoutX);
Assert.AreEqual(0f, root_child4.LayoutY);
Assert.AreEqual(50f, root_child4.LayoutWidth);
Assert.AreEqual(50f, root_child4.LayoutHeight);
}
[Test]
public void Test_align_content_stretch_is_not_overriding_align_items()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.AlignContent = YogaAlign.Stretch;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexDirection = YogaFlexDirection.Row;
root_child0.AlignContent = YogaAlign.Stretch;
root_child0.AlignItems = YogaAlign.Center;
root_child0.Width = 100;
root_child0.Height = 100;
root.Insert(0, root_child0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.AlignContent = YogaAlign.Stretch;
root_child0_child0.Width = 10;
root_child0_child0.Height = 10;
root_child0.Insert(0, root_child0_child0);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(45f, root_child0_child0.LayoutY);
Assert.AreEqual(10f, root_child0_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0_child0.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(90f, root_child0_child0.LayoutX);
Assert.AreEqual(45f, root_child0_child0.LayoutY);
Assert.AreEqual(10f, root_child0_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0_child0.LayoutHeight);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcav = Google.Cloud.AIPlatform.V1;
using sys = System;
namespace Google.Cloud.AIPlatform.V1
{
/// <summary>Resource name for the <c>AnnotationSpec</c> resource.</summary>
public sealed partial class AnnotationSpecName : gax::IResourceName, sys::IEquatable<AnnotationSpecName>
{
/// <summary>The possible contents of <see cref="AnnotationSpecName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </summary>
ProjectLocationDatasetAnnotationSpec = 1,
}
private static gax::PathTemplate s_projectLocationDatasetAnnotationSpec = new gax::PathTemplate("projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}");
/// <summary>Creates a <see cref="AnnotationSpecName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AnnotationSpecName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AnnotationSpecName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AnnotationSpecName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AnnotationSpecName"/> with the pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecId">The <c>AnnotationSpec</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AnnotationSpecName"/> constructed from the provided ids.</returns>
public static AnnotationSpecName FromProjectLocationDatasetAnnotationSpec(string projectId, string locationId, string datasetId, string annotationSpecId) =>
new AnnotationSpecName(ResourceNameType.ProjectLocationDatasetAnnotationSpec, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), annotationSpecId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecId, nameof(annotationSpecId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AnnotationSpecName"/> with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecId">The <c>AnnotationSpec</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AnnotationSpecName"/> with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string datasetId, string annotationSpecId) =>
FormatProjectLocationDatasetAnnotationSpec(projectId, locationId, datasetId, annotationSpecId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AnnotationSpecName"/> with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecId">The <c>AnnotationSpec</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AnnotationSpecName"/> with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </returns>
public static string FormatProjectLocationDatasetAnnotationSpec(string projectId, string locationId, string datasetId, string annotationSpecId) =>
s_projectLocationDatasetAnnotationSpec.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecId, nameof(annotationSpecId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AnnotationSpecName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="annotationSpecName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AnnotationSpecName"/> if successful.</returns>
public static AnnotationSpecName Parse(string annotationSpecName) => Parse(annotationSpecName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AnnotationSpecName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="annotationSpecName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AnnotationSpecName"/> if successful.</returns>
public static AnnotationSpecName Parse(string annotationSpecName, bool allowUnparsed) =>
TryParse(annotationSpecName, allowUnparsed, out AnnotationSpecName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AnnotationSpecName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="annotationSpecName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AnnotationSpecName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string annotationSpecName, out AnnotationSpecName result) =>
TryParse(annotationSpecName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AnnotationSpecName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="annotationSpecName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AnnotationSpecName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string annotationSpecName, bool allowUnparsed, out AnnotationSpecName result)
{
gax::GaxPreconditions.CheckNotNull(annotationSpecName, nameof(annotationSpecName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationDatasetAnnotationSpec.TryParseName(annotationSpecName, out resourceName))
{
result = FromProjectLocationDatasetAnnotationSpec(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(annotationSpecName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AnnotationSpecName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string annotationSpecId = null, string datasetId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AnnotationSpecId = annotationSpecId;
DatasetId = datasetId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AnnotationSpecName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecId">The <c>AnnotationSpec</c> ID. Must not be <c>null</c> or empty.</param>
public AnnotationSpecName(string projectId, string locationId, string datasetId, string annotationSpecId) : this(ResourceNameType.ProjectLocationDatasetAnnotationSpec, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), annotationSpecId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecId, nameof(annotationSpecId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AnnotationSpec</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string AnnotationSpecId { get; }
/// <summary>
/// The <c>Dataset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DatasetId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationDatasetAnnotationSpec: return s_projectLocationDatasetAnnotationSpec.Expand(ProjectId, LocationId, DatasetId, AnnotationSpecId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AnnotationSpecName);
/// <inheritdoc/>
public bool Equals(AnnotationSpecName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AnnotationSpecName a, AnnotationSpecName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AnnotationSpecName a, AnnotationSpecName b) => !(a == b);
}
public partial class AnnotationSpec
{
/// <summary>
/// <see cref="gcav::AnnotationSpecName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::AnnotationSpecName AnnotationSpecName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::AnnotationSpecName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
//uScript Generated Code - Build 1.0.3018
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[NodePath("Graphs")]
[System.Serializable]
[FriendlyName("Untitled", "")]
public class active_anim : uScriptLogic
{
#pragma warning disable 414
GameObject parentGameObject = null;
uScript_GUI thisScriptsOnGuiListener = null;
bool m_RegisteredForEvents = false;
//externally exposed events
//external parameters
//local nodes
[Multiline(3)]
public System.String Close = "";
System.Single local_11_System_Single = (float) 0;
System.Single local_12_System_Single = (float) 0;
System.Single local_15_System_Single = (float) 0;
System.Single local_17_System_Single = (float) 0;
[Multiline(3)]
public System.String Open = "";
//owner nodes
UnityEngine.GameObject owner_Connection_0 = null;
UnityEngine.GameObject owner_Connection_13 = null;
//logic nodes
//pointer to script instanced logic node
uScriptAct_GetAnimationState logic_uScriptAct_GetAnimationState_uScriptAct_GetAnimationState_1 = new uScriptAct_GetAnimationState( );
UnityEngine.GameObject logic_uScriptAct_GetAnimationState_target_1 = default(UnityEngine.GameObject);
System.String logic_uScriptAct_GetAnimationState_animationName_1 = "";
System.Single logic_uScriptAct_GetAnimationState_weight_1;
System.Single logic_uScriptAct_GetAnimationState_normalizedPosition_1;
System.Single logic_uScriptAct_GetAnimationState_animLength_1;
System.Single logic_uScriptAct_GetAnimationState_speed_1;
System.Int32 logic_uScriptAct_GetAnimationState_layer_1;
UnityEngine.WrapMode logic_uScriptAct_GetAnimationState_wrapMode_1;
bool logic_uScriptAct_GetAnimationState_Out_1 = true;
//pointer to script instanced logic node
uScriptAct_PlayAnimation logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_2 = new uScriptAct_PlayAnimation( );
UnityEngine.GameObject[] logic_uScriptAct_PlayAnimation_Target_2 = new UnityEngine.GameObject[] {};
System.String logic_uScriptAct_PlayAnimation_Animation_2 = "";
System.Single logic_uScriptAct_PlayAnimation_SpeedFactor_2 = (float) 1;
UnityEngine.WrapMode logic_uScriptAct_PlayAnimation_AnimWrapMode_2 = UnityEngine.WrapMode.Default;
System.Boolean logic_uScriptAct_PlayAnimation_StopOtherAnimations_2 = (bool) true;
bool logic_uScriptAct_PlayAnimation_Out_2 = true;
//pointer to script instanced logic node
uScriptAct_Passthrough logic_uScriptAct_Passthrough_uScriptAct_Passthrough_3 = new uScriptAct_Passthrough( );
bool logic_uScriptAct_Passthrough_Out_3 = true;
//pointer to script instanced logic node
uScriptAct_SetAnimationPosition logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_4 = new uScriptAct_SetAnimationPosition( );
UnityEngine.GameObject logic_uScriptAct_SetAnimationPosition_target_4 = default(UnityEngine.GameObject);
System.String logic_uScriptAct_SetAnimationPosition_animationName_4 = "";
System.Single logic_uScriptAct_SetAnimationPosition_normalizedPosition_4 = (float) 0;
//pointer to script instanced logic node
uScriptAct_Passthrough logic_uScriptAct_Passthrough_uScriptAct_Passthrough_5 = new uScriptAct_Passthrough( );
bool logic_uScriptAct_Passthrough_Out_5 = true;
//pointer to script instanced logic node
uScriptAct_SetAnimationPosition logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_6 = new uScriptAct_SetAnimationPosition( );
UnityEngine.GameObject logic_uScriptAct_SetAnimationPosition_target_6 = default(UnityEngine.GameObject);
System.String logic_uScriptAct_SetAnimationPosition_animationName_6 = "";
System.Single logic_uScriptAct_SetAnimationPosition_normalizedPosition_6 = (float) 0;
//pointer to script instanced logic node
uScriptCon_CompareFloat logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_7 = new uScriptCon_CompareFloat( );
System.Single logic_uScriptCon_CompareFloat_A_7 = (float) 0;
System.Single logic_uScriptCon_CompareFloat_B_7 = (float) 1;
bool logic_uScriptCon_CompareFloat_GreaterThan_7 = true;
bool logic_uScriptCon_CompareFloat_GreaterThanOrEqualTo_7 = true;
bool logic_uScriptCon_CompareFloat_EqualTo_7 = true;
bool logic_uScriptCon_CompareFloat_NotEqualTo_7 = true;
bool logic_uScriptCon_CompareFloat_LessThanOrEqualTo_7 = true;
bool logic_uScriptCon_CompareFloat_LessThan_7 = true;
//pointer to script instanced logic node
uScriptAct_GetAnimationState logic_uScriptAct_GetAnimationState_uScriptAct_GetAnimationState_8 = new uScriptAct_GetAnimationState( );
UnityEngine.GameObject logic_uScriptAct_GetAnimationState_target_8 = default(UnityEngine.GameObject);
System.String logic_uScriptAct_GetAnimationState_animationName_8 = "";
System.Single logic_uScriptAct_GetAnimationState_weight_8;
System.Single logic_uScriptAct_GetAnimationState_normalizedPosition_8;
System.Single logic_uScriptAct_GetAnimationState_animLength_8;
System.Single logic_uScriptAct_GetAnimationState_speed_8;
System.Int32 logic_uScriptAct_GetAnimationState_layer_8;
UnityEngine.WrapMode logic_uScriptAct_GetAnimationState_wrapMode_8;
bool logic_uScriptAct_GetAnimationState_Out_8 = true;
//pointer to script instanced logic node
uScriptCon_CompareFloat logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_9 = new uScriptCon_CompareFloat( );
System.Single logic_uScriptCon_CompareFloat_A_9 = (float) 0;
System.Single logic_uScriptCon_CompareFloat_B_9 = (float) 1;
bool logic_uScriptCon_CompareFloat_GreaterThan_9 = true;
bool logic_uScriptCon_CompareFloat_GreaterThanOrEqualTo_9 = true;
bool logic_uScriptCon_CompareFloat_EqualTo_9 = true;
bool logic_uScriptCon_CompareFloat_NotEqualTo_9 = true;
bool logic_uScriptCon_CompareFloat_LessThanOrEqualTo_9 = true;
bool logic_uScriptCon_CompareFloat_LessThan_9 = true;
//pointer to script instanced logic node
uScriptAct_PlayAnimation logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_10 = new uScriptAct_PlayAnimation( );
UnityEngine.GameObject[] logic_uScriptAct_PlayAnimation_Target_10 = new UnityEngine.GameObject[] {};
System.String logic_uScriptAct_PlayAnimation_Animation_10 = "";
System.Single logic_uScriptAct_PlayAnimation_SpeedFactor_10 = (float) 1;
UnityEngine.WrapMode logic_uScriptAct_PlayAnimation_AnimWrapMode_10 = UnityEngine.WrapMode.Default;
System.Boolean logic_uScriptAct_PlayAnimation_StopOtherAnimations_10 = (bool) true;
bool logic_uScriptAct_PlayAnimation_Out_10 = true;
//pointer to script instanced logic node
uScriptAct_SubtractFloat logic_uScriptAct_SubtractFloat_uScriptAct_SubtractFloat_14 = new uScriptAct_SubtractFloat( );
System.Single logic_uScriptAct_SubtractFloat_A_14 = (float) 1;
System.Single logic_uScriptAct_SubtractFloat_B_14 = (float) 0;
System.Single logic_uScriptAct_SubtractFloat_FloatResult_14;
System.Int32 logic_uScriptAct_SubtractFloat_IntResult_14;
bool logic_uScriptAct_SubtractFloat_Out_14 = true;
//pointer to script instanced logic node
uScriptAct_SubtractFloat logic_uScriptAct_SubtractFloat_uScriptAct_SubtractFloat_16 = new uScriptAct_SubtractFloat( );
System.Single logic_uScriptAct_SubtractFloat_A_16 = (float) 1;
System.Single logic_uScriptAct_SubtractFloat_B_16 = (float) 0;
System.Single logic_uScriptAct_SubtractFloat_FloatResult_16;
System.Int32 logic_uScriptAct_SubtractFloat_IntResult_16;
bool logic_uScriptAct_SubtractFloat_Out_16 = true;
//event nodes
UnityEngine.GameObject event_UnityEngine_GameObject_GameObject_54 = default(UnityEngine.GameObject);
//property nodes
//method nodes
#pragma warning restore 414
//functions to refresh properties from entities
void SyncUnityHooks( )
{
SyncEventListeners( );
if ( null == owner_Connection_0 || false == m_RegisteredForEvents )
{
owner_Connection_0 = parentGameObject;
if ( null != owner_Connection_0 )
{
{
uScript_Trigger component = owner_Connection_0.GetComponent<uScript_Trigger>();
if ( null == component )
{
component = owner_Connection_0.AddComponent<uScript_Trigger>();
}
if ( null != component )
{
component.OnEnterTrigger += Instance_OnEnterTrigger_54;
component.OnExitTrigger += Instance_OnExitTrigger_54;
component.WhileInsideTrigger += Instance_WhileInsideTrigger_54;
}
}
}
}
if ( null == owner_Connection_13 || false == m_RegisteredForEvents )
{
owner_Connection_13 = parentGameObject;
}
}
void RegisterForUnityHooks( )
{
SyncEventListeners( );
//reset event listeners if needed
//this isn't a variable node so it should only be called once per enabling of the script
//if it's called twice there would be a double event registration (which is an error)
if ( false == m_RegisteredForEvents )
{
if ( null != owner_Connection_0 )
{
{
uScript_Trigger component = owner_Connection_0.GetComponent<uScript_Trigger>();
if ( null == component )
{
component = owner_Connection_0.AddComponent<uScript_Trigger>();
}
if ( null != component )
{
component.OnEnterTrigger += Instance_OnEnterTrigger_54;
component.OnExitTrigger += Instance_OnExitTrigger_54;
component.WhileInsideTrigger += Instance_WhileInsideTrigger_54;
}
}
}
}
}
void SyncEventListeners( )
{
}
void UnregisterEventListeners( )
{
if ( null != owner_Connection_0 )
{
{
uScript_Trigger component = owner_Connection_0.GetComponent<uScript_Trigger>();
if ( null != component )
{
component.OnEnterTrigger -= Instance_OnEnterTrigger_54;
component.OnExitTrigger -= Instance_OnExitTrigger_54;
component.WhileInsideTrigger -= Instance_WhileInsideTrigger_54;
}
}
}
}
public override void SetParent(GameObject g)
{
parentGameObject = g;
logic_uScriptAct_GetAnimationState_uScriptAct_GetAnimationState_1.SetParent(g);
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_2.SetParent(g);
logic_uScriptAct_Passthrough_uScriptAct_Passthrough_3.SetParent(g);
logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_4.SetParent(g);
logic_uScriptAct_Passthrough_uScriptAct_Passthrough_5.SetParent(g);
logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_6.SetParent(g);
logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_7.SetParent(g);
logic_uScriptAct_GetAnimationState_uScriptAct_GetAnimationState_8.SetParent(g);
logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_9.SetParent(g);
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_10.SetParent(g);
logic_uScriptAct_SubtractFloat_uScriptAct_SubtractFloat_14.SetParent(g);
logic_uScriptAct_SubtractFloat_uScriptAct_SubtractFloat_16.SetParent(g);
owner_Connection_0 = parentGameObject;
owner_Connection_13 = parentGameObject;
}
public void Awake()
{
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_2.Finished += uScriptAct_PlayAnimation_Finished_2;
logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_4.Out += uScriptAct_SetAnimationPosition_Out_4;
logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_6.Out += uScriptAct_SetAnimationPosition_Out_6;
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_10.Finished += uScriptAct_PlayAnimation_Finished_10;
}
public void Start()
{
SyncUnityHooks( );
m_RegisteredForEvents = true;
}
public void OnEnable()
{
RegisterForUnityHooks( );
m_RegisteredForEvents = true;
}
public void OnDisable()
{
UnregisterEventListeners( );
m_RegisteredForEvents = false;
}
public void Update()
{
//other scripts might have added GameObjects with event scripts
//so we need to verify all our event listeners are registered
SyncEventListeners( );
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_2.Update( );
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_10.Update( );
}
public void OnDestroy()
{
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_2.Finished -= uScriptAct_PlayAnimation_Finished_2;
logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_4.Out -= uScriptAct_SetAnimationPosition_Out_4;
logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_6.Out -= uScriptAct_SetAnimationPosition_Out_6;
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_10.Finished -= uScriptAct_PlayAnimation_Finished_10;
}
void Instance_OnEnterTrigger_54(object o, uScript_Trigger.TriggerEventArgs e)
{
//fill globals
event_UnityEngine_GameObject_GameObject_54 = e.GameObject;
//relay event to nodes
Relay_OnEnterTrigger_54( );
}
void Instance_OnExitTrigger_54(object o, uScript_Trigger.TriggerEventArgs e)
{
//fill globals
event_UnityEngine_GameObject_GameObject_54 = e.GameObject;
//relay event to nodes
Relay_OnExitTrigger_54( );
}
void Instance_WhileInsideTrigger_54(object o, uScript_Trigger.TriggerEventArgs e)
{
//fill globals
event_UnityEngine_GameObject_GameObject_54 = e.GameObject;
//relay event to nodes
Relay_WhileInsideTrigger_54( );
}
void uScriptAct_PlayAnimation_Finished_2(object o, System.EventArgs e)
{
//fill globals
//relay event to nodes
Relay_Finished_2( );
}
void uScriptAct_SetAnimationPosition_Out_4(object o, System.EventArgs e)
{
//fill globals
//relay event to nodes
Relay_Out_4( );
}
void uScriptAct_SetAnimationPosition_Out_6(object o, System.EventArgs e)
{
//fill globals
//relay event to nodes
Relay_Out_6( );
}
void uScriptAct_PlayAnimation_Finished_10(object o, System.EventArgs e)
{
//fill globals
//relay event to nodes
Relay_Finished_10( );
}
void Relay_In_1()
{
{
{
logic_uScriptAct_GetAnimationState_target_1 = owner_Connection_13;
}
{
logic_uScriptAct_GetAnimationState_animationName_1 = Close;
}
{
}
{
}
{
}
{
}
{
}
{
}
}
logic_uScriptAct_GetAnimationState_uScriptAct_GetAnimationState_1.In(logic_uScriptAct_GetAnimationState_target_1, logic_uScriptAct_GetAnimationState_animationName_1, out logic_uScriptAct_GetAnimationState_weight_1, out logic_uScriptAct_GetAnimationState_normalizedPosition_1, out logic_uScriptAct_GetAnimationState_animLength_1, out logic_uScriptAct_GetAnimationState_speed_1, out logic_uScriptAct_GetAnimationState_layer_1, out logic_uScriptAct_GetAnimationState_wrapMode_1);
local_15_System_Single = logic_uScriptAct_GetAnimationState_normalizedPosition_1;
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
bool test_0 = logic_uScriptAct_GetAnimationState_uScriptAct_GetAnimationState_1.Out;
if ( test_0 == true )
{
Relay_In_14();
}
}
void Relay_Finished_2()
{
}
void Relay_In_2()
{
{
{
int index = 0;
if ( logic_uScriptAct_PlayAnimation_Target_2.Length <= index)
{
System.Array.Resize(ref logic_uScriptAct_PlayAnimation_Target_2, index + 1);
}
logic_uScriptAct_PlayAnimation_Target_2[ index++ ] = owner_Connection_13;
}
{
logic_uScriptAct_PlayAnimation_Animation_2 = Open;
}
{
}
{
}
{
}
}
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_2.In(logic_uScriptAct_PlayAnimation_Target_2, logic_uScriptAct_PlayAnimation_Animation_2, logic_uScriptAct_PlayAnimation_SpeedFactor_2, logic_uScriptAct_PlayAnimation_AnimWrapMode_2, logic_uScriptAct_PlayAnimation_StopOtherAnimations_2);
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
}
void Relay_In_3()
{
{
}
logic_uScriptAct_Passthrough_uScriptAct_Passthrough_3.In();
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
bool test_0 = logic_uScriptAct_Passthrough_uScriptAct_Passthrough_3.Out;
if ( test_0 == true )
{
Relay_In_1();
}
}
void Relay_Out_4()
{
Relay_In_2();
}
void Relay_In_4()
{
{
{
logic_uScriptAct_SetAnimationPosition_target_4 = owner_Connection_13;
}
{
logic_uScriptAct_SetAnimationPosition_animationName_4 = Open;
}
{
logic_uScriptAct_SetAnimationPosition_normalizedPosition_4 = local_12_System_Single;
}
}
logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_4.In(logic_uScriptAct_SetAnimationPosition_target_4, logic_uScriptAct_SetAnimationPosition_animationName_4, logic_uScriptAct_SetAnimationPosition_normalizedPosition_4);
}
void Relay_In_5()
{
{
}
logic_uScriptAct_Passthrough_uScriptAct_Passthrough_5.In();
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
bool test_0 = logic_uScriptAct_Passthrough_uScriptAct_Passthrough_5.Out;
if ( test_0 == true )
{
Relay_In_8();
}
}
void Relay_Out_6()
{
Relay_In_10();
}
void Relay_In_6()
{
{
{
logic_uScriptAct_SetAnimationPosition_target_6 = owner_Connection_13;
}
{
logic_uScriptAct_SetAnimationPosition_animationName_6 = Close;
}
{
logic_uScriptAct_SetAnimationPosition_normalizedPosition_6 = local_11_System_Single;
}
}
logic_uScriptAct_SetAnimationPosition_uScriptAct_SetAnimationPosition_6.In(logic_uScriptAct_SetAnimationPosition_target_6, logic_uScriptAct_SetAnimationPosition_animationName_6, logic_uScriptAct_SetAnimationPosition_normalizedPosition_6);
}
void Relay_In_7()
{
{
{
logic_uScriptCon_CompareFloat_A_7 = local_12_System_Single;
}
{
}
}
logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_7.In(logic_uScriptCon_CompareFloat_A_7, logic_uScriptCon_CompareFloat_B_7);
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
bool test_0 = logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_7.EqualTo;
bool test_1 = logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_7.NotEqualTo;
if ( test_0 == true )
{
Relay_In_2();
}
if ( test_1 == true )
{
Relay_In_4();
}
}
void Relay_In_8()
{
{
{
logic_uScriptAct_GetAnimationState_target_8 = owner_Connection_13;
}
{
logic_uScriptAct_GetAnimationState_animationName_8 = Open;
}
{
}
{
}
{
}
{
}
{
}
{
}
}
logic_uScriptAct_GetAnimationState_uScriptAct_GetAnimationState_8.In(logic_uScriptAct_GetAnimationState_target_8, logic_uScriptAct_GetAnimationState_animationName_8, out logic_uScriptAct_GetAnimationState_weight_8, out logic_uScriptAct_GetAnimationState_normalizedPosition_8, out logic_uScriptAct_GetAnimationState_animLength_8, out logic_uScriptAct_GetAnimationState_speed_8, out logic_uScriptAct_GetAnimationState_layer_8, out logic_uScriptAct_GetAnimationState_wrapMode_8);
local_17_System_Single = logic_uScriptAct_GetAnimationState_normalizedPosition_8;
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
bool test_0 = logic_uScriptAct_GetAnimationState_uScriptAct_GetAnimationState_8.Out;
if ( test_0 == true )
{
Relay_In_16();
}
}
void Relay_In_9()
{
{
{
logic_uScriptCon_CompareFloat_A_9 = local_11_System_Single;
}
{
}
}
logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_9.In(logic_uScriptCon_CompareFloat_A_9, logic_uScriptCon_CompareFloat_B_9);
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
bool test_0 = logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_9.EqualTo;
bool test_1 = logic_uScriptCon_CompareFloat_uScriptCon_CompareFloat_9.NotEqualTo;
if ( test_0 == true )
{
Relay_In_10();
}
if ( test_1 == true )
{
Relay_In_6();
}
}
void Relay_Finished_10()
{
}
void Relay_In_10()
{
{
{
int index = 0;
if ( logic_uScriptAct_PlayAnimation_Target_10.Length <= index)
{
System.Array.Resize(ref logic_uScriptAct_PlayAnimation_Target_10, index + 1);
}
logic_uScriptAct_PlayAnimation_Target_10[ index++ ] = owner_Connection_13;
}
{
logic_uScriptAct_PlayAnimation_Animation_10 = Close;
}
{
}
{
}
{
}
}
logic_uScriptAct_PlayAnimation_uScriptAct_PlayAnimation_10.In(logic_uScriptAct_PlayAnimation_Target_10, logic_uScriptAct_PlayAnimation_Animation_10, logic_uScriptAct_PlayAnimation_SpeedFactor_10, logic_uScriptAct_PlayAnimation_AnimWrapMode_10, logic_uScriptAct_PlayAnimation_StopOtherAnimations_10);
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
}
void Relay_In_14()
{
{
{
}
{
logic_uScriptAct_SubtractFloat_B_14 = local_15_System_Single;
}
{
}
{
}
}
logic_uScriptAct_SubtractFloat_uScriptAct_SubtractFloat_14.In(logic_uScriptAct_SubtractFloat_A_14, logic_uScriptAct_SubtractFloat_B_14, out logic_uScriptAct_SubtractFloat_FloatResult_14, out logic_uScriptAct_SubtractFloat_IntResult_14);
local_12_System_Single = logic_uScriptAct_SubtractFloat_FloatResult_14;
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
bool test_0 = logic_uScriptAct_SubtractFloat_uScriptAct_SubtractFloat_14.Out;
if ( test_0 == true )
{
Relay_In_7();
}
}
void Relay_In_16()
{
{
{
}
{
logic_uScriptAct_SubtractFloat_B_16 = local_17_System_Single;
}
{
}
{
}
}
logic_uScriptAct_SubtractFloat_uScriptAct_SubtractFloat_16.In(logic_uScriptAct_SubtractFloat_A_16, logic_uScriptAct_SubtractFloat_B_16, out logic_uScriptAct_SubtractFloat_FloatResult_16, out logic_uScriptAct_SubtractFloat_IntResult_16);
local_11_System_Single = logic_uScriptAct_SubtractFloat_FloatResult_16;
//save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested
bool test_0 = logic_uScriptAct_SubtractFloat_uScriptAct_SubtractFloat_16.Out;
if ( test_0 == true )
{
Relay_In_9();
}
}
void Relay_OnEnterTrigger_54()
{
Relay_In_3();
}
void Relay_OnExitTrigger_54()
{
Relay_In_5();
}
void Relay_WhileInsideTrigger_54()
{
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sce.Atf;
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Sled.Lua.Dom;
using Sce.Sled.Shared.Controls;
using Sce.Sled.Shared.Services;
namespace Sce.Sled.Lua
{
[Export(typeof(IInitializable))]
[Export(typeof(IContextMenuCommandProvider))]
[Export(typeof(SledCommandPluginVariableLists))]
[PartCreationPolicy(CreationPolicy.Shared)]
class SledCommandPluginVariableLists : IInitializable, ICommandClient, IContextMenuCommandProvider
{
[ImportingConstructor]
public SledCommandPluginVariableLists(ICommandService commandService)
{
ICommandService commandService1 = commandService;
var menu =
commandService1.RegisterMenu(
Menu.VarList,
"Lua Variable List",
"Lua Variable List");
commandService1.RegisterCommand(
Command.Goto,
Menu.VarList,
Group.NavigateCommands,
"Goto",
"Goto variable",
Keys.None,
Atf.Resources.ZoomInImage,
CommandVisibility.ContextMenu,
this);
commandService1.RegisterCommand(
Command.AddWatch,
Menu.VarList,
Group.WatchCommands,
"Add Watch",
"Add varible to watch list",
Keys.None,
null,
CommandVisibility.ContextMenu,
this);
commandService1.RegisterCommand(
Command.RemoveWatch,
Menu.VarList,
Group.WatchCommands,
"Remove Watch",
"Remove variable from watch list",
Keys.None,
null,
CommandVisibility.ContextMenu,
this);
commandService1.RegisterCommand(
Command.CopyName,
Menu.VarList,
Group.CopyCommands,
"Copy Name",
"Copy the variable's name to the clipboard",
Atf.Input.Keys.None,
null,
CommandVisibility.ContextMenu,
this);
commandService1.RegisterCommand(
Command.CopyValue,
Menu.VarList,
Group.CopyCommands,
"Copy Value",
"Copy the variable's value to the clipboard",
Atf.Input.Keys.None,
null,
CommandVisibility.ContextMenu,
this);
// Don't show the menu
menu.GetMenuItem().Visible = false;
}
#region IInitializable Interface
void IInitializable.Initialize()
{
}
#endregion
#region ICommandClient Interface
public bool CanDoCommand(object commandTag)
{
return
(commandTag is Command) &&
(m_selection.Count > 0);
}
public void DoCommand(object commandTag)
{
if (!(commandTag is Command))
return;
if (m_selection.Count <= 0)
return;
try
{
var cmd = (Command)commandTag;
switch (cmd)
{
case Command.Goto:
m_gotoService.GotoVariable(m_selection[0]);
break;
case Command.AddWatch:
HandleAddWatch(m_selection);
break;
case Command.RemoveWatch:
HandleRemoveWatch(m_selection);
break;
case Command.CopyName:
case Command.CopyValue:
HandleCopyCommands(cmd, m_selection);
break;
}
}
finally
{
m_selection.Clear();
}
}
public void UpdateCommand(object commandTag, CommandState state)
{
}
#endregion
#region IContextMenuCommandProvider Overrides
public IEnumerable<object> GetCommands(object context, object target)
{
m_selection.Clear();
var clicked = target.As<ISledLuaVarBaseType>();
if (clicked == null)
return s_emptyCommands;
{
var registry = SledServiceInstance.TryGet<IContextRegistry>();
if (registry != null)
{
// Check if a GUI editor is the active context
var editor = registry.ActiveContext.As<SledTreeListViewEditor>();
if (editor != null)
{
// Add selection from editor to saved selection
foreach (var item in editor.Selection)
{
if (item.Is<ISledLuaVarBaseType>())
m_selection.Add(item.As<ISledLuaVarBaseType>());
}
}
}
}
// Add clicked item to selection
if (!m_selection.Contains(clicked))
m_selection.Add(clicked);
//
// Check what commands can be issued
//
var lstCommands = new List<object>();
// If only one item we can jump to it
if (m_selection.Count == 1)
lstCommands.Add(Command.Goto);
var bWatchGui =
clicked.DomNode.GetRoot().Type ==
SledLuaSchema.SledLuaVarWatchListType.Type;
if (bWatchGui)
lstCommands.Add(Command.RemoveWatch);
else
{
// Check if there are any items in the
// selection that aren't being watched
var bAnyItemsNotWatched =
m_selection.Any(
luaVar => !m_luaWatchedVariableService.IsLuaVarWatched(luaVar));
if (bAnyItemsNotWatched)
lstCommands.Add(Command.AddWatch);
}
lstCommands.Add(StandardCommand.EditCopy);
lstCommands.Add(Command.CopyName);
lstCommands.Add(Command.CopyValue);
return lstCommands;
}
#endregion
#region Commands
enum Command
{
Goto,
AddWatch,
RemoveWatch,
CopyName,
CopyValue,
}
enum Menu
{
VarList,
}
enum Group
{
NavigateCommands,
WatchCommands,
CopyCommands,
}
#endregion
private void HandleAddWatch(IEnumerable<ISledLuaVarBaseType> selection)
{
foreach (var luaVar in selection)
{
if (m_luaWatchedVariableService.IsLuaVarWatched(luaVar))
continue;
m_luaWatchedVariableService.AddWatchedLuaVar(luaVar);
}
}
private void HandleRemoveWatch(IEnumerable<ISledLuaVarBaseType> selection)
{
foreach (var luaVar in selection)
{
var rootLevelLuaVar = SledLuaUtil.GetRootLevelVar(luaVar);
if (!m_luaWatchedVariableService.IsLuaVarWatched(rootLevelLuaVar))
continue;
m_luaWatchedVariableService.RemoveWatchedLuaVar(rootLevelLuaVar);
}
}
private void HandleCopyCommands(Command cmd, IEnumerable<ISledLuaVarBaseType> selection)
{
var sb = new StringBuilder();
foreach (var luaVar in selection)
{
switch (cmd)
{
case Command.CopyName: sb.Append(luaVar.Name); break;
case Command.CopyValue: sb.Append(luaVar.Value); break;
}
sb.Append(Environment.NewLine);
}
try
{
StandardEditCommands.UseSystemClipboard = true;
var dataObject = new DataObject(DataFormats.Text, sb.ToString());
m_standardEditCommands.Clipboard = dataObject;
}
finally
{
StandardEditCommands.UseSystemClipboard = false;
}
}
#pragma warning disable 649 // Field is never assigned
[Import]
private StandardEditCommands m_standardEditCommands;
[Import]
private ISledGotoService m_gotoService;
[Import]
private ISledLuaWatchedVariableService m_luaWatchedVariableService;
#pragma warning restore 649
private readonly List<ISledLuaVarBaseType> m_selection =
new List<ISledLuaVarBaseType>();
private static readonly IEnumerable<object> s_emptyCommands =
EmptyEnumerable<object>.Instance;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
internal static class ExpressionHelper
{
public static string GetUncachedExpressionText(LambdaExpression expression)
=> GetExpressionText(expression, expressionTextCache: null);
public static string GetExpressionText(LambdaExpression expression, ConcurrentDictionary<LambdaExpression, string> expressionTextCache)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
if (expressionTextCache != null &&
expressionTextCache.TryGetValue(expression, out var expressionText))
{
return expressionText;
}
// Determine size of string needed (length) and number of segments it contains (segmentCount). Put another
// way, segmentCount tracks the number of times the loop below should iterate. This avoids adding ".model"
// and / or an extra leading "." and then removing them after the loop. Other information collected in this
// first loop helps with length and segmentCount adjustments. doNotCache is somewhat separate: If
// true, expression strings are not cached for the expression.
//
// After the corrections below the first loop, length is usually exactly the size of the returned string.
// However when containsIndexers is true, the calculation is approximate because either evaluating indexer
// expressions multiple times or saving indexer strings can get expensive. Optimizing for the common case
// of a collection (not a dictionary) with less than 100 elements. If that assumption proves to be
// incorrect, the StringBuilder will be enlarged but hopefully just once.
var doNotCache = false;
var lastIsModel = false;
var length = 0;
var segmentCount = 0;
var trailingMemberExpressions = 0;
var part = expression.Body;
while (part != null)
{
switch (part.NodeType)
{
case ExpressionType.Call:
// Will exit loop if at Method().Property or [i,j].Property. In that case (like [i].Property),
// don't cache and don't remove ".Model" (if that's .Property).
doNotCache = true;
lastIsModel = false;
var methodExpression = (MethodCallExpression)part;
if (IsSingleArgumentIndexer(methodExpression))
{
length += "[99]".Length;
part = methodExpression.Object;
segmentCount++;
trailingMemberExpressions = 0;
}
else
{
// Unsupported.
part = null;
}
break;
case ExpressionType.ArrayIndex:
var binaryExpression = (BinaryExpression)part;
doNotCache = true;
lastIsModel = false;
length += "[99]".Length;
part = binaryExpression.Left;
segmentCount++;
trailingMemberExpressions = 0;
break;
case ExpressionType.MemberAccess:
var memberExpressionPart = (MemberExpression)part;
var name = memberExpressionPart.Member.Name;
// If identifier contains "__", it is "reserved for use by the implementation" and likely
// compiler- or Razor-generated e.g. the name of a field in a delegate's generated class.
if (name.Contains("__"))
{
// Exit loop.
part = null;
}
else
{
lastIsModel = string.Equals("model", name, StringComparison.OrdinalIgnoreCase);
length += name.Length + 1;
part = memberExpressionPart.Expression;
segmentCount++;
trailingMemberExpressions++;
}
break;
case ExpressionType.Parameter:
// Unsupported but indicates previous member access was not the view's Model.
lastIsModel = false;
part = null;
break;
default:
// Unsupported.
part = null;
break;
}
}
// If name would start with ".model", then strip that part away.
if (lastIsModel)
{
length -= ".model".Length;
segmentCount--;
trailingMemberExpressions--;
}
// Trim the leading "." if present. The loop below special-cases the last property to avoid this addition.
if (trailingMemberExpressions > 0)
{
length--;
}
Debug.Assert(segmentCount >= 0);
if (segmentCount == 0)
{
Debug.Assert(!doNotCache);
if (expressionTextCache != null)
{
expressionTextCache.TryAdd(expression, string.Empty);
}
return string.Empty;
}
var builder = new StringBuilder(length);
part = expression.Body;
while (part != null && segmentCount > 0)
{
segmentCount--;
switch (part.NodeType)
{
case ExpressionType.Call:
Debug.Assert(doNotCache);
var methodExpression = (MethodCallExpression)part;
InsertIndexerInvocationText(builder, methodExpression.Arguments.Single(), expression);
part = methodExpression.Object;
break;
case ExpressionType.ArrayIndex:
Debug.Assert(doNotCache);
var binaryExpression = (BinaryExpression)part;
InsertIndexerInvocationText(builder, binaryExpression.Right, expression);
part = binaryExpression.Left;
break;
case ExpressionType.MemberAccess:
var memberExpression = (MemberExpression)part;
var name = memberExpression.Member.Name;
Debug.Assert(!name.Contains("__"));
builder.Insert(0, name);
if (segmentCount > 0)
{
// One or more parts to the left of this part are coming.
builder.Insert(0, '.');
}
part = memberExpression.Expression;
break;
default:
// Should be unreachable due to handling in above loop.
Debug.Assert(false);
break;
}
}
Debug.Assert(segmentCount == 0);
expressionText = builder.ToString();
if (expressionTextCache != null && !doNotCache)
{
expressionTextCache.TryAdd(expression, expressionText);
}
return expressionText;
}
private static void InsertIndexerInvocationText(
StringBuilder builder,
Expression indexExpression,
LambdaExpression parentExpression)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (indexExpression == null)
{
throw new ArgumentNullException(nameof(indexExpression));
}
if (parentExpression == null)
{
throw new ArgumentNullException(nameof(parentExpression));
}
if (parentExpression.Parameters == null)
{
throw new ArgumentException(Resources.FormatPropertyOfTypeCannotBeNull(
nameof(parentExpression.Parameters),
nameof(parentExpression)));
}
var converted = Expression.Convert(indexExpression, typeof(object));
var fakeParameter = Expression.Parameter(typeof(object), null);
var lambda = Expression.Lambda<Func<object, object>>(converted, fakeParameter);
Func<object, object> func;
try
{
func = CachedExpressionCompiler.Process(lambda) ?? lambda.Compile();
}
catch (InvalidOperationException ex)
{
var parameters = parentExpression.Parameters.ToArray();
throw new InvalidOperationException(
Resources.FormatExpressionHelper_InvalidIndexerExpression(indexExpression, parameters[0].Name),
ex);
}
builder.Insert(0, ']');
builder.Insert(0, Convert.ToString(func(null), CultureInfo.InvariantCulture));
builder.Insert(0, '[');
}
public static bool IsSingleArgumentIndexer(Expression expression)
{
if (!(expression is MethodCallExpression methodExpression) || methodExpression.Arguments.Count != 1)
{
return false;
}
// Check whether GetDefaultMembers() (if present in CoreCLR) would return a member of this type. Compiler
// names the indexer property, if any, in a generated [DefaultMember] attribute for the containing type.
var declaringType = methodExpression.Method.DeclaringType;
var defaultMember = declaringType.GetCustomAttribute<DefaultMemberAttribute>(inherit: true);
if (defaultMember == null)
{
return false;
}
// Find default property (the indexer) and confirm its getter is the method in this expression.
var runtimeProperties = declaringType.GetRuntimeProperties();
foreach (var property in runtimeProperties)
{
if ((string.Equals(defaultMember.MemberName, property.Name, StringComparison.Ordinal) &&
property.GetMethod == methodExpression.Method))
{
return true;
}
}
return false;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataTableExtenstions.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Linq.Expressions;
using System.Globalization;
using System.Diagnostics;
using System.Data.DataSetExtensions;
namespace System.Data
{
/// <summary>
/// This static class defines the DataTable extension methods.
/// </summary>
public static class DataTableExtensions
{
/// <summary>
/// This method returns a IEnumerable of Datarows.
/// </summary>
/// <param name="source">
/// The source DataTable to make enumerable.
/// </param>
/// <returns>
/// IEnumerable of datarows.
/// </returns>
public static EnumerableRowCollection<DataRow> AsEnumerable(this DataTable source)
{
DataSetUtil.CheckArgumentNull(source, "source");
return new EnumerableRowCollection<DataRow>(source);
}
/// <summary>
/// This method takes an input sequence of DataRows and produces a DataTable object
/// with copies of the source rows.
/// Also note that this will cause the rest of the query to execute at this point in time
/// (e.g. there is no more delayed execution after this sequence operator).
/// </summary>
/// <param name="source">
/// The input sequence of DataRows
/// </param>
/// <returns>
/// DataTable containing copies of the source DataRows.
/// Properties for the DataTable table will be taken from first DataRow in the source.
/// </returns>
/// <exception cref="ArgumentNullException">if source is null</exception>
/// <exception cref="InvalidOperationException">if source is empty</exception>
public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
where T : DataRow
{
DataSetUtil.CheckArgumentNull(source, "source");
return LoadTableFromEnumerable(source, null, null, null);
}
/// <summary>
/// delegates to other CopyToDataTable overload with a null FillErrorEventHandler.
/// </summary>
public static void CopyToDataTable<T>(this IEnumerable<T> source, DataTable table, LoadOption options)
where T : DataRow
{
DataSetUtil.CheckArgumentNull(source, "source");
DataSetUtil.CheckArgumentNull(table, "table");
LoadTableFromEnumerable(source, table, options, null);
}
/// <summary>
/// This method takes an input sequence of DataRows and produces a DataTable object
/// with copies of the source rows.
/// Also note that this will cause the rest of the query to execute at this point in time
/// (e.g. there is no more delayed execution after this sequence operator).
/// </summary>
/// <param name="source">
/// The input sequence of DataRows
///
/// CopyToDataTable uses DataRowVersion.Default when retrieving values from source DataRow
/// which will include proposed values for DataRow being edited.
///
/// Null DataRow in the sequence are skipped.
/// </param>
/// <param name="table">
/// The target DataTable to load.
/// </param>
/// <param name="options">
/// The target DataTable to load.
/// </param>
/// <param name="errorHandler">
/// Error handler for recoverable errors.
/// Recoverable errors include:
/// A source DataRow is in the deleted or detached state state.
/// DataTable.LoadDataRow threw an exception, i.e. wrong # of columns in source row
/// Unrecoverable errors include:
/// exceptions from IEnumerator, DataTable.BeginLoadData or DataTable.EndLoadData
/// </param>
/// <returns>
/// DataTable containing copies of the source DataRows.
/// </returns>
/// <exception cref="ArgumentNullException">if source is null</exception>
/// <exception cref="ArgumentNullException">if table is null</exception>
/// <exception cref="InvalidOperationException">if source DataRow is in Deleted or Detached state</exception>
public static void CopyToDataTable<T>(this IEnumerable<T> source, DataTable table, LoadOption options, FillErrorEventHandler errorHandler)
where T : DataRow
{
DataSetUtil.CheckArgumentNull(source, "source");
DataSetUtil.CheckArgumentNull(table, "table");
LoadTableFromEnumerable(source, table, options, errorHandler);
}
private static DataTable LoadTableFromEnumerable<T>(IEnumerable<T> source, DataTable table, LoadOption? options, FillErrorEventHandler errorHandler)
where T : DataRow
{
if (options.HasValue) {
switch(options.Value) {
case LoadOption.OverwriteChanges:
case LoadOption.PreserveChanges:
case LoadOption.Upsert:
break;
default:
throw DataSetUtil.InvalidLoadOption(options.Value);
}
}
using (IEnumerator<T> rows = source.GetEnumerator())
{
// need to get first row to create table
if (!rows.MoveNext())
{
if (table == null)
{
throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_EmptyDataRowSource);
}
else
{
return table;
}
}
DataRow current;
if (table == null)
{
current = rows.Current;
if (current == null)
{
throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_NullDataRow);
}
table = new DataTable();
table.Locale = CultureInfo.CurrentCulture;
// We do not copy the same properties that DataView.ToTable does.
// If user needs that functionality, use other CopyToDataTable overloads.
// The reasoning being, the IEnumerator<DataRow> can be sourced from
// different DataTable, so we just use the "Default" instead of resolving the difference.
foreach (DataColumn column in current.Table.Columns)
{
table.Columns.Add(column.ColumnName, column.DataType);
}
}
table.BeginLoadData();
try
{
do
{
current = rows.Current;
if (current == null)
{
continue;
}
object[] values = null;
try
{ // 'recoverable' error block
switch(current.RowState)
{
case DataRowState.Detached:
if (!current.HasVersion(DataRowVersion.Proposed))
{
throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_CannotLoadDetachedRow);
}
goto case DataRowState.Added;
case DataRowState.Unchanged:
case DataRowState.Added:
case DataRowState.Modified:
values = current.ItemArray;
if (options.HasValue)
{
table.LoadDataRow(values, options.Value);
}
else
{
table.LoadDataRow(values, true);
}
break;
case DataRowState.Deleted:
throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_CannotLoadDeletedRow);
default:
throw DataSetUtil.InvalidDataRowState(current.RowState);
}
}
catch (Exception e)
{
if (!DataSetUtil.IsCatchableExceptionType(e))
{
throw;
}
FillErrorEventArgs fillError = null;
if (null != errorHandler)
{
fillError = new FillErrorEventArgs(table, values);
fillError.Errors = e;
errorHandler.Invoke(rows, fillError);
}
if (null == fillError) {
throw;
}
else if (!fillError.Continue)
{
if (Object.ReferenceEquals(fillError.Errors ?? e, e))
{ // if user didn't change exception to throw (or set it to null)
throw;
}
else
{ // user may have changed exception to throw in handler
throw fillError.Errors;
}
}
}
} while (rows.MoveNext());
}
finally
{
table.EndLoadData();
}
}
Debug.Assert(null != table, "null DataTable");
return table;
}
#region Methods to Create LinqDataView
/// <summary>
/// Creates a LinkDataView of DataRow over the input table.
/// </summary>
/// <param name="table">DataTable that the view is over.</param>
/// <returns>An instance of LinkDataView.</returns>
public static DataView AsDataView(this DataTable table)
{
DataSetUtil.CheckArgumentNull<DataTable>(table, "table");
return new LinqDataView(table, null);
}
/// <summary>
/// Creates a LinqDataView from EnumerableDataTable
/// </summary>
/// <typeparam name="T">Type of the row in the table. Must inherit from DataRow</typeparam>
/// <param name="source">The enumerable-datatable over which view must be created.</param>
/// <returns>Generated LinkDataView of type T</returns>
public static DataView AsDataView<T>(this EnumerableRowCollection<T> source) where T : DataRow
{
DataSetUtil.CheckArgumentNull<EnumerableRowCollection<T>>(source, "source");
return source.GetLinqDataView();
}
#endregion LinqDataView
}
}
| |
namespace XenAdmin.Dialogs.Wlb
{
partial class WlbCredentialsDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WlbCredentialsDialog));
this.textboxWLBPort = new System.Windows.Forms.TextBox();
this.LabelWLBServerPort = new System.Windows.Forms.Label();
this.checkboxUseCurrentXSCredentials = new System.Windows.Forms.CheckBox();
this.textboxWlbUrl = new System.Windows.Forms.TextBox();
this.textboxXSPassword = new System.Windows.Forms.TextBox();
this.textboxXSUserName = new System.Windows.Forms.TextBox();
this.LabelXenServerPassword = new System.Windows.Forms.Label();
this.LabelXenServerUsername = new System.Windows.Forms.Label();
this.LabelXenServerCredsBlurb = new System.Windows.Forms.Label();
this.textboxWlbPassword = new System.Windows.Forms.TextBox();
this.textboxWlbUserName = new System.Windows.Forms.TextBox();
this.LabelWLBPassword = new System.Windows.Forms.Label();
this.LabelWLBUsername = new System.Windows.Forms.Label();
this.LabelWLBServerCredsBlurb = new System.Windows.Forms.Label();
this.LabelWLBServerName = new System.Windows.Forms.Label();
this.LabelWLBServerNameBlurb = new System.Windows.Forms.Label();
this.decentGroupBoxWLBServerAddress = new XenAdmin.Controls.DecentGroupBox();
this.labelDefaultPortBlurb = new System.Windows.Forms.Label();
this.decentGroupBoxWLBCredentials = new XenAdmin.Controls.DecentGroupBox();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.decentGroupBoxXSCredentials = new XenAdmin.Controls.DecentGroupBox();
this.pictureBox4 = new System.Windows.Forms.PictureBox();
this.pictureBox5 = new System.Windows.Forms.PictureBox();
this.pictureBox6 = new System.Windows.Forms.PictureBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOK = new System.Windows.Forms.Button();
this.imageListIcons = new System.Windows.Forms.ImageList(this.components);
this.decentGroupBoxWLBServerAddress.SuspendLayout();
this.decentGroupBoxWLBCredentials.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.decentGroupBoxXSCredentials.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).BeginInit();
this.SuspendLayout();
//
// textboxWLBPort
//
resources.ApplyResources(this.textboxWLBPort, "textboxWLBPort");
this.textboxWLBPort.Name = "textboxWLBPort";
this.textboxWLBPort.TextChanged += new System.EventHandler(this.textboxWLBPort_TextChanged);
//
// LabelWLBServerPort
//
resources.ApplyResources(this.LabelWLBServerPort, "LabelWLBServerPort");
this.LabelWLBServerPort.Name = "LabelWLBServerPort";
//
// checkboxUseCurrentXSCredentials
//
resources.ApplyResources(this.checkboxUseCurrentXSCredentials, "checkboxUseCurrentXSCredentials");
this.checkboxUseCurrentXSCredentials.Name = "checkboxUseCurrentXSCredentials";
this.checkboxUseCurrentXSCredentials.UseVisualStyleBackColor = true;
this.checkboxUseCurrentXSCredentials.CheckedChanged += new System.EventHandler(this.checkboxUseCurrentXSCredentials_CheckedChanged);
//
// textboxWlbUrl
//
resources.ApplyResources(this.textboxWlbUrl, "textboxWlbUrl");
this.textboxWlbUrl.Name = "textboxWlbUrl";
this.textboxWlbUrl.TextChanged += new System.EventHandler(this.textboxWlbUrl_TextChanged);
//
// textboxXSPassword
//
resources.ApplyResources(this.textboxXSPassword, "textboxXSPassword");
this.textboxXSPassword.Name = "textboxXSPassword";
this.textboxXSPassword.TextChanged += new System.EventHandler(this.textboxXSPassword_TextChanged);
//
// textboxXSUserName
//
resources.ApplyResources(this.textboxXSUserName, "textboxXSUserName");
this.textboxXSUserName.Name = "textboxXSUserName";
this.textboxXSUserName.TextChanged += new System.EventHandler(this.textboxXSUserName_TextChanged);
//
// LabelXenServerPassword
//
resources.ApplyResources(this.LabelXenServerPassword, "LabelXenServerPassword");
this.LabelXenServerPassword.Name = "LabelXenServerPassword";
//
// LabelXenServerUsername
//
resources.ApplyResources(this.LabelXenServerUsername, "LabelXenServerUsername");
this.LabelXenServerUsername.Name = "LabelXenServerUsername";
//
// LabelXenServerCredsBlurb
//
resources.ApplyResources(this.LabelXenServerCredsBlurb, "LabelXenServerCredsBlurb");
this.LabelXenServerCredsBlurb.Name = "LabelXenServerCredsBlurb";
//
// textboxWlbPassword
//
resources.ApplyResources(this.textboxWlbPassword, "textboxWlbPassword");
this.textboxWlbPassword.Name = "textboxWlbPassword";
this.textboxWlbPassword.TextChanged += new System.EventHandler(this.textboxWlbPassword_TextChanged);
//
// textboxWlbUserName
//
resources.ApplyResources(this.textboxWlbUserName, "textboxWlbUserName");
this.textboxWlbUserName.Name = "textboxWlbUserName";
this.textboxWlbUserName.TextChanged += new System.EventHandler(this.textboxWlbUserName_TextChanged);
//
// LabelWLBPassword
//
resources.ApplyResources(this.LabelWLBPassword, "LabelWLBPassword");
this.LabelWLBPassword.Name = "LabelWLBPassword";
//
// LabelWLBUsername
//
resources.ApplyResources(this.LabelWLBUsername, "LabelWLBUsername");
this.LabelWLBUsername.Name = "LabelWLBUsername";
//
// LabelWLBServerCredsBlurb
//
resources.ApplyResources(this.LabelWLBServerCredsBlurb, "LabelWLBServerCredsBlurb");
this.LabelWLBServerCredsBlurb.Name = "LabelWLBServerCredsBlurb";
//
// LabelWLBServerName
//
resources.ApplyResources(this.LabelWLBServerName, "LabelWLBServerName");
this.LabelWLBServerName.Name = "LabelWLBServerName";
//
// LabelWLBServerNameBlurb
//
resources.ApplyResources(this.LabelWLBServerNameBlurb, "LabelWLBServerNameBlurb");
this.LabelWLBServerNameBlurb.Name = "LabelWLBServerNameBlurb";
//
// decentGroupBoxWLBServerAddress
//
resources.ApplyResources(this.decentGroupBoxWLBServerAddress, "decentGroupBoxWLBServerAddress");
this.decentGroupBoxWLBServerAddress.Controls.Add(this.labelDefaultPortBlurb);
this.decentGroupBoxWLBServerAddress.Controls.Add(this.LabelWLBServerNameBlurb);
this.decentGroupBoxWLBServerAddress.Controls.Add(this.textboxWLBPort);
this.decentGroupBoxWLBServerAddress.Controls.Add(this.textboxWlbUrl);
this.decentGroupBoxWLBServerAddress.Controls.Add(this.LabelWLBServerPort);
this.decentGroupBoxWLBServerAddress.Controls.Add(this.LabelWLBServerName);
this.decentGroupBoxWLBServerAddress.Name = "decentGroupBoxWLBServerAddress";
this.decentGroupBoxWLBServerAddress.TabStop = false;
//
// labelDefaultPortBlurb
//
resources.ApplyResources(this.labelDefaultPortBlurb, "labelDefaultPortBlurb");
this.labelDefaultPortBlurb.Name = "labelDefaultPortBlurb";
//
// decentGroupBoxWLBCredentials
//
resources.ApplyResources(this.decentGroupBoxWLBCredentials, "decentGroupBoxWLBCredentials");
this.decentGroupBoxWLBCredentials.Controls.Add(this.pictureBox3);
this.decentGroupBoxWLBCredentials.Controls.Add(this.pictureBox2);
this.decentGroupBoxWLBCredentials.Controls.Add(this.pictureBox1);
this.decentGroupBoxWLBCredentials.Controls.Add(this.LabelWLBServerCredsBlurb);
this.decentGroupBoxWLBCredentials.Controls.Add(this.LabelWLBUsername);
this.decentGroupBoxWLBCredentials.Controls.Add(this.LabelWLBPassword);
this.decentGroupBoxWLBCredentials.Controls.Add(this.textboxWlbUserName);
this.decentGroupBoxWLBCredentials.Controls.Add(this.textboxWlbPassword);
this.decentGroupBoxWLBCredentials.Name = "decentGroupBoxWLBCredentials";
this.decentGroupBoxWLBCredentials.TabStop = false;
//
// pictureBox3
//
resources.ApplyResources(this.pictureBox3, "pictureBox3");
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.TabStop = false;
//
// pictureBox2
//
resources.ApplyResources(this.pictureBox2, "pictureBox2");
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.TabStop = false;
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::XenAdmin.Properties.Resources._112_RightArrowLong_Blue_24x24_72;
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// decentGroupBoxXSCredentials
//
resources.ApplyResources(this.decentGroupBoxXSCredentials, "decentGroupBoxXSCredentials");
this.decentGroupBoxXSCredentials.Controls.Add(this.pictureBox4);
this.decentGroupBoxXSCredentials.Controls.Add(this.pictureBox5);
this.decentGroupBoxXSCredentials.Controls.Add(this.pictureBox6);
this.decentGroupBoxXSCredentials.Controls.Add(this.LabelXenServerCredsBlurb);
this.decentGroupBoxXSCredentials.Controls.Add(this.textboxXSUserName);
this.decentGroupBoxXSCredentials.Controls.Add(this.LabelXenServerUsername);
this.decentGroupBoxXSCredentials.Controls.Add(this.checkboxUseCurrentXSCredentials);
this.decentGroupBoxXSCredentials.Controls.Add(this.LabelXenServerPassword);
this.decentGroupBoxXSCredentials.Controls.Add(this.textboxXSPassword);
this.decentGroupBoxXSCredentials.Name = "decentGroupBoxXSCredentials";
this.decentGroupBoxXSCredentials.TabStop = false;
//
// pictureBox4
//
resources.ApplyResources(this.pictureBox4, "pictureBox4");
this.pictureBox4.Name = "pictureBox4";
this.pictureBox4.TabStop = false;
//
// pictureBox5
//
resources.ApplyResources(this.pictureBox5, "pictureBox5");
this.pictureBox5.Name = "pictureBox5";
this.pictureBox5.TabStop = false;
//
// pictureBox6
//
resources.ApplyResources(this.pictureBox6, "pictureBox6");
this.pictureBox6.Image = global::XenAdmin.Properties.Resources._112_LeftArrowLong_Blue_24x24_72;
this.pictureBox6.Name = "pictureBox6";
this.pictureBox6.TabStop = false;
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonOK
//
resources.ApplyResources(this.buttonOK, "buttonOK");
this.buttonOK.Name = "buttonOK";
this.buttonOK.UseVisualStyleBackColor = true;
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// imageListIcons
//
this.imageListIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListIcons.ImageStream")));
this.imageListIcons.TransparentColor = System.Drawing.Color.Transparent;
this.imageListIcons.Images.SetKeyName(0, "WlbServer");
this.imageListIcons.Images.SetKeyName(1, "XenServer");
this.imageListIcons.Images.SetKeyName(2, "LeftArrow");
this.imageListIcons.Images.SetKeyName(3, "RightArrow");
//
// WlbCredentialsDialog
//
this.AcceptButton = this.buttonOK;
resources.ApplyResources(this, "$this");
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.decentGroupBoxXSCredentials);
this.Controls.Add(this.decentGroupBoxWLBCredentials);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.decentGroupBoxWLBServerAddress);
this.Name = "WlbCredentialsDialog";
this.decentGroupBoxWLBServerAddress.ResumeLayout(false);
this.decentGroupBoxWLBServerAddress.PerformLayout();
this.decentGroupBoxWLBCredentials.ResumeLayout(false);
this.decentGroupBoxWLBCredentials.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.decentGroupBoxXSCredentials.ResumeLayout(false);
this.decentGroupBoxXSCredentials.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TextBox textboxWLBPort;
private System.Windows.Forms.Label LabelWLBServerPort;
private System.Windows.Forms.CheckBox checkboxUseCurrentXSCredentials;
private System.Windows.Forms.TextBox textboxWlbUrl;
private System.Windows.Forms.TextBox textboxXSPassword;
private System.Windows.Forms.TextBox textboxXSUserName;
private System.Windows.Forms.Label LabelXenServerPassword;
private System.Windows.Forms.Label LabelXenServerUsername;
private System.Windows.Forms.Label LabelXenServerCredsBlurb;
private System.Windows.Forms.TextBox textboxWlbPassword;
private System.Windows.Forms.TextBox textboxWlbUserName;
private System.Windows.Forms.Label LabelWLBPassword;
private System.Windows.Forms.Label LabelWLBUsername;
private System.Windows.Forms.Label LabelWLBServerCredsBlurb;
private System.Windows.Forms.Label LabelWLBServerName;
private System.Windows.Forms.Label LabelWLBServerNameBlurb;
private XenAdmin.Controls.DecentGroupBox decentGroupBoxWLBServerAddress;
private XenAdmin.Controls.DecentGroupBox decentGroupBoxWLBCredentials;
private XenAdmin.Controls.DecentGroupBox decentGroupBoxXSCredentials;
private System.Windows.Forms.Label labelDefaultPortBlurb;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ImageList imageListIcons;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.PictureBox pictureBox4;
private System.Windows.Forms.PictureBox pictureBox5;
private System.Windows.Forms.PictureBox pictureBox6;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LiftedComparisonNotEqualNullableTests
{
#region Test methods
[Fact]
public static void CheckLiftedComparisonNotEqualNullableBoolTest()
{
bool?[] values = new bool?[] { null, true, false };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableBool(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableByteTest()
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableByte(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableCharTest()
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableChar(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableDecimalTest()
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableDecimal(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableDoubleTest()
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableDouble(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableFloatTest()
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableFloat(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableIntTest()
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableInt(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableLongTest()
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableLong(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableSByteTest()
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableSByte(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableShortTest()
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableShort(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableUIntTest()
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableUInt(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableULongTest()
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableULong(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonNotEqualNullableUShortTest()
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonNotEqualNullableUShort(values[i], values[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyComparisonNotEqualNullableBool(bool? a, bool? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableByte(byte? a, byte? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableChar(char? a, char? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableDecimal(decimal? a, decimal? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableDouble(double? a, double? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableFloat(float? a, float? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableInt(int? a, int? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableLong(long? a, long? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableSByte(sbyte? a, sbyte? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableShort(short? a, short? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableUInt(uint? a, uint? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableULong(ulong? a, ulong? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonNotEqualNullableUShort(ushort? a, ushort? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.NotEqual(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a != b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComUtils.MasterSetup.DS
{
public class MST_ExchangeRateDS
{
public MST_ExchangeRateDS()
{
}
private const string THIS = "PCSComUtils.MasterSetup.DS.MST_ExchangeRateDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to MST_ExchangeRate
/// </Description>
/// <Inputs>
/// MST_ExchangeRateVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
MST_ExchangeRateVO objObject = (MST_ExchangeRateVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO MST_ExchangeRate("
+ MST_ExchangeRateTable.CODE_FLD + ","
+ MST_ExchangeRateTable.RATE_FLD + ","
+ MST_ExchangeRateTable.DESCRIPTION_FLD + ","
+ MST_ExchangeRateTable.APPROVED_FLD + ","
+ MST_ExchangeRateTable.APPROVALDATE_FLD + ","
+ MST_ExchangeRateTable.BEGINDATE_FLD + ","
+ MST_ExchangeRateTable.ENDDATE_FLD + ","
+ MST_ExchangeRateTable.CCNID_FLD + ","
+ MST_ExchangeRateTable.CURRENCYID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_ExchangeRateTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.RATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[MST_ExchangeRateTable.RATE_FLD].Value = objObject.Rate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_ExchangeRateTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.APPROVED_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[MST_ExchangeRateTable.APPROVED_FLD].Value = objObject.Approved;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.APPROVALDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[MST_ExchangeRateTable.APPROVALDATE_FLD].Value = objObject.ApprovalDate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.BEGINDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[MST_ExchangeRateTable.BEGINDATE_FLD].Value = objObject.BeginDate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.ENDDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[MST_ExchangeRateTable.ENDDATE_FLD].Value = objObject.EndDate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_ExchangeRateTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.CURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_ExchangeRateTable.CURRENCYID_FLD].Value = objObject.CurrencyID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from MST_ExchangeRate
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + MST_ExchangeRateTable.TABLE_NAME + " WHERE " + "ExchangeRateID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_ExchangeRate
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_ExchangeRateVO
/// </Outputs>
/// <Returns>
/// MST_ExchangeRateVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_ExchangeRateTable.EXCHANGERATEID_FLD + ","
+ MST_ExchangeRateTable.CODE_FLD + ","
+ MST_ExchangeRateTable.RATE_FLD + ","
+ MST_ExchangeRateTable.DESCRIPTION_FLD + ","
+ MST_ExchangeRateTable.APPROVED_FLD + ","
+ MST_ExchangeRateTable.APPROVALDATE_FLD + ","
+ MST_ExchangeRateTable.BEGINDATE_FLD + ","
+ MST_ExchangeRateTable.ENDDATE_FLD + ","
+ MST_ExchangeRateTable.CCNID_FLD + ","
+ MST_ExchangeRateTable.CURRENCYID_FLD
+ " FROM " + MST_ExchangeRateTable.TABLE_NAME
+" WHERE " + MST_ExchangeRateTable.EXCHANGERATEID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
MST_ExchangeRateVO objObject = new MST_ExchangeRateVO();
while (odrPCS.Read())
{
objObject.ExchangeRateID = int.Parse(odrPCS[MST_ExchangeRateTable.EXCHANGERATEID_FLD].ToString().Trim());
objObject.Code = odrPCS[MST_ExchangeRateTable.CODE_FLD].ToString().Trim();
objObject.Rate = Decimal.Parse(odrPCS[MST_ExchangeRateTable.RATE_FLD].ToString().Trim());
objObject.Description = odrPCS[MST_ExchangeRateTable.DESCRIPTION_FLD].ToString().Trim();
objObject.Approved = bool.Parse(odrPCS[MST_ExchangeRateTable.APPROVED_FLD].ToString().Trim());
objObject.ApprovalDate = DateTime.Parse(odrPCS[MST_ExchangeRateTable.APPROVALDATE_FLD].ToString().Trim());
objObject.BeginDate = DateTime.Parse(odrPCS[MST_ExchangeRateTable.BEGINDATE_FLD].ToString().Trim());
objObject.EndDate = DateTime.Parse(odrPCS[MST_ExchangeRateTable.ENDDATE_FLD].ToString().Trim());
objObject.CCNID = int.Parse(odrPCS[MST_ExchangeRateTable.CCNID_FLD].ToString().Trim());
objObject.CurrencyID = int.Parse(odrPCS[MST_ExchangeRateTable.CURRENCYID_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_ExchangeRate
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_ExchangeRateVO
/// </Outputs>
/// <Returns>
/// MST_ExchangeRateVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetExchangeRate(int pintCurrencyID,DateTime pdtmOrderDate)
{
const string METHOD_NAME = THIS + ".GetExchangeRate()";
const string YYYYMMDD = "yyyyMMdd";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_ExchangeRateTable.EXCHANGERATEID_FLD + ","
+ MST_ExchangeRateTable.CODE_FLD + ","
+ MST_ExchangeRateTable.RATE_FLD + ","
+ MST_ExchangeRateTable.DESCRIPTION_FLD + ","
+ MST_ExchangeRateTable.APPROVED_FLD + ","
+ MST_ExchangeRateTable.APPROVALDATE_FLD + ","
+ MST_ExchangeRateTable.BEGINDATE_FLD + ","
+ MST_ExchangeRateTable.ENDDATE_FLD + ","
+ MST_ExchangeRateTable.CCNID_FLD + ","
+ MST_ExchangeRateTable.CURRENCYID_FLD
+ " FROM " + MST_ExchangeRateTable.TABLE_NAME
+ " WHERE " + MST_ExchangeRateTable.CURRENCYID_FLD + "=" + pintCurrencyID
+ " AND " + MST_ExchangeRateTable.APPROVED_FLD + "=1 "
+ " AND DATEDIFF(dayofyear," + MST_ExchangeRateTable.BEGINDATE_FLD + ",'" + pdtmOrderDate.ToString(YYYYMMDD) + "') >= 0"
+ " AND DATEDIFF(dayofyear," + MST_ExchangeRateTable.ENDDATE_FLD + ",'" + pdtmOrderDate.ToString(YYYYMMDD) + "') <= 0";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
MST_ExchangeRateVO objObject = new MST_ExchangeRateVO();
while (odrPCS.Read())
{
objObject.ExchangeRateID = int.Parse(odrPCS[MST_ExchangeRateTable.EXCHANGERATEID_FLD].ToString().Trim());
objObject.Code = odrPCS[MST_ExchangeRateTable.CODE_FLD].ToString().Trim();
objObject.Rate = Decimal.Parse(odrPCS[MST_ExchangeRateTable.RATE_FLD].ToString().Trim());
objObject.Description = odrPCS[MST_ExchangeRateTable.DESCRIPTION_FLD].ToString().Trim();
objObject.Approved = bool.Parse(odrPCS[MST_ExchangeRateTable.APPROVED_FLD].ToString().Trim());
objObject.ApprovalDate = DateTime.Parse(odrPCS[MST_ExchangeRateTable.APPROVALDATE_FLD].ToString().Trim());
objObject.BeginDate = DateTime.Parse(odrPCS[MST_ExchangeRateTable.BEGINDATE_FLD].ToString().Trim());
objObject.EndDate = DateTime.Parse(odrPCS[MST_ExchangeRateTable.ENDDATE_FLD].ToString().Trim());
objObject.CCNID = int.Parse(odrPCS[MST_ExchangeRateTable.CCNID_FLD].ToString().Trim());
objObject.CurrencyID = int.Parse(odrPCS[MST_ExchangeRateTable.CURRENCYID_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_ExchangeRate
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_ExchangeRateVO
/// </Outputs>
/// <Returns>
/// MST_ExchangeRateVO
/// </Returns>
/// <Authors>
/// SonHT
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public decimal GetLastExchangeRate(int pintCurrencyID,DateTime pdtmOrderDate)
{
const string METHOD_NAME = THIS + ".GetExchangeRate()";
const string YYYYMMDD = "yyyyMMdd";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT " + MST_ExchangeRateTable.RATE_FLD
+ " FROM " + MST_ExchangeRateTable.TABLE_NAME
+ " WHERE " + MST_ExchangeRateTable.CURRENCYID_FLD + "=" + pintCurrencyID
+ " AND " + MST_ExchangeRateTable.APPROVED_FLD + "=1 "
+ " AND DATEDIFF(dayofyear," + MST_ExchangeRateTable.BEGINDATE_FLD + ",'" + pdtmOrderDate.ToString(YYYYMMDD) + "') >= 0"
+ " AND DATEDIFF(dayofyear," + MST_ExchangeRateTable.ENDDATE_FLD + ",'" + pdtmOrderDate.ToString(YYYYMMDD) + "') <= 0"
+ " ORDER BY " + MST_ExchangeRateTable.EXCHANGERATEID_FLD + " DESC";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
while (odrPCS.Read())
{
return Convert.ToDecimal(odrPCS[MST_ExchangeRateTable.RATE_FLD]);
}
return 1;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to MST_ExchangeRate
/// </Description>
/// <Inputs>
/// MST_ExchangeRateVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
MST_ExchangeRateVO objObject = (MST_ExchangeRateVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE MST_ExchangeRate SET "
+ MST_ExchangeRateTable.CODE_FLD + "= ?" + ","
+ MST_ExchangeRateTable.RATE_FLD + "= ?" + ","
+ MST_ExchangeRateTable.DESCRIPTION_FLD + "= ?" + ","
+ MST_ExchangeRateTable.APPROVED_FLD + "= ?" + ","
+ MST_ExchangeRateTable.APPROVALDATE_FLD + "= ?" + ","
+ MST_ExchangeRateTable.BEGINDATE_FLD + "= ?" + ","
+ MST_ExchangeRateTable.ENDDATE_FLD + "= ?" + ","
+ MST_ExchangeRateTable.CCNID_FLD + "= ?" + ","
+ MST_ExchangeRateTable.CURRENCYID_FLD + "= ?"
+" WHERE " + MST_ExchangeRateTable.EXCHANGERATEID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_ExchangeRateTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.RATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[MST_ExchangeRateTable.RATE_FLD].Value = objObject.Rate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_ExchangeRateTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.APPROVED_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[MST_ExchangeRateTable.APPROVED_FLD].Value = objObject.Approved;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.APPROVALDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[MST_ExchangeRateTable.APPROVALDATE_FLD].Value = objObject.ApprovalDate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.BEGINDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[MST_ExchangeRateTable.BEGINDATE_FLD].Value = objObject.BeginDate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.ENDDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[MST_ExchangeRateTable.ENDDATE_FLD].Value = objObject.EndDate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_ExchangeRateTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.CURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_ExchangeRateTable.CURRENCYID_FLD].Value = objObject.CurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_ExchangeRateTable.EXCHANGERATEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_ExchangeRateTable.EXCHANGERATEID_FLD].Value = objObject.ExchangeRateID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from MST_ExchangeRate
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_ExchangeRateTable.EXCHANGERATEID_FLD + ","
+ MST_ExchangeRateTable.CODE_FLD + ","
+ MST_ExchangeRateTable.RATE_FLD + ","
+ MST_ExchangeRateTable.DESCRIPTION_FLD + ","
+ MST_ExchangeRateTable.APPROVED_FLD + ","
+ MST_ExchangeRateTable.APPROVALDATE_FLD + ","
+ MST_ExchangeRateTable.BEGINDATE_FLD + ","
+ MST_ExchangeRateTable.ENDDATE_FLD + ","
+ MST_ExchangeRateTable.CCNID_FLD + ","
+ MST_ExchangeRateTable.CURRENCYID_FLD
+ " FROM " + MST_ExchangeRateTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_ExchangeRateTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ MST_ExchangeRateTable.EXCHANGERATEID_FLD + ","
+ MST_ExchangeRateTable.CODE_FLD + ","
+ MST_ExchangeRateTable.RATE_FLD + ","
+ MST_ExchangeRateTable.DESCRIPTION_FLD + ","
+ MST_ExchangeRateTable.APPROVED_FLD + ","
+ MST_ExchangeRateTable.APPROVALDATE_FLD + ","
+ MST_ExchangeRateTable.BEGINDATE_FLD + ","
+ MST_ExchangeRateTable.ENDDATE_FLD + ","
+ MST_ExchangeRateTable.CCNID_FLD + ","
+ MST_ExchangeRateTable.CURRENCYID_FLD
+ " FROM " + MST_ExchangeRateTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,MST_ExchangeRateTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// List all exchange rate of CCN
/// </summary>
/// <param name="pintCCNID"></param>
/// <returns></returns>
public DataTable List(int pintCCNID)
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_ExchangeRateTable.EXCHANGERATEID_FLD + ","
+ MST_ExchangeRateTable.CODE_FLD + ","
+ MST_ExchangeRateTable.RATE_FLD + ","
+ MST_ExchangeRateTable.DESCRIPTION_FLD + ","
+ MST_ExchangeRateTable.APPROVED_FLD + ","
+ MST_ExchangeRateTable.APPROVALDATE_FLD + ","
+ MST_ExchangeRateTable.BEGINDATE_FLD + ","
+ MST_ExchangeRateTable.ENDDATE_FLD + ","
+ MST_ExchangeRateTable.CCNID_FLD + ","
+ MST_ExchangeRateTable.CURRENCYID_FLD
+ " FROM " + MST_ExchangeRateTable.TABLE_NAME
+ " WHERE " + MST_ExchangeRateTable.CCNID_FLD + "=" + pintCCNID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_ExchangeRateTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace API
{
public static class ExtensionAssemblies
{
public static Dictionary<Assembly, bool> Assemblies = new Dictionary<Assembly, bool>();
public static void LoadExtensions()
{
var files = Directory.EnumerateFiles("mods", "*.dll");
foreach (var f in files)
{
AddAssembly(Path.GetFullPath(f));
}
}
public static Assembly AddAssembly(string path)
{
var assembly = Assembly.LoadFile(path);
if (Assemblies.ContainsKey(assembly)) UnregisterTypes(assembly);
Assemblies[assembly] = false;
return assembly;
}
internal static void UnregisterTypes(Assembly assembly)
{
}
public static void RegisterTypes<T>(IEnumerable<Type> types = null)
{
RegisterTypes(typeof (T), types);
}
internal static void RegisterTypes(Type tType, IEnumerable<Type> types = null)
{
if (types == null)
types = Assemblies.Where(pair => pair.Value == false).SelectMany(module => module.Key.GetTypes()).ToArray();
foreach (var t in types.Where(type => type.IsSubclassOf(tType)))
{
var attr = t.GetCustomAttribute<ExtensionAttribute>();
if (attr != null)
t.InvokeMember(attr.Register, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null,
new object[0]);
Assemblies[t.Assembly] = true;
}
}
private static SortedList<int, TExtendableClass> GetExtensionClasses<TExtendableClass>(TExtendableClass obj)
{
if (!(obj is IExtendableClass<TExtendableClass>))
throw new ArgumentException("Supplied object is not an IExtendableClass", "obj");
return (obj as IExtendableClass<TExtendableClass>).ExtensionClasses;
}
#region Actions
public static void CallExtendedAction<TExtendableClass>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Action<ExtensionContext>>> overrideMethod)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext();
var par = new object[] {context};
ProcessExtendedCall(extensionClasses.Values.Select(arg => (object) arg), overrideMethod, par);
}
public static void CallExtendedAction<TExtendableClass, T1>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Action<ExtensionContext, T1>>> overrideMethod,
T1 t1)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext();
var par = new object[] { context, t1};
ProcessExtendedCall(extensionClasses.Values.Select(arg => (object)arg), overrideMethod, par);
}
public static void CallExtendedAction<TExtendableClass, T1, T2>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Action<ExtensionContext, T1, T2>>> overrideMethod,
T1 t1,
T2 t2)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext();
var par = new object[] { context, t1, t2 };
ProcessExtendedCall(extensionClasses.Values.Select(arg => (object)arg), overrideMethod, par);
}
public static void CallExtendedAction<TExtendableClass, T1, T2, T3>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Action<ExtensionContext, T1, T2, T3>>> overrideMethod,
T1 t1,
T2 t2,
T3 t3)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext();
var par = new object[] { context, t1, t2, t3 };
ProcessExtendedCall(extensionClasses.Values.Select(arg => (object)arg), overrideMethod, par);
}
public static void CallExtendedAction<TExtendableClass, T1, T2, T3, T4>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Action<ExtensionContext, T1, T2, T3, T4>>> overrideMethod,
T1 t1,
T2 t2,
T3 t3,
T4 t4)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext();
var par = new object[] { context, t1, t2, t3, t4 };
ProcessExtendedCall(extensionClasses.Values.Select(arg => (object)arg), overrideMethod, par);
}
public static void CallExtendedAction<TExtendableClass, T1, T2, T3, T4, T5>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Action<ExtensionContext, T1, T2, T3, T4, T5>>> overrideMethod,
T1 t1,
T2 t2,
T3 t3,
T4 t4,
T5 t5)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext();
var par = new object[] {context, t1, t2, t3, t4, t5};
ProcessExtendedCall(extensionClasses.Values.Select(arg => (object) arg), overrideMethod, par);
}
#endregion
#region Functions
public static TReturn CallExtended<TExtendableClass, TReturn>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Func<ExtensionContext<TReturn>, TReturn>>> overrideMethod)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext<TReturn> { LastValue = default(TReturn) };
var par = new object[] {context};
return ProcessExtendedCall<TReturn>(extensionClasses.Values.Select(arg => (object) arg), overrideMethod, par, context);
}
public static TReturn CallExtended<TExtendableClass, TReturn, T1>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Func<ExtensionContext<TReturn>, T1, TReturn>>> overrideMethod,
T1 t1)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext<TReturn> { LastValue = default(TReturn) };
var par = new object[] {context, t1};
return ProcessExtendedCall<TReturn>(extensionClasses.Values.Select(arg => (object) arg), overrideMethod, par, context);
}
public static TReturn CallExtended<TExtendableClass, TReturn, T1, T2>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Func<ExtensionContext<TReturn>, T1, T2, TReturn>>> overrideMethod,
T1 t1,
T2 t2)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext<TReturn> { LastValue = default(TReturn) };
var par = new object[] {context, t1, t2};
return ProcessExtendedCall<TReturn>(extensionClasses.Values.Select(arg => (object) arg), overrideMethod, par, context);
}
public static TReturn CallExtended<TExtendableClass, TReturn, T1, T2, T3>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Func<ExtensionContext<TReturn>, T1, T2, T3, TReturn>>> overrideMethod,
T1 t1,
T2 t2,
T3 t3)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext<TReturn> { LastValue = default(TReturn) };
var par = new object[] { context, t1, t2, t3 };
return ProcessExtendedCall<TReturn>(extensionClasses.Values.Select(arg => (object)arg), overrideMethod, par, context);
}
public static TReturn CallExtended<TExtendableClass, TReturn, T1, T2, T3, T4>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Func<ExtensionContext<TReturn>, T1, T2, T3, T4, TReturn>>> overrideMethod,
T1 t1,
T2 t2,
T3 t3,
T4 t4)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext<TReturn> { LastValue = default(TReturn) };
var par = new object[] { context, t1, t2, t3, t4 };
return ProcessExtendedCall<TReturn>(extensionClasses.Values.Select(arg => (object)arg), overrideMethod, par, context);
}
public static TReturn CallExtended<TExtendableClass, TReturn, T1, T2, T3, T4, T5>(
TExtendableClass obj,
Expression<Func<TExtendableClass, Func<ExtensionContext<TReturn>, T1, T2, T3, T4, T5, TReturn>>> overrideMethod,
T1 t1,
T2 t2,
T3 t3,
T4 t4,
T5 t5)
{
var extensionClasses = GetExtensionClasses(obj);
var context = new ExtensionContext<TReturn> { LastValue = default(TReturn) };
var par = new object[] { context, t1, t2, t3, t4, t5 };
return ProcessExtendedCall<TReturn>(extensionClasses.Values.Select(arg => (object)arg), overrideMethod, par, context);
}
#endregion
private static TReturn ProcessExtendedCall<TReturn>(IEnumerable<object> extensionClasses, Expression overrideMethod, object[] par,
ExtensionContext context)
{
var mi =
((((((LambdaExpression) overrideMethod).Body as UnaryExpression).Operand as MethodCallExpression).Object as
ConstantExpression).Value) as MethodInfo;
foreach (
var result in
extensionClasses.Select(
foo =>
(TReturn)
mi.Invoke(foo, BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, par, null))
)
{
context.SetValue(result);
}
return context.GetValue<TReturn>();
}
private static void ProcessExtendedCall(IEnumerable<object> extensionClasses, Expression overrideMethod, object[] par)
{
var mi = ((((((LambdaExpression)overrideMethod).Body as UnaryExpression).Operand as MethodCallExpression).Object as ConstantExpression).Value) as MethodInfo;
foreach (
var result in
extensionClasses)
mi.Invoke(result, BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, par, null);
}
public static void AddExtensions<TExtendableClass>(TExtendableClass obj)
where TExtendableClass : class
{
var extensionClasses = GetExtensionClasses(obj);
extensionClasses.Add(0, obj);
foreach (var f in ClassExtender.GetInstanceCreators<TExtendableClass>())
{
var ff = f.Value(obj);
if (ff != null) extensionClasses.Add(f.Key, ff);
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// 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.
#endregion
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
internal partial class NativeMethods
{
#region Native methods
public readonly Delegates.grpcsharp_init_delegate grpcsharp_init;
public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown;
public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string;
public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create;
public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length;
public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled;
public readonly Delegates.grpcsharp_batch_context_reset_delegate grpcsharp_batch_context_reset;
public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy;
public readonly Delegates.grpcsharp_request_call_context_create_delegate grpcsharp_request_call_context_create;
public readonly Delegates.grpcsharp_request_call_context_call_delegate grpcsharp_request_call_context_call;
public readonly Delegates.grpcsharp_request_call_context_method_delegate grpcsharp_request_call_context_method;
public readonly Delegates.grpcsharp_request_call_context_host_delegate grpcsharp_request_call_context_host;
public readonly Delegates.grpcsharp_request_call_context_deadline_delegate grpcsharp_request_call_context_deadline;
public readonly Delegates.grpcsharp_request_call_context_request_metadata_delegate grpcsharp_request_call_context_request_metadata;
public readonly Delegates.grpcsharp_request_call_context_reset_delegate grpcsharp_request_call_context_reset;
public readonly Delegates.grpcsharp_request_call_context_destroy_delegate grpcsharp_request_call_context_destroy;
public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create;
public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release;
public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel;
public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status;
public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary;
public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming;
public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming;
public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming;
public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message;
public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client;
public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server;
public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message;
public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata;
public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside;
public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata;
public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials;
public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer;
public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy;
public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create;
public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string;
public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer;
public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy;
public readonly Delegates.grpcsharp_override_default_ssl_roots_delegate grpcsharp_override_default_ssl_roots;
public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create;
public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create;
public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release;
public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create;
public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create;
public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call;
public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state;
public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state;
public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target;
public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy;
public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event;
public readonly Delegates.grpcsharp_completion_queue_create_async_delegate grpcsharp_completion_queue_create_async;
public readonly Delegates.grpcsharp_completion_queue_create_sync_delegate grpcsharp_completion_queue_create_sync;
public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown;
public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next;
public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck;
public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy;
public readonly Delegates.gprsharp_free_delegate gprsharp_free;
public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create;
public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add;
public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count;
public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key;
public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value;
public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full;
public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log;
public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin;
public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin;
public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create;
public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release;
public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create;
public readonly Delegates.grpcsharp_server_register_completion_queue_delegate grpcsharp_server_register_completion_queue;
public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port;
public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port;
public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start;
public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call;
public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls;
public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback;
public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy;
public readonly Delegates.grpcsharp_call_auth_context_delegate grpcsharp_call_auth_context;
public readonly Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate grpcsharp_auth_context_peer_identity_property_name;
public readonly Delegates.grpcsharp_auth_context_property_iterator_delegate grpcsharp_auth_context_property_iterator;
public readonly Delegates.grpcsharp_auth_property_iterator_next_delegate grpcsharp_auth_property_iterator_next;
public readonly Delegates.grpcsharp_auth_context_release_delegate grpcsharp_auth_context_release;
public readonly Delegates.gprsharp_now_delegate gprsharp_now;
public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future;
public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past;
public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type;
public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec;
public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback;
public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop;
public readonly Delegates.grpcsharp_test_override_method_delegate grpcsharp_test_override_method;
#endregion
public NativeMethods(UnmanagedLibrary library)
{
this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library);
this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library);
this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library);
this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library);
this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library);
this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library);
this.grpcsharp_batch_context_reset = GetMethodDelegate<Delegates.grpcsharp_batch_context_reset_delegate>(library);
this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library);
this.grpcsharp_request_call_context_create = GetMethodDelegate<Delegates.grpcsharp_request_call_context_create_delegate>(library);
this.grpcsharp_request_call_context_call = GetMethodDelegate<Delegates.grpcsharp_request_call_context_call_delegate>(library);
this.grpcsharp_request_call_context_method = GetMethodDelegate<Delegates.grpcsharp_request_call_context_method_delegate>(library);
this.grpcsharp_request_call_context_host = GetMethodDelegate<Delegates.grpcsharp_request_call_context_host_delegate>(library);
this.grpcsharp_request_call_context_deadline = GetMethodDelegate<Delegates.grpcsharp_request_call_context_deadline_delegate>(library);
this.grpcsharp_request_call_context_request_metadata = GetMethodDelegate<Delegates.grpcsharp_request_call_context_request_metadata_delegate>(library);
this.grpcsharp_request_call_context_reset = GetMethodDelegate<Delegates.grpcsharp_request_call_context_reset_delegate>(library);
this.grpcsharp_request_call_context_destroy = GetMethodDelegate<Delegates.grpcsharp_request_call_context_destroy_delegate>(library);
this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library);
this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library);
this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library);
this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library);
this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library);
this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library);
this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library);
this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library);
this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library);
this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library);
this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library);
this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library);
this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library);
this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library);
this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library);
this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library);
this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library);
this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library);
this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library);
this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library);
this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library);
this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library);
this.grpcsharp_override_default_ssl_roots = GetMethodDelegate<Delegates.grpcsharp_override_default_ssl_roots_delegate>(library);
this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library);
this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library);
this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library);
this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library);
this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library);
this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library);
this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library);
this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library);
this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library);
this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library);
this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library);
this.grpcsharp_completion_queue_create_async = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_async_delegate>(library);
this.grpcsharp_completion_queue_create_sync = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_sync_delegate>(library);
this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library);
this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library);
this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library);
this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library);
this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library);
this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library);
this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library);
this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library);
this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library);
this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library);
this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library);
this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library);
this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library);
this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library);
this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library);
this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library);
this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library);
this.grpcsharp_server_register_completion_queue = GetMethodDelegate<Delegates.grpcsharp_server_register_completion_queue_delegate>(library);
this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library);
this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library);
this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library);
this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library);
this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library);
this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library);
this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library);
this.grpcsharp_call_auth_context = GetMethodDelegate<Delegates.grpcsharp_call_auth_context_delegate>(library);
this.grpcsharp_auth_context_peer_identity_property_name = GetMethodDelegate<Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate>(library);
this.grpcsharp_auth_context_property_iterator = GetMethodDelegate<Delegates.grpcsharp_auth_context_property_iterator_delegate>(library);
this.grpcsharp_auth_property_iterator_next = GetMethodDelegate<Delegates.grpcsharp_auth_property_iterator_next_delegate>(library);
this.grpcsharp_auth_context_release = GetMethodDelegate<Delegates.grpcsharp_auth_context_release_delegate>(library);
this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library);
this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library);
this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library);
this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library);
this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library);
this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library);
this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library);
this.grpcsharp_test_override_method = GetMethodDelegate<Delegates.grpcsharp_test_override_method_delegate>(library);
}
public NativeMethods(DllImportsFromStaticLib unusedInstance)
{
this.grpcsharp_init = DllImportsFromStaticLib.grpcsharp_init;
this.grpcsharp_shutdown = DllImportsFromStaticLib.grpcsharp_shutdown;
this.grpcsharp_version_string = DllImportsFromStaticLib.grpcsharp_version_string;
this.grpcsharp_batch_context_create = DllImportsFromStaticLib.grpcsharp_batch_context_create;
this.grpcsharp_batch_context_recv_initial_metadata = DllImportsFromStaticLib.grpcsharp_batch_context_recv_initial_metadata;
this.grpcsharp_batch_context_recv_message_length = DllImportsFromStaticLib.grpcsharp_batch_context_recv_message_length;
this.grpcsharp_batch_context_recv_message_to_buffer = DllImportsFromStaticLib.grpcsharp_batch_context_recv_message_to_buffer;
this.grpcsharp_batch_context_recv_status_on_client_status = DllImportsFromStaticLib.grpcsharp_batch_context_recv_status_on_client_status;
this.grpcsharp_batch_context_recv_status_on_client_details = DllImportsFromStaticLib.grpcsharp_batch_context_recv_status_on_client_details;
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = DllImportsFromStaticLib.grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
this.grpcsharp_batch_context_recv_close_on_server_cancelled = DllImportsFromStaticLib.grpcsharp_batch_context_recv_close_on_server_cancelled;
this.grpcsharp_batch_context_reset = DllImportsFromStaticLib.grpcsharp_batch_context_reset;
this.grpcsharp_batch_context_destroy = DllImportsFromStaticLib.grpcsharp_batch_context_destroy;
this.grpcsharp_request_call_context_create = DllImportsFromStaticLib.grpcsharp_request_call_context_create;
this.grpcsharp_request_call_context_call = DllImportsFromStaticLib.grpcsharp_request_call_context_call;
this.grpcsharp_request_call_context_method = DllImportsFromStaticLib.grpcsharp_request_call_context_method;
this.grpcsharp_request_call_context_host = DllImportsFromStaticLib.grpcsharp_request_call_context_host;
this.grpcsharp_request_call_context_deadline = DllImportsFromStaticLib.grpcsharp_request_call_context_deadline;
this.grpcsharp_request_call_context_request_metadata = DllImportsFromStaticLib.grpcsharp_request_call_context_request_metadata;
this.grpcsharp_request_call_context_reset = DllImportsFromStaticLib.grpcsharp_request_call_context_reset;
this.grpcsharp_request_call_context_destroy = DllImportsFromStaticLib.grpcsharp_request_call_context_destroy;
this.grpcsharp_composite_call_credentials_create = DllImportsFromStaticLib.grpcsharp_composite_call_credentials_create;
this.grpcsharp_call_credentials_release = DllImportsFromStaticLib.grpcsharp_call_credentials_release;
this.grpcsharp_call_cancel = DllImportsFromStaticLib.grpcsharp_call_cancel;
this.grpcsharp_call_cancel_with_status = DllImportsFromStaticLib.grpcsharp_call_cancel_with_status;
this.grpcsharp_call_start_unary = DllImportsFromStaticLib.grpcsharp_call_start_unary;
this.grpcsharp_call_start_client_streaming = DllImportsFromStaticLib.grpcsharp_call_start_client_streaming;
this.grpcsharp_call_start_server_streaming = DllImportsFromStaticLib.grpcsharp_call_start_server_streaming;
this.grpcsharp_call_start_duplex_streaming = DllImportsFromStaticLib.grpcsharp_call_start_duplex_streaming;
this.grpcsharp_call_send_message = DllImportsFromStaticLib.grpcsharp_call_send_message;
this.grpcsharp_call_send_close_from_client = DllImportsFromStaticLib.grpcsharp_call_send_close_from_client;
this.grpcsharp_call_send_status_from_server = DllImportsFromStaticLib.grpcsharp_call_send_status_from_server;
this.grpcsharp_call_recv_message = DllImportsFromStaticLib.grpcsharp_call_recv_message;
this.grpcsharp_call_recv_initial_metadata = DllImportsFromStaticLib.grpcsharp_call_recv_initial_metadata;
this.grpcsharp_call_start_serverside = DllImportsFromStaticLib.grpcsharp_call_start_serverside;
this.grpcsharp_call_send_initial_metadata = DllImportsFromStaticLib.grpcsharp_call_send_initial_metadata;
this.grpcsharp_call_set_credentials = DllImportsFromStaticLib.grpcsharp_call_set_credentials;
this.grpcsharp_call_get_peer = DllImportsFromStaticLib.grpcsharp_call_get_peer;
this.grpcsharp_call_destroy = DllImportsFromStaticLib.grpcsharp_call_destroy;
this.grpcsharp_channel_args_create = DllImportsFromStaticLib.grpcsharp_channel_args_create;
this.grpcsharp_channel_args_set_string = DllImportsFromStaticLib.grpcsharp_channel_args_set_string;
this.grpcsharp_channel_args_set_integer = DllImportsFromStaticLib.grpcsharp_channel_args_set_integer;
this.grpcsharp_channel_args_destroy = DllImportsFromStaticLib.grpcsharp_channel_args_destroy;
this.grpcsharp_override_default_ssl_roots = DllImportsFromStaticLib.grpcsharp_override_default_ssl_roots;
this.grpcsharp_ssl_credentials_create = DllImportsFromStaticLib.grpcsharp_ssl_credentials_create;
this.grpcsharp_composite_channel_credentials_create = DllImportsFromStaticLib.grpcsharp_composite_channel_credentials_create;
this.grpcsharp_channel_credentials_release = DllImportsFromStaticLib.grpcsharp_channel_credentials_release;
this.grpcsharp_insecure_channel_create = DllImportsFromStaticLib.grpcsharp_insecure_channel_create;
this.grpcsharp_secure_channel_create = DllImportsFromStaticLib.grpcsharp_secure_channel_create;
this.grpcsharp_channel_create_call = DllImportsFromStaticLib.grpcsharp_channel_create_call;
this.grpcsharp_channel_check_connectivity_state = DllImportsFromStaticLib.grpcsharp_channel_check_connectivity_state;
this.grpcsharp_channel_watch_connectivity_state = DllImportsFromStaticLib.grpcsharp_channel_watch_connectivity_state;
this.grpcsharp_channel_get_target = DllImportsFromStaticLib.grpcsharp_channel_get_target;
this.grpcsharp_channel_destroy = DllImportsFromStaticLib.grpcsharp_channel_destroy;
this.grpcsharp_sizeof_grpc_event = DllImportsFromStaticLib.grpcsharp_sizeof_grpc_event;
this.grpcsharp_completion_queue_create_async = DllImportsFromStaticLib.grpcsharp_completion_queue_create_async;
this.grpcsharp_completion_queue_create_sync = DllImportsFromStaticLib.grpcsharp_completion_queue_create_sync;
this.grpcsharp_completion_queue_shutdown = DllImportsFromStaticLib.grpcsharp_completion_queue_shutdown;
this.grpcsharp_completion_queue_next = DllImportsFromStaticLib.grpcsharp_completion_queue_next;
this.grpcsharp_completion_queue_pluck = DllImportsFromStaticLib.grpcsharp_completion_queue_pluck;
this.grpcsharp_completion_queue_destroy = DllImportsFromStaticLib.grpcsharp_completion_queue_destroy;
this.gprsharp_free = DllImportsFromStaticLib.gprsharp_free;
this.grpcsharp_metadata_array_create = DllImportsFromStaticLib.grpcsharp_metadata_array_create;
this.grpcsharp_metadata_array_add = DllImportsFromStaticLib.grpcsharp_metadata_array_add;
this.grpcsharp_metadata_array_count = DllImportsFromStaticLib.grpcsharp_metadata_array_count;
this.grpcsharp_metadata_array_get_key = DllImportsFromStaticLib.grpcsharp_metadata_array_get_key;
this.grpcsharp_metadata_array_get_value = DllImportsFromStaticLib.grpcsharp_metadata_array_get_value;
this.grpcsharp_metadata_array_destroy_full = DllImportsFromStaticLib.grpcsharp_metadata_array_destroy_full;
this.grpcsharp_redirect_log = DllImportsFromStaticLib.grpcsharp_redirect_log;
this.grpcsharp_metadata_credentials_create_from_plugin = DllImportsFromStaticLib.grpcsharp_metadata_credentials_create_from_plugin;
this.grpcsharp_metadata_credentials_notify_from_plugin = DllImportsFromStaticLib.grpcsharp_metadata_credentials_notify_from_plugin;
this.grpcsharp_ssl_server_credentials_create = DllImportsFromStaticLib.grpcsharp_ssl_server_credentials_create;
this.grpcsharp_server_credentials_release = DllImportsFromStaticLib.grpcsharp_server_credentials_release;
this.grpcsharp_server_create = DllImportsFromStaticLib.grpcsharp_server_create;
this.grpcsharp_server_register_completion_queue = DllImportsFromStaticLib.grpcsharp_server_register_completion_queue;
this.grpcsharp_server_add_insecure_http2_port = DllImportsFromStaticLib.grpcsharp_server_add_insecure_http2_port;
this.grpcsharp_server_add_secure_http2_port = DllImportsFromStaticLib.grpcsharp_server_add_secure_http2_port;
this.grpcsharp_server_start = DllImportsFromStaticLib.grpcsharp_server_start;
this.grpcsharp_server_request_call = DllImportsFromStaticLib.grpcsharp_server_request_call;
this.grpcsharp_server_cancel_all_calls = DllImportsFromStaticLib.grpcsharp_server_cancel_all_calls;
this.grpcsharp_server_shutdown_and_notify_callback = DllImportsFromStaticLib.grpcsharp_server_shutdown_and_notify_callback;
this.grpcsharp_server_destroy = DllImportsFromStaticLib.grpcsharp_server_destroy;
this.grpcsharp_call_auth_context = DllImportsFromStaticLib.grpcsharp_call_auth_context;
this.grpcsharp_auth_context_peer_identity_property_name = DllImportsFromStaticLib.grpcsharp_auth_context_peer_identity_property_name;
this.grpcsharp_auth_context_property_iterator = DllImportsFromStaticLib.grpcsharp_auth_context_property_iterator;
this.grpcsharp_auth_property_iterator_next = DllImportsFromStaticLib.grpcsharp_auth_property_iterator_next;
this.grpcsharp_auth_context_release = DllImportsFromStaticLib.grpcsharp_auth_context_release;
this.gprsharp_now = DllImportsFromStaticLib.gprsharp_now;
this.gprsharp_inf_future = DllImportsFromStaticLib.gprsharp_inf_future;
this.gprsharp_inf_past = DllImportsFromStaticLib.gprsharp_inf_past;
this.gprsharp_convert_clock_type = DllImportsFromStaticLib.gprsharp_convert_clock_type;
this.gprsharp_sizeof_timespec = DllImportsFromStaticLib.gprsharp_sizeof_timespec;
this.grpcsharp_test_callback = DllImportsFromStaticLib.grpcsharp_test_callback;
this.grpcsharp_test_nop = DllImportsFromStaticLib.grpcsharp_test_nop;
this.grpcsharp_test_override_method = DllImportsFromStaticLib.grpcsharp_test_override_method;
}
public NativeMethods(DllImportsFromSharedLib unusedInstance)
{
this.grpcsharp_init = DllImportsFromSharedLib.grpcsharp_init;
this.grpcsharp_shutdown = DllImportsFromSharedLib.grpcsharp_shutdown;
this.grpcsharp_version_string = DllImportsFromSharedLib.grpcsharp_version_string;
this.grpcsharp_batch_context_create = DllImportsFromSharedLib.grpcsharp_batch_context_create;
this.grpcsharp_batch_context_recv_initial_metadata = DllImportsFromSharedLib.grpcsharp_batch_context_recv_initial_metadata;
this.grpcsharp_batch_context_recv_message_length = DllImportsFromSharedLib.grpcsharp_batch_context_recv_message_length;
this.grpcsharp_batch_context_recv_message_to_buffer = DllImportsFromSharedLib.grpcsharp_batch_context_recv_message_to_buffer;
this.grpcsharp_batch_context_recv_status_on_client_status = DllImportsFromSharedLib.grpcsharp_batch_context_recv_status_on_client_status;
this.grpcsharp_batch_context_recv_status_on_client_details = DllImportsFromSharedLib.grpcsharp_batch_context_recv_status_on_client_details;
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = DllImportsFromSharedLib.grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
this.grpcsharp_batch_context_recv_close_on_server_cancelled = DllImportsFromSharedLib.grpcsharp_batch_context_recv_close_on_server_cancelled;
this.grpcsharp_batch_context_reset = DllImportsFromSharedLib.grpcsharp_batch_context_reset;
this.grpcsharp_batch_context_destroy = DllImportsFromSharedLib.grpcsharp_batch_context_destroy;
this.grpcsharp_request_call_context_create = DllImportsFromSharedLib.grpcsharp_request_call_context_create;
this.grpcsharp_request_call_context_call = DllImportsFromSharedLib.grpcsharp_request_call_context_call;
this.grpcsharp_request_call_context_method = DllImportsFromSharedLib.grpcsharp_request_call_context_method;
this.grpcsharp_request_call_context_host = DllImportsFromSharedLib.grpcsharp_request_call_context_host;
this.grpcsharp_request_call_context_deadline = DllImportsFromSharedLib.grpcsharp_request_call_context_deadline;
this.grpcsharp_request_call_context_request_metadata = DllImportsFromSharedLib.grpcsharp_request_call_context_request_metadata;
this.grpcsharp_request_call_context_reset = DllImportsFromSharedLib.grpcsharp_request_call_context_reset;
this.grpcsharp_request_call_context_destroy = DllImportsFromSharedLib.grpcsharp_request_call_context_destroy;
this.grpcsharp_composite_call_credentials_create = DllImportsFromSharedLib.grpcsharp_composite_call_credentials_create;
this.grpcsharp_call_credentials_release = DllImportsFromSharedLib.grpcsharp_call_credentials_release;
this.grpcsharp_call_cancel = DllImportsFromSharedLib.grpcsharp_call_cancel;
this.grpcsharp_call_cancel_with_status = DllImportsFromSharedLib.grpcsharp_call_cancel_with_status;
this.grpcsharp_call_start_unary = DllImportsFromSharedLib.grpcsharp_call_start_unary;
this.grpcsharp_call_start_client_streaming = DllImportsFromSharedLib.grpcsharp_call_start_client_streaming;
this.grpcsharp_call_start_server_streaming = DllImportsFromSharedLib.grpcsharp_call_start_server_streaming;
this.grpcsharp_call_start_duplex_streaming = DllImportsFromSharedLib.grpcsharp_call_start_duplex_streaming;
this.grpcsharp_call_send_message = DllImportsFromSharedLib.grpcsharp_call_send_message;
this.grpcsharp_call_send_close_from_client = DllImportsFromSharedLib.grpcsharp_call_send_close_from_client;
this.grpcsharp_call_send_status_from_server = DllImportsFromSharedLib.grpcsharp_call_send_status_from_server;
this.grpcsharp_call_recv_message = DllImportsFromSharedLib.grpcsharp_call_recv_message;
this.grpcsharp_call_recv_initial_metadata = DllImportsFromSharedLib.grpcsharp_call_recv_initial_metadata;
this.grpcsharp_call_start_serverside = DllImportsFromSharedLib.grpcsharp_call_start_serverside;
this.grpcsharp_call_send_initial_metadata = DllImportsFromSharedLib.grpcsharp_call_send_initial_metadata;
this.grpcsharp_call_set_credentials = DllImportsFromSharedLib.grpcsharp_call_set_credentials;
this.grpcsharp_call_get_peer = DllImportsFromSharedLib.grpcsharp_call_get_peer;
this.grpcsharp_call_destroy = DllImportsFromSharedLib.grpcsharp_call_destroy;
this.grpcsharp_channel_args_create = DllImportsFromSharedLib.grpcsharp_channel_args_create;
this.grpcsharp_channel_args_set_string = DllImportsFromSharedLib.grpcsharp_channel_args_set_string;
this.grpcsharp_channel_args_set_integer = DllImportsFromSharedLib.grpcsharp_channel_args_set_integer;
this.grpcsharp_channel_args_destroy = DllImportsFromSharedLib.grpcsharp_channel_args_destroy;
this.grpcsharp_override_default_ssl_roots = DllImportsFromSharedLib.grpcsharp_override_default_ssl_roots;
this.grpcsharp_ssl_credentials_create = DllImportsFromSharedLib.grpcsharp_ssl_credentials_create;
this.grpcsharp_composite_channel_credentials_create = DllImportsFromSharedLib.grpcsharp_composite_channel_credentials_create;
this.grpcsharp_channel_credentials_release = DllImportsFromSharedLib.grpcsharp_channel_credentials_release;
this.grpcsharp_insecure_channel_create = DllImportsFromSharedLib.grpcsharp_insecure_channel_create;
this.grpcsharp_secure_channel_create = DllImportsFromSharedLib.grpcsharp_secure_channel_create;
this.grpcsharp_channel_create_call = DllImportsFromSharedLib.grpcsharp_channel_create_call;
this.grpcsharp_channel_check_connectivity_state = DllImportsFromSharedLib.grpcsharp_channel_check_connectivity_state;
this.grpcsharp_channel_watch_connectivity_state = DllImportsFromSharedLib.grpcsharp_channel_watch_connectivity_state;
this.grpcsharp_channel_get_target = DllImportsFromSharedLib.grpcsharp_channel_get_target;
this.grpcsharp_channel_destroy = DllImportsFromSharedLib.grpcsharp_channel_destroy;
this.grpcsharp_sizeof_grpc_event = DllImportsFromSharedLib.grpcsharp_sizeof_grpc_event;
this.grpcsharp_completion_queue_create_async = DllImportsFromSharedLib.grpcsharp_completion_queue_create_async;
this.grpcsharp_completion_queue_create_sync = DllImportsFromSharedLib.grpcsharp_completion_queue_create_sync;
this.grpcsharp_completion_queue_shutdown = DllImportsFromSharedLib.grpcsharp_completion_queue_shutdown;
this.grpcsharp_completion_queue_next = DllImportsFromSharedLib.grpcsharp_completion_queue_next;
this.grpcsharp_completion_queue_pluck = DllImportsFromSharedLib.grpcsharp_completion_queue_pluck;
this.grpcsharp_completion_queue_destroy = DllImportsFromSharedLib.grpcsharp_completion_queue_destroy;
this.gprsharp_free = DllImportsFromSharedLib.gprsharp_free;
this.grpcsharp_metadata_array_create = DllImportsFromSharedLib.grpcsharp_metadata_array_create;
this.grpcsharp_metadata_array_add = DllImportsFromSharedLib.grpcsharp_metadata_array_add;
this.grpcsharp_metadata_array_count = DllImportsFromSharedLib.grpcsharp_metadata_array_count;
this.grpcsharp_metadata_array_get_key = DllImportsFromSharedLib.grpcsharp_metadata_array_get_key;
this.grpcsharp_metadata_array_get_value = DllImportsFromSharedLib.grpcsharp_metadata_array_get_value;
this.grpcsharp_metadata_array_destroy_full = DllImportsFromSharedLib.grpcsharp_metadata_array_destroy_full;
this.grpcsharp_redirect_log = DllImportsFromSharedLib.grpcsharp_redirect_log;
this.grpcsharp_metadata_credentials_create_from_plugin = DllImportsFromSharedLib.grpcsharp_metadata_credentials_create_from_plugin;
this.grpcsharp_metadata_credentials_notify_from_plugin = DllImportsFromSharedLib.grpcsharp_metadata_credentials_notify_from_plugin;
this.grpcsharp_ssl_server_credentials_create = DllImportsFromSharedLib.grpcsharp_ssl_server_credentials_create;
this.grpcsharp_server_credentials_release = DllImportsFromSharedLib.grpcsharp_server_credentials_release;
this.grpcsharp_server_create = DllImportsFromSharedLib.grpcsharp_server_create;
this.grpcsharp_server_register_completion_queue = DllImportsFromSharedLib.grpcsharp_server_register_completion_queue;
this.grpcsharp_server_add_insecure_http2_port = DllImportsFromSharedLib.grpcsharp_server_add_insecure_http2_port;
this.grpcsharp_server_add_secure_http2_port = DllImportsFromSharedLib.grpcsharp_server_add_secure_http2_port;
this.grpcsharp_server_start = DllImportsFromSharedLib.grpcsharp_server_start;
this.grpcsharp_server_request_call = DllImportsFromSharedLib.grpcsharp_server_request_call;
this.grpcsharp_server_cancel_all_calls = DllImportsFromSharedLib.grpcsharp_server_cancel_all_calls;
this.grpcsharp_server_shutdown_and_notify_callback = DllImportsFromSharedLib.grpcsharp_server_shutdown_and_notify_callback;
this.grpcsharp_server_destroy = DllImportsFromSharedLib.grpcsharp_server_destroy;
this.grpcsharp_call_auth_context = DllImportsFromSharedLib.grpcsharp_call_auth_context;
this.grpcsharp_auth_context_peer_identity_property_name = DllImportsFromSharedLib.grpcsharp_auth_context_peer_identity_property_name;
this.grpcsharp_auth_context_property_iterator = DllImportsFromSharedLib.grpcsharp_auth_context_property_iterator;
this.grpcsharp_auth_property_iterator_next = DllImportsFromSharedLib.grpcsharp_auth_property_iterator_next;
this.grpcsharp_auth_context_release = DllImportsFromSharedLib.grpcsharp_auth_context_release;
this.gprsharp_now = DllImportsFromSharedLib.gprsharp_now;
this.gprsharp_inf_future = DllImportsFromSharedLib.gprsharp_inf_future;
this.gprsharp_inf_past = DllImportsFromSharedLib.gprsharp_inf_past;
this.gprsharp_convert_clock_type = DllImportsFromSharedLib.gprsharp_convert_clock_type;
this.gprsharp_sizeof_timespec = DllImportsFromSharedLib.gprsharp_sizeof_timespec;
this.grpcsharp_test_callback = DllImportsFromSharedLib.grpcsharp_test_callback;
this.grpcsharp_test_nop = DllImportsFromSharedLib.grpcsharp_test_nop;
this.grpcsharp_test_override_method = DllImportsFromSharedLib.grpcsharp_test_override_method;
}
/// <summary>
/// Delegate types for all published native methods. Declared under inner class to prevent scope pollution.
/// </summary>
public class Delegates
{
public delegate void grpcsharp_init_delegate();
public delegate void grpcsharp_shutdown_delegate();
public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char*
public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate();
public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx, out UIntPtr detailsLength);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx);
public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_reset_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx);
public delegate RequestCallContextSafeHandle grpcsharp_request_call_context_create_delegate();
public delegate CallSafeHandle grpcsharp_request_call_context_call_delegate(RequestCallContextSafeHandle ctx);
public delegate IntPtr grpcsharp_request_call_context_method_delegate(RequestCallContextSafeHandle ctx, out UIntPtr methodLength);
public delegate IntPtr grpcsharp_request_call_context_host_delegate(RequestCallContextSafeHandle ctx, out UIntPtr hostLength);
public delegate Timespec grpcsharp_request_call_context_deadline_delegate(RequestCallContextSafeHandle ctx);
public delegate IntPtr grpcsharp_request_call_context_request_metadata_delegate(RequestCallContextSafeHandle ctx);
public delegate void grpcsharp_request_call_context_reset_delegate(RequestCallContextSafeHandle ctx);
public delegate void grpcsharp_request_call_context_destroy_delegate(IntPtr ctx);
public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials);
public delegate CallError grpcsharp_call_cancel_delegate(CallSafeHandle call);
public delegate CallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description);
public delegate CallError grpcsharp_call_start_unary_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_send_message_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, int sendEmptyInitialMetadata);
public delegate CallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call, BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, byte[] statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, int sendEmptyInitialMetadata, byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
public delegate CallError grpcsharp_call_recv_message_delegate(CallSafeHandle call, BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call, BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call, BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate CallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials);
public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call);
public delegate void grpcsharp_call_destroy_delegate(IntPtr call);
public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs);
public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args);
public delegate void grpcsharp_override_default_ssl_roots_delegate(string pemRootCerts);
public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials);
public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs);
public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect);
public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState, Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call);
public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel);
public delegate int grpcsharp_sizeof_grpc_event_delegate();
public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_async_delegate();
public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_sync_delegate();
public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag);
public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq);
public delegate void gprsharp_free_delegate(IntPtr ptr);
public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity);
public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray);
public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr keyLength);
public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr valueLength);
public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array);
public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback);
public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor);
public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, SslClientCertificateRequestType clientCertificateRequest);
public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials);
public delegate ServerSafeHandle grpcsharp_server_create_delegate(ChannelArgsSafeHandle args);
public delegate void grpcsharp_server_register_completion_queue_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq);
public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr);
public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server);
public delegate CallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, RequestCallContextSafeHandle ctx);
public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server);
public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_destroy_delegate(IntPtr server);
public delegate AuthContextSafeHandle grpcsharp_call_auth_context_delegate(CallSafeHandle call);
public delegate IntPtr grpcsharp_auth_context_peer_identity_property_name_delegate(AuthContextSafeHandle authContext); // returns const char*
public delegate AuthContextSafeHandle.NativeAuthPropertyIterator grpcsharp_auth_context_property_iterator_delegate(AuthContextSafeHandle authContext);
public delegate IntPtr grpcsharp_auth_property_iterator_next_delegate(ref AuthContextSafeHandle.NativeAuthPropertyIterator iterator); // returns const auth_property*
public delegate void grpcsharp_auth_context_release_delegate(IntPtr authContext);
public delegate Timespec gprsharp_now_delegate(ClockType clockType);
public delegate Timespec gprsharp_inf_future_delegate(ClockType clockType);
public delegate Timespec gprsharp_inf_past_delegate(ClockType clockType);
public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, ClockType targetClock);
public delegate int gprsharp_sizeof_timespec_delegate();
public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] NativeCallbackTestDelegate callback);
public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr);
public delegate void grpcsharp_test_override_method_delegate(string methodName, string variant);
}
/// <summary>
/// grpc_csharp_ext used as a static library (e.g Unity iOS).
/// </summary>
internal class DllImportsFromStaticLib
{
private const string ImportName = "__Internal";
[DllImport(ImportName)]
public static extern void grpcsharp_init();
[DllImport(ImportName)]
public static extern void grpcsharp_shutdown();
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_version_string();
[DllImport(ImportName)]
public static extern BatchContextSafeHandle grpcsharp_batch_context_create();
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_batch_context_recv_initial_metadata(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_batch_context_recv_message_length(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_batch_context_recv_message_to_buffer(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
[DllImport(ImportName)]
public static extern StatusCode grpcsharp_batch_context_recv_status_on_client_status(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_details(BatchContextSafeHandle ctx, out UIntPtr detailsLength);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern int grpcsharp_batch_context_recv_close_on_server_cancelled(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_batch_context_reset(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_batch_context_destroy(IntPtr ctx);
[DllImport(ImportName)]
public static extern RequestCallContextSafeHandle grpcsharp_request_call_context_create();
[DllImport(ImportName)]
public static extern CallSafeHandle grpcsharp_request_call_context_call(RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_request_call_context_method(RequestCallContextSafeHandle ctx, out UIntPtr methodLength);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_request_call_context_host(RequestCallContextSafeHandle ctx, out UIntPtr hostLength);
[DllImport(ImportName)]
public static extern Timespec grpcsharp_request_call_context_deadline(RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_request_call_context_request_metadata(RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_request_call_context_reset(RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_request_call_context_destroy(IntPtr ctx);
[DllImport(ImportName)]
public static extern CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
[DllImport(ImportName)]
public static extern void grpcsharp_call_credentials_release(IntPtr credentials);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_cancel(CallSafeHandle call);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_unary(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_client_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_server_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_send_message(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, int sendEmptyInitialMetadata);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_send_close_from_client(CallSafeHandle call, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_send_status_from_server(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, byte[] statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, int sendEmptyInitialMetadata, byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_recv_message(CallSafeHandle call, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_recv_initial_metadata(CallSafeHandle call, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_serverside(CallSafeHandle call, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_send_initial_metadata(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_set_credentials(CallSafeHandle call, CallCredentialsSafeHandle credentials);
[DllImport(ImportName)]
public static extern CStringSafeHandle grpcsharp_call_get_peer(CallSafeHandle call);
[DllImport(ImportName)]
public static extern void grpcsharp_call_destroy(IntPtr call);
[DllImport(ImportName)]
public static extern ChannelArgsSafeHandle grpcsharp_channel_args_create(UIntPtr numArgs);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_args_set_string(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_args_set_integer(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_args_destroy(IntPtr args);
[DllImport(ImportName)]
public static extern void grpcsharp_override_default_ssl_roots(string pemRootCerts);
[DllImport(ImportName)]
public static extern ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
[DllImport(ImportName)]
public static extern ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_credentials_release(IntPtr credentials);
[DllImport(ImportName)]
public static extern ChannelSafeHandle grpcsharp_insecure_channel_create(string target, ChannelArgsSafeHandle channelArgs);
[DllImport(ImportName)]
public static extern ChannelSafeHandle grpcsharp_secure_channel_create(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
[DllImport(ImportName)]
public static extern CallSafeHandle grpcsharp_channel_create_call(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
[DllImport(ImportName)]
public static extern ChannelState grpcsharp_channel_check_connectivity_state(ChannelSafeHandle channel, int tryToConnect);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_watch_connectivity_state(ChannelSafeHandle channel, ChannelState lastObservedState, Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CStringSafeHandle grpcsharp_channel_get_target(ChannelSafeHandle call);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_destroy(IntPtr channel);
[DllImport(ImportName)]
public static extern int grpcsharp_sizeof_grpc_event();
[DllImport(ImportName)]
public static extern CompletionQueueSafeHandle grpcsharp_completion_queue_create_async();
[DllImport(ImportName)]
public static extern CompletionQueueSafeHandle grpcsharp_completion_queue_create_sync();
[DllImport(ImportName)]
public static extern void grpcsharp_completion_queue_shutdown(CompletionQueueSafeHandle cq);
[DllImport(ImportName)]
public static extern CompletionQueueEvent grpcsharp_completion_queue_next(CompletionQueueSafeHandle cq);
[DllImport(ImportName)]
public static extern CompletionQueueEvent grpcsharp_completion_queue_pluck(CompletionQueueSafeHandle cq, IntPtr tag);
[DllImport(ImportName)]
public static extern void grpcsharp_completion_queue_destroy(IntPtr cq);
[DllImport(ImportName)]
public static extern void gprsharp_free(IntPtr ptr);
[DllImport(ImportName)]
public static extern MetadataArraySafeHandle grpcsharp_metadata_array_create(UIntPtr capacity);
[DllImport(ImportName)]
public static extern void grpcsharp_metadata_array_add(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
[DllImport(ImportName)]
public static extern UIntPtr grpcsharp_metadata_array_count(IntPtr metadataArray);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_metadata_array_get_key(IntPtr metadataArray, UIntPtr index, out UIntPtr keyLength);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_metadata_array_get_value(IntPtr metadataArray, UIntPtr index, out UIntPtr valueLength);
[DllImport(ImportName)]
public static extern void grpcsharp_metadata_array_destroy_full(IntPtr array);
[DllImport(ImportName)]
public static extern void grpcsharp_redirect_log(GprLogDelegate callback);
[DllImport(ImportName)]
public static extern CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin(NativeMetadataInterceptor interceptor);
[DllImport(ImportName)]
public static extern void grpcsharp_metadata_credentials_notify_from_plugin(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
[DllImport(ImportName)]
public static extern ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, SslClientCertificateRequestType clientCertificateRequest);
[DllImport(ImportName)]
public static extern void grpcsharp_server_credentials_release(IntPtr credentials);
[DllImport(ImportName)]
public static extern ServerSafeHandle grpcsharp_server_create(ChannelArgsSafeHandle args);
[DllImport(ImportName)]
public static extern void grpcsharp_server_register_completion_queue(ServerSafeHandle server, CompletionQueueSafeHandle cq);
[DllImport(ImportName)]
public static extern int grpcsharp_server_add_insecure_http2_port(ServerSafeHandle server, string addr);
[DllImport(ImportName)]
public static extern int grpcsharp_server_add_secure_http2_port(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
[DllImport(ImportName)]
public static extern void grpcsharp_server_start(ServerSafeHandle server);
[DllImport(ImportName)]
public static extern CallError grpcsharp_server_request_call(ServerSafeHandle server, CompletionQueueSafeHandle cq, RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_server_cancel_all_calls(ServerSafeHandle server);
[DllImport(ImportName)]
public static extern void grpcsharp_server_shutdown_and_notify_callback(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_server_destroy(IntPtr server);
[DllImport(ImportName)]
public static extern AuthContextSafeHandle grpcsharp_call_auth_context(CallSafeHandle call);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_auth_context_peer_identity_property_name(AuthContextSafeHandle authContext);
[DllImport(ImportName)]
public static extern AuthContextSafeHandle.NativeAuthPropertyIterator grpcsharp_auth_context_property_iterator(AuthContextSafeHandle authContext);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_auth_property_iterator_next(ref AuthContextSafeHandle.NativeAuthPropertyIterator iterator);
[DllImport(ImportName)]
public static extern void grpcsharp_auth_context_release(IntPtr authContext);
[DllImport(ImportName)]
public static extern Timespec gprsharp_now(ClockType clockType);
[DllImport(ImportName)]
public static extern Timespec gprsharp_inf_future(ClockType clockType);
[DllImport(ImportName)]
public static extern Timespec gprsharp_inf_past(ClockType clockType);
[DllImport(ImportName)]
public static extern Timespec gprsharp_convert_clock_type(Timespec t, ClockType targetClock);
[DllImport(ImportName)]
public static extern int gprsharp_sizeof_timespec();
[DllImport(ImportName)]
public static extern CallError grpcsharp_test_callback([MarshalAs(UnmanagedType.FunctionPtr)] NativeCallbackTestDelegate callback);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_test_nop(IntPtr ptr);
[DllImport(ImportName)]
public static extern void grpcsharp_test_override_method(string methodName, string variant);
}
/// <summary>
/// grpc_csharp_ext used a shared library (e.g on Unity Standalone and Android).
/// </summary>
internal class DllImportsFromSharedLib
{
private const string ImportName = "grpc_csharp_ext";
[DllImport(ImportName)]
public static extern void grpcsharp_init();
[DllImport(ImportName)]
public static extern void grpcsharp_shutdown();
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_version_string();
[DllImport(ImportName)]
public static extern BatchContextSafeHandle grpcsharp_batch_context_create();
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_batch_context_recv_initial_metadata(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_batch_context_recv_message_length(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_batch_context_recv_message_to_buffer(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
[DllImport(ImportName)]
public static extern StatusCode grpcsharp_batch_context_recv_status_on_client_status(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_details(BatchContextSafeHandle ctx, out UIntPtr detailsLength);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern int grpcsharp_batch_context_recv_close_on_server_cancelled(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_batch_context_reset(BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_batch_context_destroy(IntPtr ctx);
[DllImport(ImportName)]
public static extern RequestCallContextSafeHandle grpcsharp_request_call_context_create();
[DllImport(ImportName)]
public static extern CallSafeHandle grpcsharp_request_call_context_call(RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_request_call_context_method(RequestCallContextSafeHandle ctx, out UIntPtr methodLength);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_request_call_context_host(RequestCallContextSafeHandle ctx, out UIntPtr hostLength);
[DllImport(ImportName)]
public static extern Timespec grpcsharp_request_call_context_deadline(RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_request_call_context_request_metadata(RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_request_call_context_reset(RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_request_call_context_destroy(IntPtr ctx);
[DllImport(ImportName)]
public static extern CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
[DllImport(ImportName)]
public static extern void grpcsharp_call_credentials_release(IntPtr credentials);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_cancel(CallSafeHandle call);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_unary(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_client_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_server_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_send_message(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, int sendEmptyInitialMetadata);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_send_close_from_client(CallSafeHandle call, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_send_status_from_server(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, byte[] statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, int sendEmptyInitialMetadata, byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_recv_message(CallSafeHandle call, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_recv_initial_metadata(CallSafeHandle call, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_start_serverside(CallSafeHandle call, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_send_initial_metadata(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport(ImportName)]
public static extern CallError grpcsharp_call_set_credentials(CallSafeHandle call, CallCredentialsSafeHandle credentials);
[DllImport(ImportName)]
public static extern CStringSafeHandle grpcsharp_call_get_peer(CallSafeHandle call);
[DllImport(ImportName)]
public static extern void grpcsharp_call_destroy(IntPtr call);
[DllImport(ImportName)]
public static extern ChannelArgsSafeHandle grpcsharp_channel_args_create(UIntPtr numArgs);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_args_set_string(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_args_set_integer(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_args_destroy(IntPtr args);
[DllImport(ImportName)]
public static extern void grpcsharp_override_default_ssl_roots(string pemRootCerts);
[DllImport(ImportName)]
public static extern ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
[DllImport(ImportName)]
public static extern ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_credentials_release(IntPtr credentials);
[DllImport(ImportName)]
public static extern ChannelSafeHandle grpcsharp_insecure_channel_create(string target, ChannelArgsSafeHandle channelArgs);
[DllImport(ImportName)]
public static extern ChannelSafeHandle grpcsharp_secure_channel_create(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
[DllImport(ImportName)]
public static extern CallSafeHandle grpcsharp_channel_create_call(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
[DllImport(ImportName)]
public static extern ChannelState grpcsharp_channel_check_connectivity_state(ChannelSafeHandle channel, int tryToConnect);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_watch_connectivity_state(ChannelSafeHandle channel, ChannelState lastObservedState, Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern CStringSafeHandle grpcsharp_channel_get_target(ChannelSafeHandle call);
[DllImport(ImportName)]
public static extern void grpcsharp_channel_destroy(IntPtr channel);
[DllImport(ImportName)]
public static extern int grpcsharp_sizeof_grpc_event();
[DllImport(ImportName)]
public static extern CompletionQueueSafeHandle grpcsharp_completion_queue_create_async();
[DllImport(ImportName)]
public static extern CompletionQueueSafeHandle grpcsharp_completion_queue_create_sync();
[DllImport(ImportName)]
public static extern void grpcsharp_completion_queue_shutdown(CompletionQueueSafeHandle cq);
[DllImport(ImportName)]
public static extern CompletionQueueEvent grpcsharp_completion_queue_next(CompletionQueueSafeHandle cq);
[DllImport(ImportName)]
public static extern CompletionQueueEvent grpcsharp_completion_queue_pluck(CompletionQueueSafeHandle cq, IntPtr tag);
[DllImport(ImportName)]
public static extern void grpcsharp_completion_queue_destroy(IntPtr cq);
[DllImport(ImportName)]
public static extern void gprsharp_free(IntPtr ptr);
[DllImport(ImportName)]
public static extern MetadataArraySafeHandle grpcsharp_metadata_array_create(UIntPtr capacity);
[DllImport(ImportName)]
public static extern void grpcsharp_metadata_array_add(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
[DllImport(ImportName)]
public static extern UIntPtr grpcsharp_metadata_array_count(IntPtr metadataArray);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_metadata_array_get_key(IntPtr metadataArray, UIntPtr index, out UIntPtr keyLength);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_metadata_array_get_value(IntPtr metadataArray, UIntPtr index, out UIntPtr valueLength);
[DllImport(ImportName)]
public static extern void grpcsharp_metadata_array_destroy_full(IntPtr array);
[DllImport(ImportName)]
public static extern void grpcsharp_redirect_log(GprLogDelegate callback);
[DllImport(ImportName)]
public static extern CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin(NativeMetadataInterceptor interceptor);
[DllImport(ImportName)]
public static extern void grpcsharp_metadata_credentials_notify_from_plugin(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
[DllImport(ImportName)]
public static extern ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, SslClientCertificateRequestType clientCertificateRequest);
[DllImport(ImportName)]
public static extern void grpcsharp_server_credentials_release(IntPtr credentials);
[DllImport(ImportName)]
public static extern ServerSafeHandle grpcsharp_server_create(ChannelArgsSafeHandle args);
[DllImport(ImportName)]
public static extern void grpcsharp_server_register_completion_queue(ServerSafeHandle server, CompletionQueueSafeHandle cq);
[DllImport(ImportName)]
public static extern int grpcsharp_server_add_insecure_http2_port(ServerSafeHandle server, string addr);
[DllImport(ImportName)]
public static extern int grpcsharp_server_add_secure_http2_port(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
[DllImport(ImportName)]
public static extern void grpcsharp_server_start(ServerSafeHandle server);
[DllImport(ImportName)]
public static extern CallError grpcsharp_server_request_call(ServerSafeHandle server, CompletionQueueSafeHandle cq, RequestCallContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_server_cancel_all_calls(ServerSafeHandle server);
[DllImport(ImportName)]
public static extern void grpcsharp_server_shutdown_and_notify_callback(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport(ImportName)]
public static extern void grpcsharp_server_destroy(IntPtr server);
[DllImport(ImportName)]
public static extern AuthContextSafeHandle grpcsharp_call_auth_context(CallSafeHandle call);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_auth_context_peer_identity_property_name(AuthContextSafeHandle authContext);
[DllImport(ImportName)]
public static extern AuthContextSafeHandle.NativeAuthPropertyIterator grpcsharp_auth_context_property_iterator(AuthContextSafeHandle authContext);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_auth_property_iterator_next(ref AuthContextSafeHandle.NativeAuthPropertyIterator iterator);
[DllImport(ImportName)]
public static extern void grpcsharp_auth_context_release(IntPtr authContext);
[DllImport(ImportName)]
public static extern Timespec gprsharp_now(ClockType clockType);
[DllImport(ImportName)]
public static extern Timespec gprsharp_inf_future(ClockType clockType);
[DllImport(ImportName)]
public static extern Timespec gprsharp_inf_past(ClockType clockType);
[DllImport(ImportName)]
public static extern Timespec gprsharp_convert_clock_type(Timespec t, ClockType targetClock);
[DllImport(ImportName)]
public static extern int gprsharp_sizeof_timespec();
[DllImport(ImportName)]
public static extern CallError grpcsharp_test_callback([MarshalAs(UnmanagedType.FunctionPtr)] NativeCallbackTestDelegate callback);
[DllImport(ImportName)]
public static extern IntPtr grpcsharp_test_nop(IntPtr ptr);
[DllImport(ImportName)]
public static extern void grpcsharp_test_override_method(string methodName, string variant);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using StudentsLabs.APIControllers.Areas.HelpPage.ModelDescriptions;
using StudentsLabs.APIControllers.Areas.HelpPage.Models;
namespace StudentsLabs.APIControllers.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
namespace VoidEngine.VGame
{
public class Tile : Sprite
{
public enum TileCollisions
{
Passable,
Impassable,
Platform,
Water
}
public TileCollisions TileType;
protected int GridSize;
List<Tile> TileList = new List<Tile>();
int TileNum;
public bool GeneratedRandom;
public bool IsRandom;
public int RandomNumber;
Random random;
public Tile(Texture2D texture, Vector2 position, TileCollisions tileType, int randomSeed, int tilenum, Color color)
: base(position, color, texture)
{
AnimationSets = new List<AnimationSet>();
GridSize = texture.Width / 4;
random = new Random(randomSeed);
IsRandom = true;
AddAnimations(texture);
this.TileNum = tilenum;
this.TileType = tileType;
inbounds = new Rectangle(0, 0, texture.Width / 4, texture.Height / 4);
}
public Tile(Texture2D texture, Vector2 position, TileCollisions tileType, List<Tile> tileList, int tilenum, Color color)
: base(position, color, texture)
{
AnimationSets = new List<AnimationSet>();
GridSize = texture.Width / 4;
TileList = tileList;
this.TileNum = tilenum;
AddAnimations(texture);
this.TileType = tileType;
inbounds = new Rectangle(0, 0, texture.Width / 4, texture.Height / 4);
}
public void UpdateConnections()
{
bool mapright = IsSameResourceRightMe();
bool mapleft = IsSameResourceLeftMe();
bool mapup = IsSameResourceAboveMe();
bool mapdown = IsSameResourceBelowMe();
if (!mapright && !mapleft && !mapdown && !mapup)
SetAnimation("0");
else if (!mapright && mapleft && !mapdown && !mapup)
SetAnimation("1");
else if (mapright && mapleft && !mapdown && !mapup)
SetAnimation("2");
else if (mapright && !mapleft && !mapdown && !mapup)
SetAnimation("3");
else if (!mapright && !mapleft && mapdown && !mapup)
SetAnimation("4");
else if (!mapright && mapleft && mapdown && !mapup)
SetAnimation("5");
else if (mapright && mapleft && mapdown && !mapup)
SetAnimation("6");
else if (mapright && !mapleft && mapdown && !mapup)
SetAnimation("7");
else if (!mapright && !mapleft && mapdown && mapup)
SetAnimation("8");
else if (!mapright && mapleft && mapdown && mapup)
SetAnimation("9");
else if (mapright && mapleft && mapdown && mapup)
SetAnimation("10");
else if (mapright && !mapleft && mapdown && mapup)
SetAnimation("11");
else if (!mapright && !mapleft && !mapdown && mapup)
SetAnimation("12");
else if (!mapright && mapleft && !mapdown && mapup)
SetAnimation("13");
else if (mapright && mapleft && !mapdown && mapup)
SetAnimation("14");
else if (mapright && !mapleft && !mapdown && mapup)
SetAnimation("15");
}
public override void Update(GameTime gameTime)
{
if (IsRandom && !GeneratedRandom)
{
RandomNumber = random.Next(0, 256);
RandomNumber = (RandomNumber - 0) / (16 - 0);
SetAnimation(RandomNumber.ToString());
GeneratedRandom = true;
}
base.Update(gameTime);
}
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
base.Draw(gameTime, spriteBatch);
}
protected bool IsSameResourceAboveMe()
{
foreach (Tile t in TileList)
{
if (t.TileNum == TileNum && t.Position.Y == Position.Y - GridSize && t.Position.X == Position.X)
{
return true;
}
}
return false;
}
protected bool IsSameResourceLeftMe()
{
foreach (Tile t in TileList)
{
if (t.TileNum == TileNum && t.Position.X == Position.X + GridSize && t.Position.Y == Position.Y)
{
return true;
}
}
return false;
}
protected bool IsSameResourceRightMe()
{
foreach (Tile t in TileList)
{
if (t.TileNum == TileNum && t.Position.X == Position.X - GridSize && t.Position.Y == Position.Y)
{
return true;
}
}
return false;
}
protected bool IsSameResourceBelowMe()
{
foreach (Tile t in TileList)
{
if (t.TileNum == TileNum && t.Position.Y == Position.Y + GridSize && t.Position.X == Position.X)
{
return true;
}
}
return false;
}
public bool IsAResorceAboveMe()
{
foreach (Tile t in TileList)
{
if (t.Position.Y == Position.Y - GridSize && t.Position.X == Position.X)
{
return true;
}
}
return false;
}
protected bool IsAResorceLeftMe()
{
foreach (Tile t in TileList)
{
if (t.Position.X == Position.X + GridSize && t.Position.Y == Position.Y)
{
return true;
}
}
return false;
}
protected bool IsAResorceRightMe()
{
foreach (Tile t in TileList)
{
if (t.Position.X == Position.X - GridSize && t.Position.Y == Position.Y)
{
return true;
}
}
return false;
}
protected bool IsAResorceBelowMe()
{
foreach (Tile t in TileList)
{
if (t.Position.Y == Position.Y + GridSize && t.Position.X == Position.X)
{
return true;
}
}
return false;
}
protected override void AddAnimations(Texture2D texture)
{
AnimationSets.Add(new Sprite.AnimationSet("0", texture, new Point(GridSize, GridSize), Point.Zero, new Point(0, 0), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("1", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize, 0), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("2", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize * 2, 0), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("3", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize * 3, 0), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("4", texture, new Point(GridSize, GridSize), Point.Zero, new Point(0, GridSize), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("5", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize, GridSize), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("6", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize * 2, GridSize), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("7", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize * 3, GridSize), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("8", texture, new Point(GridSize, GridSize), Point.Zero, new Point(0, GridSize * 2), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("9", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize, GridSize * 2), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("10", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize * 2, GridSize * 2), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("11", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize * 3, GridSize * 2), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("12", texture, new Point(GridSize, GridSize), Point.Zero, new Point(0, GridSize * 3), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("13", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize, GridSize * 3), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("14", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize * 2, GridSize * 3), 0, false));
AnimationSets.Add(new Sprite.AnimationSet("15", texture, new Point(GridSize, GridSize), Point.Zero, new Point(GridSize * 3, GridSize * 3), 0, false));
SetAnimation("0");
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocEditGetter
// ObjectType: DocEditGetter
// CSLAType: UnitOfWork
using System;
using Csla;
using DocStore.Business.Admin;
namespace DocStore.Business
{
/// <summary>
/// DocEditGetter (creator and getter unit of work pattern).<br/>
/// This is a generated <see cref="DocEditGetter"/> business object.
/// This class is a root object that implements the Unit of Work pattern.
/// </summary>
[Serializable]
public partial class DocEditGetter : ReadOnlyBase<DocEditGetter>
{
#region Business Properties
/// <summary>
/// Maintains metadata about unit of work (child) <see cref="Doc"/> property.
/// </summary>
public static readonly PropertyInfo<Doc> DocProperty = RegisterProperty<Doc>(p => p.Doc, "Doc");
/// <summary>
/// Gets the Doc object (unit of work child property).
/// </summary>
/// <value>The Doc.</value>
public Doc Doc
{
get { return GetProperty(DocProperty); }
private set { LoadProperty(DocProperty, value); }
}
/// <summary>
/// Maintains metadata about unit of work (child) <see cref="DocClassNVL"/> property.
/// </summary>
public static readonly PropertyInfo<DocClassNVL> DocClassNVLProperty = RegisterProperty<DocClassNVL>(p => p.DocClassNVL, "Doc Class NVL");
/// <summary>
/// Gets the Doc Class NVL object (unit of work child property).
/// </summary>
/// <value>The Doc Class NVL.</value>
public DocClassNVL DocClassNVL
{
get { return GetProperty(DocClassNVLProperty); }
private set { LoadProperty(DocClassNVLProperty, value); }
}
/// <summary>
/// Maintains metadata about unit of work (child) <see cref="DocTypeNVL"/> property.
/// </summary>
public static readonly PropertyInfo<DocTypeNVL> DocTypeNVLProperty = RegisterProperty<DocTypeNVL>(p => p.DocTypeNVL, "Doc Type NVL");
/// <summary>
/// Gets the Doc Type NVL object (unit of work child property).
/// </summary>
/// <value>The Doc Type NVL.</value>
public DocTypeNVL DocTypeNVL
{
get { return GetProperty(DocTypeNVLProperty); }
private set { LoadProperty(DocTypeNVLProperty, value); }
}
/// <summary>
/// Maintains metadata about unit of work (child) <see cref="DocStatusNVL"/> property.
/// </summary>
public static readonly PropertyInfo<DocStatusNVL> DocStatusNVLProperty = RegisterProperty<DocStatusNVL>(p => p.DocStatusNVL, "Doc Status NVL");
/// <summary>
/// Gets the Doc Status NVL object (unit of work child property).
/// </summary>
/// <value>The Doc Status NVL.</value>
public DocStatusNVL DocStatusNVL
{
get { return GetProperty(DocStatusNVLProperty); }
private set { LoadProperty(DocStatusNVLProperty, value); }
}
/// <summary>
/// Maintains metadata about unit of work (child) <see cref="UserNVL"/> property.
/// </summary>
public static readonly PropertyInfo<UserNVL> UserNVLProperty = RegisterProperty<UserNVL>(p => p.UserNVL, "User NVL");
/// <summary>
/// Gets the User NVL object (unit of work child property).
/// </summary>
/// <value>The User NVL.</value>
public UserNVL UserNVL
{
get { return GetProperty(UserNVLProperty); }
private set { LoadProperty(UserNVLProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocEditGetter"/> unit of objects.
/// </summary>
/// <returns>A reference to the created <see cref="DocEditGetter"/> unit of objects.</returns>
public static DocEditGetter NewDocEditGetter()
{
// DataPortal_Fetch is used as ReadOnlyBase<T> doesn't allow the use of DataPortal_Create.
return DataPortal.Fetch<DocEditGetter>(new Criteria1(true, new int()));
}
/// <summary>
/// Factory method. Loads a <see cref="DocEditGetter"/> unit of objects, based on given parameters.
/// </summary>
/// <param name="docID">The DocID parameter of the DocEditGetter to fetch.</param>
/// <returns>A reference to the fetched <see cref="DocEditGetter"/> unit of objects.</returns>
public static DocEditGetter GetDocEditGetter(int docID)
{
return DataPortal.Fetch<DocEditGetter>(new Criteria1(false, docID));
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocEditGetter"/> unit of objects.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewDocEditGetter(EventHandler<DataPortalResult<DocEditGetter>> callback)
{
// DataPortal_Fetch is used as ReadOnlyBase<T> doesn't allow the use of DataPortal_Create.
DataPortal.BeginFetch<DocEditGetter>(new Criteria1(true, new int()), (o, e) =>
{
if (e.Error != null)
throw e.Error;
if (!DocClassNVL.IsCached)
DocClassNVL.SetCache(e.Object.DocClassNVL);
if (!DocTypeNVL.IsCached)
DocTypeNVL.SetCache(e.Object.DocTypeNVL);
if (!DocStatusNVL.IsCached)
DocStatusNVL.SetCache(e.Object.DocStatusNVL);
if (!UserNVL.IsCached)
UserNVL.SetCache(e.Object.UserNVL);
callback(o, e);
});
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="DocEditGetter"/> unit of objects, based on given parameters.
/// </summary>
/// <param name="docID">The DocID parameter of the DocEditGetter to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetDocEditGetter(int docID, EventHandler<DataPortalResult<DocEditGetter>> callback)
{
DataPortal.BeginFetch<DocEditGetter>(new Criteria1(false, docID), (o, e) =>
{
if (e.Error != null)
throw e.Error;
if (!DocClassNVL.IsCached)
DocClassNVL.SetCache(e.Object.DocClassNVL);
if (!DocTypeNVL.IsCached)
DocTypeNVL.SetCache(e.Object.DocTypeNVL);
if (!DocStatusNVL.IsCached)
DocStatusNVL.SetCache(e.Object.DocStatusNVL);
if (!UserNVL.IsCached)
UserNVL.SetCache(e.Object.UserNVL);
callback(o, e);
});
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocEditGetter"/> class.
/// </summary>
/// <remarks> Do not use to create a Unit of Work. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocEditGetter()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Criteria
/// <summary>
/// Criteria1 criteria.
/// </summary>
[Serializable]
protected class Criteria1 : CriteriaBase<Criteria1>
{
/// <summary>
/// Maintains metadata about <see cref="CreateDoc"/> property.
/// </summary>
public static readonly PropertyInfo<bool> CreateDocProperty = RegisterProperty<bool>(p => p.CreateDoc, "Create Doc");
/// <summary>
/// Gets or sets the Create Doc.
/// </summary>
/// <value><c>true</c> if Create Doc; otherwise, <c>false</c>.</value>
public bool CreateDoc
{
get { return ReadProperty(CreateDocProperty); }
set { LoadProperty(CreateDocProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="DocID"/> property.
/// </summary>
public static readonly PropertyInfo<int> DocIDProperty = RegisterProperty<int>(p => p.DocID, "Doc ID");
/// <summary>
/// Gets or sets the Doc ID.
/// </summary>
/// <value>The Doc ID.</value>
public int DocID
{
get { return ReadProperty(DocIDProperty); }
set { LoadProperty(DocIDProperty, value); }
}
/// <summary>
/// Initializes a new instance of the <see cref="Criteria1"/> class.
/// </summary>
/// <remarks> A parameterless constructor is required by the MobileFormatter.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public Criteria1()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Criteria1"/> class.
/// </summary>
/// <param name="createDoc">The CreateDoc.</param>
/// <param name="docID">The DocID.</param>
public Criteria1(bool createDoc, int docID)
{
CreateDoc = createDoc;
DocID = docID;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is Criteria1)
{
var c = (Criteria1) obj;
if (!CreateDoc.Equals(c.CreateDoc))
return false;
if (!DocID.Equals(c.DocID))
return false;
return true;
}
return false;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return string.Concat("Criteria1", CreateDoc.ToString(), DocID.ToString()).GetHashCode();
}
}
#endregion
#region Data Access
/// <summary>
/// Creates or loads a <see cref="DocEditGetter"/> unit of objects, based on given criteria.
/// </summary>
/// <param name="crit">The create/fetch criteria.</param>
protected void DataPortal_Fetch(Criteria1 crit)
{
if (crit.CreateDoc)
LoadProperty(DocProperty, Doc.NewDoc());
else
LoadProperty(DocProperty, Doc.GetDoc(crit.DocID));
LoadProperty(DocClassNVLProperty, DocClassNVL.GetDocClassNVL());
LoadProperty(DocTypeNVLProperty, DocTypeNVL.GetDocTypeNVL());
LoadProperty(DocStatusNVLProperty, DocStatusNVL.GetDocStatusNVL());
LoadProperty(UserNVLProperty, UserNVL.GetUserNVL());
}
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using UnityEditorInternal;
using Debug = UnityEngine.Debug;
using Ink.Runtime;
/// <summary>
/// Holds a reference to an InkFile object for every .ink file detected in the Assets folder.
/// Provides helper functions to easily obtain these files.
/// </summary>
namespace Ink.UnityIntegration {
public class InkLibrary : ScriptableObject {
public static bool created {
get {
InkLibrary tmpSettings = AssetDatabase.LoadAssetAtPath<InkLibrary>(defaultPath);
if(tmpSettings != null)
return true;
string[] GUIDs = AssetDatabase.FindAssets("t:"+typeof(InkLibrary).Name);
if(GUIDs.Length > 0)
return true;
return false;
}
}
private static InkLibrary _Instance;
public static InkLibrary Instance {
get {
if(_Instance == null)
_Instance = FindOrCreateLibrary();
return _Instance;
}
}
public const string defaultPath = "Assets/InkLibrary.asset";
public bool compileAutomatically = true;
public bool handleJSONFilesAutomatically = true;
public List<InkFile> inkLibrary = new List<InkFile>();
public List<InkCompiler.CompilationStackItem> compilationStack = new List<InkCompiler.CompilationStackItem>();
[MenuItem("Edit/Project Settings/Ink", false, 500)]
public static void SelectFromProjectSettings() {
Selection.activeObject = Instance;
}
/// <summary>
/// Removes and null references in the library
/// </summary>
public static void Clean () {
for (int i = InkLibrary.Instance.inkLibrary.Count - 1; i >= 0; i--) {
InkFile inkFile = InkLibrary.Instance.inkLibrary[i];
if (inkFile.inkAsset == null)
InkLibrary.Instance.inkLibrary.RemoveAt(i);
}
}
private static InkLibrary FindOrCreateLibrary () {
InkLibrary tmpSettings = AssetDatabase.LoadAssetAtPath<InkLibrary>(defaultPath);
if(tmpSettings == null) {
string[] GUIDs = AssetDatabase.FindAssets("t:"+typeof(InkLibrary).Name);
if(GUIDs.Length > 0) {
string path = AssetDatabase.GUIDToAssetPath(GUIDs[0]);
tmpSettings = AssetDatabase.LoadAssetAtPath<InkLibrary>(path);
if(GUIDs.Length > 1) {
for(int i = 1; i < GUIDs.Length; i++) {
AssetDatabase.DeleteAsset(AssetDatabase.GUIDToAssetPath(GUIDs[i]));
}
Debug.LogWarning("More than one InkLibrary was found. Deleted excess libraries.");
}
}
}
// If we couldn't find the asset in the project, create a new one.
if(tmpSettings == null) {
tmpSettings = CreateInkLibrary ();
Debug.Log("Created a new ink library at "+defaultPath+" because one was not found.");
InkLibrary.Rebuild();
}
return tmpSettings;
}
private static InkLibrary CreateInkLibrary () {
var asset = ScriptableObject.CreateInstance<InkLibrary>();
AssetDatabase.CreateAsset (asset, defaultPath);
AssetDatabase.SaveAssets ();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(asset));
return asset;
}
public static string[] GetAllInkFilePaths () {
string[] inkFilePaths = Directory.GetFiles(Application.dataPath, "*.ink", SearchOption.AllDirectories);
for (int i = 0; i < inkFilePaths.Length; i++) {
inkFilePaths [i] = InkEditorUtils.SanitizePathString(inkFilePaths [i]);
}
return inkFilePaths;
}
/// <summary>
/// Updates the ink library. Executed whenever an ink file is changed by InkToJSONPostProcessor
/// Can be called manually, but incurs a performance cost.
/// </summary>
public static void Rebuild () {
Debug.Log("Rebuilding Ink Library...");
string[] inkFilePaths = GetAllInkFilePaths();
List<InkFile> newInkLibrary = new List<InkFile>(inkFilePaths.Length);
for (int i = 0; i < inkFilePaths.Length; i++) {
InkFile inkFile = GetInkFileWithAbsolutePath(inkFilePaths [i]);
if(inkFile == null) {
string localAssetPath = inkFilePaths [i].Substring(Application.dataPath.Length-6);
DefaultAsset inkFileAsset = AssetDatabase.LoadAssetAtPath<DefaultAsset>(localAssetPath);
// If the ink file can't be found, it might not yet have been imported. We try to manually import it to fix this.
if(inkFileAsset == null) {
AssetDatabase.ImportAsset(localAssetPath);
inkFileAsset = AssetDatabase.LoadAssetAtPath<DefaultAsset>(localAssetPath);
if(inkFileAsset == null) {
Debug.LogWarning("Ink File Asset not found at "+localAssetPath+". This can occur if the .meta file has not yet been created. This issue should resolve itself, but if unexpected errors occur, rebuild Ink Library using > Recompile Ink");
continue;
}
}
inkFile = new InkFile(inkFileAsset);
}
newInkLibrary.Add(inkFile);
}
InkLibrary.Instance.inkLibrary = newInkLibrary;
foreach (InkFile inkFile in InkLibrary.Instance.inkLibrary) {
inkFile.ParseContent();
}
RebuildInkFileConnections();
foreach (InkFile inkFile in InkLibrary.Instance.inkLibrary) {
inkFile.FindCompiledJSONAsset();
}
EditorUtility.SetDirty(InkLibrary.Instance);
AssetDatabase.SaveAssets();
EditorApplication.RepaintProjectWindow();
}
/// <summary>
/// Rebuilds which files are master files.
/// </summary>
public static void RebuildInkFileConnections () {
foreach (InkFile inkFile in InkLibrary.Instance.inkLibrary) {
inkFile.parent = null;
inkFile.master = null;
inkFile.FindIncludedFiles();
}
// We now set the master file for ink files. As a file can be in an include hierarchy, we need to do this in two passes.
// First, we set the master file to the file that includes an ink file.
foreach (InkFile inkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile.includes.Count == 0)
continue;
foreach (InkFile otherInkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile == otherInkFile)
continue;
if(inkFile.includes.Contains(otherInkFile.inkAsset)) {
otherInkFile.parent = inkFile.inkAsset;
}
}
}
// Next, we create a list of all the files owned by the actual master file, which we obtain by travelling up the parent tree from each file.
Dictionary<InkFile, List<InkFile>> masterChildRelationships = new Dictionary<InkFile, List<InkFile>>();
foreach (InkFile inkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile.parent == null)
continue;
InkFile parent = inkFile.parentInkFile;
while (parent.parent != null) {
parent = parent.parentInkFile;
}
if(!masterChildRelationships.ContainsKey(parent)) {
masterChildRelationships.Add(parent, new List<InkFile>());
}
masterChildRelationships[parent].Add(inkFile);
}
// Finally, we set the master file of the children
foreach (var inkFileRelationship in masterChildRelationships) {
foreach(InkFile childInkFile in inkFileRelationship.Value) {
childInkFile.master = inkFileRelationship.Key.inkAsset;
if(InkLibrary.Instance.handleJSONFilesAutomatically && childInkFile.jsonAsset != null) {
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(childInkFile.jsonAsset));
childInkFile.jsonAsset = null;
}
}
}
}
public static List<InkFile> GetMasterInkFiles () {
List<InkFile> masterInkFiles = new List<InkFile>();
if(InkLibrary.Instance.inkLibrary == null) return masterInkFiles;
foreach (InkFile inkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile.isMaster) {
masterInkFiles.Add(inkFile);
}
}
return masterInkFiles;
}
/// <summary>
/// Gets the ink file from the .ink file reference.
/// </summary>
/// <returns>The ink file with path.</returns>
/// <param name="path">Path.</param>
public static InkFile GetInkFileWithFile (DefaultAsset file) {
if(InkLibrary.Instance.inkLibrary == null) return null;
foreach(InkFile inkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile.inkAsset == file) {
return inkFile;
}
}
return null;
}
/// <summary>
/// Gets the ink file with path relative to Assets folder, for example: "Assets/Ink/myStory.ink".
/// </summary>
/// <returns>The ink file with path.</returns>
/// <param name="path">Path.</param>
public static InkFile GetInkFileWithPath (string path) {
if(InkLibrary.Instance.inkLibrary == null) return null;
foreach(InkFile inkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile.filePath == path) {
return inkFile;
}
}
return null;
}
/// <summary>
/// Gets the ink file with absolute path.
/// </summary>
/// <returns>The ink file with path.</returns>
/// <param name="path">Path.</param>
public static InkFile GetInkFileWithAbsolutePath (string absolutePath) {
if(InkLibrary.Instance.inkLibrary == null) return null;
foreach(InkFile inkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile.absoluteFilePath == absolutePath) {
return inkFile;
}
}
return null;
}
public static List<InkCompiler.CompilationStackItem> FilesInCompilingStackInState (InkCompiler.CompilationStackItem.State state) {
List<InkCompiler.CompilationStackItem> items = new List<InkCompiler.CompilationStackItem>();
foreach(var x in InkLibrary.Instance.compilationStack) {
if(x.state == state)
items.Add(x);
}
return items;
}
public static InkCompiler.CompilationStackItem GetCompilationStackItem (string inkAbsoluteFilePath) {
foreach(var x in InkLibrary.Instance.compilationStack) {
if(x.inkAbsoluteFilePath == inkAbsoluteFilePath)
return x;
}
Debug.LogError("Fatal Error compiling Ink! No file found! Please report this as a bug. "+inkAbsoluteFilePath);
return null;
}
public static InkCompiler.CompilationStackItem GetCompilationStackItem (InkFile inkFile) {
foreach(var x in InkLibrary.Instance.compilationStack) {
if(x.inkFile == inkFile)
return x;
}
return null;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security;
using System.Text;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Estate
{
/// <summary>
/// Estate management console commands.
/// </summary>
public class EstateManagementCommands
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected EstateManagementModule m_module;
protected Commander m_commander = new Commander("estate");
public EstateManagementCommands(EstateManagementModule module)
{
m_module = module;
}
public void Initialise()
{
// m_log.DebugFormat("[ESTATE MODULE]: Setting up estate commands for region {0}", m_module.Scene.RegionInfo.RegionName);
m_module.Scene.AddCommand("Regions", m_module, "set terrain texture",
"set terrain texture <number> <uuid> [<x>] [<y>]",
"Sets the terrain <number> to <uuid>, if <x> or <y> are specified, it will only " +
"set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" +
" that coordinate.",
consoleSetTerrainTexture);
m_module.Scene.AddCommand("Regions", m_module, "set terrain heights",
"set terrain heights <corner> <min> <max> [<x>] [<y>]",
"Sets the terrain texture heights on corner #<corner> to <min>/<max>, if <x> or <y> are specified, it will only " +
"set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" +
" that coordinate. Corner # SW = 0, NW = 1, SE = 2, NE = 3, all corners = -1.",
consoleSetTerrainHeights);
m_module.Scene.AddCommand("Regions", m_module, "set water height",
"set water height <height> [<x>] [<y>]",
"Sets the water height in meters. If <x> and <y> are specified, it will only set it on regions with a matching coordinate. " +
"Specify -1 in <x> or <y> to wildcard that coordinate.",
consoleSetWaterHeight);
m_module.Scene.AddCommand(
"Estates", m_module, "estate show", "estate show", "Shows all estates on the simulator.", ShowEstatesCommand);
}
public void Close() {}
protected void consoleSetTerrainTexture(string module, string[] args)
{
string num = args[3];
string uuid = args[4];
int x = (args.Length > 5 ? int.Parse(args[5]) : -1);
int y = (args.Length > 6 ? int.Parse(args[6]) : -1);
if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x)
{
if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y)
{
int corner = int.Parse(num);
UUID texture = UUID.Parse(uuid);
m_log.Debug("[ESTATEMODULE]: Setting terrain textures for " + m_module.Scene.RegionInfo.RegionName +
string.Format(" (C#{0} = {1})", corner, texture));
switch (corner)
{
case 0:
m_module.Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture;
break;
case 1:
m_module.Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture;
break;
case 2:
m_module.Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture;
break;
case 3:
m_module.Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture;
break;
}
m_module.Scene.RegionInfo.RegionSettings.Save();
m_module.TriggerRegionInfoChange();
m_module.sendRegionHandshakeToAll();
}
}
}
protected void consoleSetWaterHeight(string module, string[] args)
{
string heightstring = args[3];
int x = (args.Length > 4 ? int.Parse(args[4]) : -1);
int y = (args.Length > 5 ? int.Parse(args[5]) : -1);
if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x)
{
if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y)
{
double selectedheight = double.Parse(heightstring);
m_log.Debug("[ESTATEMODULE]: Setting water height in " + m_module.Scene.RegionInfo.RegionName + " to " +
string.Format(" {0}", selectedheight));
m_module.Scene.RegionInfo.RegionSettings.WaterHeight = selectedheight;
m_module.Scene.RegionInfo.RegionSettings.Save();
m_module.TriggerRegionInfoChange();
m_module.sendRegionHandshakeToAll();
}
}
}
protected void consoleSetTerrainHeights(string module, string[] args)
{
string num = args[3];
string min = args[4];
string max = args[5];
int x = (args.Length > 6 ? int.Parse(args[6]) : -1);
int y = (args.Length > 7 ? int.Parse(args[7]) : -1);
if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x)
{
if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y)
{
int corner = int.Parse(num);
float lowValue = float.Parse(min, Culture.NumberFormatInfo);
float highValue = float.Parse(max, Culture.NumberFormatInfo);
m_log.Debug("[ESTATEMODULE]: Setting terrain heights " + m_module.Scene.RegionInfo.RegionName +
string.Format(" (C{0}, {1}-{2}", corner, lowValue, highValue));
switch (corner)
{
case -1:
m_module.Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
case 0:
m_module.Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
break;
case 1:
m_module.Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
break;
case 2:
m_module.Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
break;
case 3:
m_module.Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
m_module.Scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
}
m_module.Scene.RegionInfo.RegionSettings.Save();
m_module.TriggerRegionInfoChange();
m_module.sendRegionHandshakeToAll();
}
}
}
protected void ShowEstatesCommand(string module, string[] cmd)
{
StringBuilder report = new StringBuilder();
RegionInfo ri = m_module.Scene.RegionInfo;
EstateSettings es = ri.EstateSettings;
report.AppendFormat("Estate information for region {0}\n", ri.RegionName);
report.AppendFormat(
"{0,-20} {1,-7} {2,-20}\n",
"Estate Name",
"ID",
"Owner");
report.AppendFormat(
"{0,-20} {1,-7} {2,-20}\n",
es.EstateName, es.EstateID, m_module.UserManager.GetUserName(es.EstateOwner));
MainConsole.Instance.Output(report.ToString());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.