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.
/******************************************************************************
* 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 DuplicateEvenIndexedDouble()
{
var test = new SimpleUnaryOpTest__DuplicateEvenIndexedDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__DuplicateEvenIndexedDouble
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector256<Double> _clsVar;
private Vector256<Double> _fld;
private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable;
static SimpleUnaryOpTest__DuplicateEvenIndexedDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__DuplicateEvenIndexedDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.DuplicateEvenIndexed(
Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.DuplicateEvenIndexed(
Avx.LoadVector256((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.DuplicateEvenIndexed(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateEvenIndexed), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateEvenIndexed), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateEvenIndexed), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.DuplicateEvenIndexed(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr);
var result = Avx.DuplicateEvenIndexed(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Double*)(_dataTable.inArrayPtr));
var result = Avx.DuplicateEvenIndexed(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr));
var result = Avx.DuplicateEvenIndexed(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__DuplicateEvenIndexedDouble();
var result = Avx.DuplicateEvenIndexed(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.DuplicateEvenIndexed(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(firstOp[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i % 2 == 0) ? (BitConverter.DoubleToInt64Bits(firstOp[i]) != BitConverter.DoubleToInt64Bits(result[i])) : (BitConverter.DoubleToInt64Bits(firstOp[i - 1]) != BitConverter.DoubleToInt64Bits(result[i])))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.DuplicateEvenIndexed)}<Double>(Vector256<Double>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="CampaignExtensionSettingServiceClient"/> instances.</summary>
public sealed partial class CampaignExtensionSettingServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CampaignExtensionSettingServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CampaignExtensionSettingServiceSettings"/>.</returns>
public static CampaignExtensionSettingServiceSettings GetDefault() => new CampaignExtensionSettingServiceSettings();
/// <summary>
/// Constructs a new <see cref="CampaignExtensionSettingServiceSettings"/> object with default settings.
/// </summary>
public CampaignExtensionSettingServiceSettings()
{
}
private CampaignExtensionSettingServiceSettings(CampaignExtensionSettingServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCampaignExtensionSettingSettings = existing.GetCampaignExtensionSettingSettings;
MutateCampaignExtensionSettingsSettings = existing.MutateCampaignExtensionSettingsSettings;
OnCopy(existing);
}
partial void OnCopy(CampaignExtensionSettingServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignExtensionSettingServiceClient.GetCampaignExtensionSetting</c> and
/// <c>CampaignExtensionSettingServiceClient.GetCampaignExtensionSettingAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCampaignExtensionSettingSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignExtensionSettingServiceClient.MutateCampaignExtensionSettings</c> and
/// <c>CampaignExtensionSettingServiceClient.MutateCampaignExtensionSettingsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCampaignExtensionSettingsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CampaignExtensionSettingServiceSettings"/> object.</returns>
public CampaignExtensionSettingServiceSettings Clone() => new CampaignExtensionSettingServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CampaignExtensionSettingServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class CampaignExtensionSettingServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignExtensionSettingServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CampaignExtensionSettingServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CampaignExtensionSettingServiceClientBuilder()
{
UseJwtAccessWithScopes = CampaignExtensionSettingServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CampaignExtensionSettingServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignExtensionSettingServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CampaignExtensionSettingServiceClient Build()
{
CampaignExtensionSettingServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CampaignExtensionSettingServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CampaignExtensionSettingServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CampaignExtensionSettingServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CampaignExtensionSettingServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CampaignExtensionSettingServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CampaignExtensionSettingServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CampaignExtensionSettingServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
CampaignExtensionSettingServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignExtensionSettingServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CampaignExtensionSettingService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign extension settings.
/// </remarks>
public abstract partial class CampaignExtensionSettingServiceClient
{
/// <summary>
/// The default endpoint for the CampaignExtensionSettingService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CampaignExtensionSettingService scopes.</summary>
/// <remarks>
/// The default CampaignExtensionSettingService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CampaignExtensionSettingServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignExtensionSettingServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CampaignExtensionSettingServiceClient"/>.</returns>
public static stt::Task<CampaignExtensionSettingServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CampaignExtensionSettingServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CampaignExtensionSettingServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignExtensionSettingServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CampaignExtensionSettingServiceClient"/>.</returns>
public static CampaignExtensionSettingServiceClient Create() =>
new CampaignExtensionSettingServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CampaignExtensionSettingServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CampaignExtensionSettingServiceSettings"/>.</param>
/// <returns>The created <see cref="CampaignExtensionSettingServiceClient"/>.</returns>
internal static CampaignExtensionSettingServiceClient Create(grpccore::CallInvoker callInvoker, CampaignExtensionSettingServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CampaignExtensionSettingService.CampaignExtensionSettingServiceClient grpcClient = new CampaignExtensionSettingService.CampaignExtensionSettingServiceClient(callInvoker);
return new CampaignExtensionSettingServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CampaignExtensionSettingService client</summary>
public virtual CampaignExtensionSettingService.CampaignExtensionSettingServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignExtensionSetting GetCampaignExtensionSetting(GetCampaignExtensionSettingRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignExtensionSetting> GetCampaignExtensionSettingAsync(GetCampaignExtensionSettingRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignExtensionSetting> GetCampaignExtensionSettingAsync(GetCampaignExtensionSettingRequest request, st::CancellationToken cancellationToken) =>
GetCampaignExtensionSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign extension setting to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignExtensionSetting GetCampaignExtensionSetting(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignExtensionSetting(new GetCampaignExtensionSettingRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign extension setting to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignExtensionSetting> GetCampaignExtensionSettingAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignExtensionSettingAsync(new GetCampaignExtensionSettingRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign extension setting to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignExtensionSetting> GetCampaignExtensionSettingAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCampaignExtensionSettingAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign extension setting to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignExtensionSetting GetCampaignExtensionSetting(gagvr::CampaignExtensionSettingName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignExtensionSetting(new GetCampaignExtensionSettingRequest
{
ResourceNameAsCampaignExtensionSettingName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign extension setting to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignExtensionSetting> GetCampaignExtensionSettingAsync(gagvr::CampaignExtensionSettingName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignExtensionSettingAsync(new GetCampaignExtensionSettingRequest
{
ResourceNameAsCampaignExtensionSettingName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign extension setting to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignExtensionSetting> GetCampaignExtensionSettingAsync(gagvr::CampaignExtensionSettingName resourceName, st::CancellationToken cancellationToken) =>
GetCampaignExtensionSettingAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCampaignExtensionSettingsResponse MutateCampaignExtensionSettings(MutateCampaignExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignExtensionSettingsResponse> MutateCampaignExtensionSettingsAsync(MutateCampaignExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignExtensionSettingsResponse> MutateCampaignExtensionSettingsAsync(MutateCampaignExtensionSettingsRequest request, st::CancellationToken cancellationToken) =>
MutateCampaignExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign extension settings are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign extension
/// settings.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCampaignExtensionSettingsResponse MutateCampaignExtensionSettings(string customerId, scg::IEnumerable<CampaignExtensionSettingOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignExtensionSettings(new MutateCampaignExtensionSettingsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign extension settings are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign extension
/// settings.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignExtensionSettingsResponse> MutateCampaignExtensionSettingsAsync(string customerId, scg::IEnumerable<CampaignExtensionSettingOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignExtensionSettingsAsync(new MutateCampaignExtensionSettingsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign extension settings are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign extension
/// settings.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignExtensionSettingsResponse> MutateCampaignExtensionSettingsAsync(string customerId, scg::IEnumerable<CampaignExtensionSettingOperation> operations, st::CancellationToken cancellationToken) =>
MutateCampaignExtensionSettingsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CampaignExtensionSettingService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign extension settings.
/// </remarks>
public sealed partial class CampaignExtensionSettingServiceClientImpl : CampaignExtensionSettingServiceClient
{
private readonly gaxgrpc::ApiCall<GetCampaignExtensionSettingRequest, gagvr::CampaignExtensionSetting> _callGetCampaignExtensionSetting;
private readonly gaxgrpc::ApiCall<MutateCampaignExtensionSettingsRequest, MutateCampaignExtensionSettingsResponse> _callMutateCampaignExtensionSettings;
/// <summary>
/// Constructs a client wrapper for the CampaignExtensionSettingService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CampaignExtensionSettingServiceSettings"/> used within this client.
/// </param>
public CampaignExtensionSettingServiceClientImpl(CampaignExtensionSettingService.CampaignExtensionSettingServiceClient grpcClient, CampaignExtensionSettingServiceSettings settings)
{
GrpcClient = grpcClient;
CampaignExtensionSettingServiceSettings effectiveSettings = settings ?? CampaignExtensionSettingServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCampaignExtensionSetting = clientHelper.BuildApiCall<GetCampaignExtensionSettingRequest, gagvr::CampaignExtensionSetting>(grpcClient.GetCampaignExtensionSettingAsync, grpcClient.GetCampaignExtensionSetting, effectiveSettings.GetCampaignExtensionSettingSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCampaignExtensionSetting);
Modify_GetCampaignExtensionSettingApiCall(ref _callGetCampaignExtensionSetting);
_callMutateCampaignExtensionSettings = clientHelper.BuildApiCall<MutateCampaignExtensionSettingsRequest, MutateCampaignExtensionSettingsResponse>(grpcClient.MutateCampaignExtensionSettingsAsync, grpcClient.MutateCampaignExtensionSettings, effectiveSettings.MutateCampaignExtensionSettingsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCampaignExtensionSettings);
Modify_MutateCampaignExtensionSettingsApiCall(ref _callMutateCampaignExtensionSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCampaignExtensionSettingApiCall(ref gaxgrpc::ApiCall<GetCampaignExtensionSettingRequest, gagvr::CampaignExtensionSetting> call);
partial void Modify_MutateCampaignExtensionSettingsApiCall(ref gaxgrpc::ApiCall<MutateCampaignExtensionSettingsRequest, MutateCampaignExtensionSettingsResponse> call);
partial void OnConstruction(CampaignExtensionSettingService.CampaignExtensionSettingServiceClient grpcClient, CampaignExtensionSettingServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CampaignExtensionSettingService client</summary>
public override CampaignExtensionSettingService.CampaignExtensionSettingServiceClient GrpcClient { get; }
partial void Modify_GetCampaignExtensionSettingRequest(ref GetCampaignExtensionSettingRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCampaignExtensionSettingsRequest(ref MutateCampaignExtensionSettingsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CampaignExtensionSetting GetCampaignExtensionSetting(GetCampaignExtensionSettingRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCampaignExtensionSettingRequest(ref request, ref callSettings);
return _callGetCampaignExtensionSetting.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested campaign extension setting in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CampaignExtensionSetting> GetCampaignExtensionSettingAsync(GetCampaignExtensionSettingRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCampaignExtensionSettingRequest(ref request, ref callSettings);
return _callGetCampaignExtensionSetting.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCampaignExtensionSettingsResponse MutateCampaignExtensionSettings(MutateCampaignExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignExtensionSettingsRequest(ref request, ref callSettings);
return _callMutateCampaignExtensionSettings.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCampaignExtensionSettingsResponse> MutateCampaignExtensionSettingsAsync(MutateCampaignExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignExtensionSettingsRequest(ref request, ref callSettings);
return _callMutateCampaignExtensionSettings.Async(request, callSettings);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Net.Http.Headers
{
public class RangeItemHeaderValue : ICloneable
{
private long? _from;
private long? _to;
public long? From
{
get { return _from; }
}
public long? To
{
get { return _to; }
}
public RangeItemHeaderValue(long? from, long? to)
{
if (!from.HasValue && !to.HasValue)
{
throw new ArgumentException(SR.net_http_headers_invalid_range);
}
if (from.HasValue && (from.Value < 0))
{
throw new ArgumentOutOfRangeException("from");
}
if (to.HasValue && (to.Value < 0))
{
throw new ArgumentOutOfRangeException("to");
}
if (from.HasValue && to.HasValue && (from.Value > to.Value))
{
throw new ArgumentOutOfRangeException("from");
}
_from = from;
_to = to;
}
private RangeItemHeaderValue(RangeItemHeaderValue source)
{
Contract.Requires(source != null);
_from = source._from;
_to = source._to;
}
public override string ToString()
{
if (!_from.HasValue)
{
return "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo);
}
else if (!_to.HasValue)
{
return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-";
}
return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-" +
_to.Value.ToString(NumberFormatInfo.InvariantInfo);
}
public override bool Equals(object obj)
{
RangeItemHeaderValue other = obj as RangeItemHeaderValue;
if (other == null)
{
return false;
}
return ((_from == other._from) && (_to == other._to));
}
public override int GetHashCode()
{
if (!_from.HasValue)
{
return _to.GetHashCode();
}
else if (!_to.HasValue)
{
return _from.GetHashCode();
}
return _from.GetHashCode() ^ _to.GetHashCode();
}
// Returns the length of a range list. E.g. "1-2, 3-4, 5-6" adds 3 ranges to 'rangeCollection'. Note that empty
// list segments are allowed, e.g. ",1-2, , 3-4,,".
internal static int GetRangeItemListLength(string input, int startIndex,
ICollection<RangeItemHeaderValue> rangeCollection)
{
Contract.Requires(rangeCollection != null);
Contract.Requires(startIndex >= 0);
Contract.Ensures((Contract.Result<int>() == 0) || (rangeCollection.Count > 0),
"If we can parse the string, then we expect to have at least one range item.");
if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length))
{
return 0;
}
// Empty segments are allowed, so skip all delimiter-only segments (e.g. ", ,").
bool separatorFound = false;
int current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out separatorFound);
// It's OK if we didn't find leading separator characters. Ignore 'separatorFound'.
if (current == input.Length)
{
return 0;
}
RangeItemHeaderValue range = null;
while (true)
{
int rangeLength = GetRangeItemLength(input, current, out range);
if (rangeLength == 0)
{
return 0;
}
rangeCollection.Add(range);
current = current + rangeLength;
current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound);
// If the string is not consumed, we must have a delimiter, otherwise the string is not a valid
// range list.
if ((current < input.Length) && !separatorFound)
{
return 0;
}
if (current == input.Length)
{
return current - startIndex;
}
}
}
internal static int GetRangeItemLength(string input, int startIndex, out RangeItemHeaderValue parsedValue)
{
Contract.Requires(startIndex >= 0);
// This parser parses number ranges: e.g. '1-2', '1-', '-2'.
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespaces. If not, we'll return 0.
int current = startIndex;
// Try parse the first value of a value pair.
int fromStartIndex = current;
int fromLength = HttpRuleParser.GetNumberLength(input, current, false);
if (fromLength > HttpRuleParser.MaxInt64Digits)
{
return 0;
}
current = current + fromLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Afer the first value, the '-' character must follow.
if ((current == input.Length) || (input[current] != '-'))
{
// We need a '-' character otherwise this can't be a valid range.
return 0;
}
current++; // skip the '-' character
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
int toStartIndex = current;
int toLength = 0;
// If we didn't reach the end of the string, try parse the second value of the range.
if (current < input.Length)
{
toLength = HttpRuleParser.GetNumberLength(input, current, false);
if (toLength > HttpRuleParser.MaxInt64Digits)
{
return 0;
}
current = current + toLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
if ((fromLength == 0) && (toLength == 0))
{
return 0; // At least one value must be provided in order to be a valid range.
}
// Try convert first value to int64
long from = 0;
if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from))
{
return 0;
}
// Try convert second value to int64
long to = 0;
if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to))
{
return 0;
}
// 'from' must not be greater than 'to'
if ((fromLength > 0) && (toLength > 0) && (from > to))
{
return 0;
}
parsedValue = new RangeItemHeaderValue((fromLength == 0 ? (long?)null : (long?)from),
(toLength == 0 ? (long?)null : (long?)to));
return current - startIndex;
}
object ICloneable.Clone()
{
return new RangeItemHeaderValue(this);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.Sql.Models;
namespace Microsoft.Azure.Management.Sql.Models
{
/// <summary>
/// Represents the properties of an Azure SQL Advisor Recommended Ac.
/// </summary>
public partial class RecommendedActionProperties
{
private IDictionary<string, object> _details;
/// <summary>
/// Optional. Gets additional details specific to this recommended
/// action
/// </summary>
public IDictionary<string, object> Details
{
get { return this._details; }
set { this._details = value; }
}
private RecommendedActionErrorInfo _errorDetails;
/// <summary>
/// Optional. Gets the error details if and why this recommended action
/// is put to Error state.
/// </summary>
public RecommendedActionErrorInfo ErrorDetails
{
get { return this._errorDetails; }
set { this._errorDetails = value; }
}
private IList<RecommendedActionImpactInfo> _estimatedImpact;
/// <summary>
/// Optional. Gets the estimated impact info for this recommended
/// action E.g., Estimated CPU gain, Estimated Disk Space change
/// </summary>
public IList<RecommendedActionImpactInfo> EstimatedImpact
{
get { return this._estimatedImpact; }
set { this._estimatedImpact = value; }
}
private string _executeActionDuration;
/// <summary>
/// Optional. Gets the time taken for applying this recommended action
/// on user resource. E.g., Time taken for index creation
/// </summary>
public string ExecuteActionDuration
{
get { return this._executeActionDuration; }
set { this._executeActionDuration = value; }
}
private string _executeActionInitiatedBy;
/// <summary>
/// Optional. Gets if approval for applying this recommended action is
/// given by User/System.
/// </summary>
public string ExecuteActionInitiatedBy
{
get { return this._executeActionInitiatedBy; }
set { this._executeActionInitiatedBy = value; }
}
private System.DateTime? _executeActionInitiatedTime;
/// <summary>
/// Optional. Gets the time when this recommended action is approved
/// for execution
/// </summary>
public System.DateTime? ExecuteActionInitiatedTime
{
get { return this._executeActionInitiatedTime; }
set { this._executeActionInitiatedTime = value; }
}
private System.DateTime? _executeActionStartTime;
/// <summary>
/// Optional. Gets the time when system started applying this
/// recommended action on the user resource. E.g., Index creation
/// start time
/// </summary>
public System.DateTime? ExecuteActionStartTime
{
get { return this._executeActionStartTime; }
set { this._executeActionStartTime = value; }
}
private RecommendedActionImplementationInfo _implementationDetails;
/// <summary>
/// Optional. Gets the implementation details of this recommended
/// action for user to apply it manually.
/// </summary>
public RecommendedActionImplementationInfo ImplementationDetails
{
get { return this._implementationDetails; }
set { this._implementationDetails = value; }
}
private bool? _isArchivedAction;
/// <summary>
/// Optional. Gets if this recommended action was already suggested
/// some time ago but user chose to ignore this and System recommends
/// again.
/// </summary>
public bool? IsArchivedAction
{
get { return this._isArchivedAction; }
set { this._isArchivedAction = value; }
}
private bool? _isExecutableAction;
/// <summary>
/// Optional. Gets if this recommended action is actionable to User
/// </summary>
public bool? IsExecutableAction
{
get { return this._isExecutableAction; }
set { this._isExecutableAction = value; }
}
private bool? _isRevertableAction;
/// <summary>
/// Optional. Gets if changes applied by this recommended action can be
/// reverted by User
/// </summary>
public bool? IsRevertableAction
{
get { return this._isRevertableAction; }
set { this._isRevertableAction = value; }
}
private DateTime _lastRefresh;
/// <summary>
/// Optional. Gets time when this Recommended Action was last refreshed.
/// </summary>
public DateTime LastRefresh
{
get { return this._lastRefresh; }
set { this._lastRefresh = value; }
}
private IList<string> _linkedObjects;
/// <summary>
/// Optional. Gets the observed/actual impact info for this recommended
/// action E.g., Actual CPU gain, Actual Disk Space change
/// </summary>
public IList<string> LinkedObjects
{
get { return this._linkedObjects; }
set { this._linkedObjects = value; }
}
private IList<RecommendedActionImpactInfo> _observedImpact;
/// <summary>
/// Optional. Gets the observed/actual impact info for this recommended
/// action E.g., Actual CPU gain, Actual Disk Space change
/// </summary>
public IList<RecommendedActionImpactInfo> ObservedImpact
{
get { return this._observedImpact; }
set { this._observedImpact = value; }
}
private string _recommendationReason;
/// <summary>
/// Optional. Gets the reason for recommending this action. E.g.,
/// DuplicateIndex
/// </summary>
public string RecommendationReason
{
get { return this._recommendationReason; }
set { this._recommendationReason = value; }
}
private string _revertActionDuration;
/// <summary>
/// Optional. Gets the time taken for reverting changes of this
/// recommended action on user resource. E.g., Time taken for dropping
/// the created index.
/// </summary>
public string RevertActionDuration
{
get { return this._revertActionDuration; }
set { this._revertActionDuration = value; }
}
private string _revertActionInitiatedBy;
/// <summary>
/// Optional. Gets if approval for reverting this recommended action is
/// given by User/System.
/// </summary>
public string RevertActionInitiatedBy
{
get { return this._revertActionInitiatedBy; }
set { this._revertActionInitiatedBy = value; }
}
private System.DateTime? _revertActionInitiatedTime;
/// <summary>
/// Optional. Gets the time when this recommended action is approved
/// for revert
/// </summary>
public System.DateTime? RevertActionInitiatedTime
{
get { return this._revertActionInitiatedTime; }
set { this._revertActionInitiatedTime = value; }
}
private System.DateTime? _revertActionStartTime;
/// <summary>
/// Optional. Gets the time when system started reverting changes of
/// this recommended action on user resource. E.g., Time when Index
/// drop is executed.
/// </summary>
public System.DateTime? RevertActionStartTime
{
get { return this._revertActionStartTime; }
set { this._revertActionStartTime = value; }
}
private int _score;
/// <summary>
/// Optional. Gets the impact of this recommended actions. Possible
/// values are 1 - Low impact, 2 - Medium Impact and 3 - High Impact
/// </summary>
public int Score
{
get { return this._score; }
set { this._score = value; }
}
private RecommendedActionStateInfo _state;
/// <summary>
/// Optional. Gets the info of the state the Recommended Action is in.
/// </summary>
public RecommendedActionStateInfo State
{
get { return this._state; }
set { this._state = value; }
}
private IList<RecommendedActionMetricInfo> _timeSeries;
/// <summary>
/// Optional. Gets the time series info of metrics for this recommended
/// action E.g., CPU time series
/// </summary>
public IList<RecommendedActionMetricInfo> TimeSeries
{
get { return this._timeSeries; }
set { this._timeSeries = value; }
}
private DateTime _validSince;
/// <summary>
/// Optional. Gets the time since when this Recommended action is valid.
/// </summary>
public DateTime ValidSince
{
get { return this._validSince; }
set { this._validSince = value; }
}
/// <summary>
/// Initializes a new instance of the RecommendedActionProperties class.
/// </summary>
public RecommendedActionProperties()
{
this.Details = new LazyDictionary<string, object>();
this.EstimatedImpact = new LazyList<RecommendedActionImpactInfo>();
this.LinkedObjects = new LazyList<string>();
this.ObservedImpact = new LazyList<RecommendedActionImpactInfo>();
this.TimeSeries = new LazyList<RecommendedActionMetricInfo>();
}
}
}
| |
// 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.Drawing
{
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Globalization;
[StructLayout(LayoutKind.Sequential)]
public struct CharacterRange
{
private int _first;
private int _length;
/// <summary>
/// Initializes a new instance of the <see cref='CharacterRange'/> class with the specifiedcoordinates.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public CharacterRange(int First, int Length)
{
_first = First;
_length = Length;
}
/// <summary>
/// Gets the First character position of this <see cref='CharacterRange'/>.
/// </summary>
public int First
{
get
{
return _first;
}
set
{
_first = value;
}
}
/// <summary>
/// Gets the Length of this <see cref='CharacterRange'/>.
/// </summary>
public int Length
{
get
{
return _length;
}
set
{
_length = value;
}
}
public override bool Equals(object obj)
{
if (obj.GetType() != typeof(CharacterRange))
return false;
CharacterRange cr = (CharacterRange)obj;
return ((_first == cr.First) && (_length == cr.Length));
}
public static bool operator ==(CharacterRange cr1, CharacterRange cr2)
{
return ((cr1.First == cr2.First) && (cr1.Length == cr2.Length));
}
public static bool operator !=(CharacterRange cr1, CharacterRange cr2)
{
return !(cr1 == cr2);
}
public override int GetHashCode()
{
return unchecked(_first << 8 + _length);
}
}
/// <summary>
/// Encapsulates text layout information (such as alignment and linespacing), display manipulations (such as
/// ellipsis insertion and national digit substitution) and OpenType features.
/// </summary>
public sealed class StringFormat : MarshalByRefObject, ICloneable, IDisposable
{
internal IntPtr nativeFormat;
private StringFormat(IntPtr format)
{
nativeFormat = format;
}
/// <summary>
/// Initializes a new instance of the <see cref='StringFormat'/> class.
/// </summary>
public StringFormat() : this(0, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='StringFormat'/> class with the specified <see cref='System.Drawing.StringFormatFlags'/>.
/// </summary>
public StringFormat(StringFormatFlags options) :
this(options, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='StringFormat'/> class with the specified
/// <see cref='System.Drawing.StringFormatFlags'/> and language.
/// </summary>
public StringFormat(StringFormatFlags options, int language)
{
int status = SafeNativeMethods.Gdip.GdipCreateStringFormat(options, language, out nativeFormat);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// Initializes a new instance of the <see cref='StringFormat'/> class from the specified
/// existing <see cref='System.Drawing.StringFormat'/>.
/// </summary>
public StringFormat(StringFormat format)
{
if (format == null)
{
throw new ArgumentNullException("format");
}
int status = SafeNativeMethods.Gdip.GdipCloneStringFormat(new HandleRef(format, format.nativeFormat), out nativeFormat);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// Cleans up Windows resources for this <see cref='StringFormat'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (nativeFormat != IntPtr.Zero)
{
try
{
#if DEBUG
int status =
#endif
SafeNativeMethods.Gdip.GdipDeleteStringFormat(new HandleRef(this, nativeFormat));
#if DEBUG
Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex)
{
if (ClientUtils.IsCriticalException(ex))
{
throw;
}
Debug.Fail("Exception thrown during Dispose: " + ex.ToString());
}
finally
{
nativeFormat = IntPtr.Zero;
}
}
}
/// <summary>
/// Creates an exact copy of this <see cref='StringFormat'/>.
/// </summary>
public object Clone()
{
IntPtr cloneFormat = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCloneStringFormat(new HandleRef(this, nativeFormat), out cloneFormat);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
StringFormat newCloneStringFormat = new StringFormat(cloneFormat);
return newCloneStringFormat;
}
/// <summary>
/// Gets or sets a <see cref='StringFormatFlags'/> that contains formatting information.
/// </summary>
public StringFormatFlags FormatFlags
{
get
{
StringFormatFlags format;
int status = SafeNativeMethods.Gdip.GdipGetStringFormatFlags(new HandleRef(this, nativeFormat), out format);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return format;
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetStringFormatFlags(new HandleRef(this, nativeFormat), value);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/// <summary>
/// Sets the measure of characters to the specified range.
/// </summary>
public void SetMeasurableCharacterRanges(CharacterRange[] ranges)
{
int status = SafeNativeMethods.Gdip.GdipSetStringFormatMeasurableCharacterRanges(new HandleRef(this, nativeFormat), ranges.Length, ranges);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
// For English, this is horizontal alignment
/// <summary>
/// Specifies text alignment information.
/// </summary>
public StringAlignment Alignment
{
get
{
StringAlignment alignment = 0;
int status = SafeNativeMethods.Gdip.GdipGetStringFormatAlign(new HandleRef(this, nativeFormat), out alignment);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return alignment;
}
set
{
if (value < StringAlignment.Near || value > StringAlignment.Far)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(StringAlignment));
}
int status = SafeNativeMethods.Gdip.GdipSetStringFormatAlign(new HandleRef(this, nativeFormat), value);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
// For English, this is vertical alignment
/// <summary>
/// Gets or sets the line alignment.
/// </summary>
public StringAlignment LineAlignment
{
get
{
StringAlignment alignment = 0;
int status = SafeNativeMethods.Gdip.GdipGetStringFormatLineAlign(new HandleRef(this, nativeFormat), out alignment);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return alignment;
}
set
{
if (value < 0 || value > StringAlignment.Far)
{
throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(StringAlignment));
}
int status = SafeNativeMethods.Gdip.GdipSetStringFormatLineAlign(new HandleRef(this, nativeFormat), value);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/// <summary>
/// Gets or sets the <see cref='HotkeyPrefix'/> for this <see cref='StringFormat'/> .
/// </summary>
public HotkeyPrefix HotkeyPrefix
{
get
{
HotkeyPrefix hotkeyPrefix;
int status = SafeNativeMethods.Gdip.GdipGetStringFormatHotkeyPrefix(new HandleRef(this, nativeFormat), out hotkeyPrefix);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return hotkeyPrefix;
}
set
{
if (value < HotkeyPrefix.None || value > HotkeyPrefix.Hide)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(HotkeyPrefix));
}
int status = SafeNativeMethods.Gdip.GdipSetStringFormatHotkeyPrefix(new HandleRef(this, nativeFormat), value);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/// <summary>
/// Sets tab stops for this <see cref='StringFormat'/>.
/// </summary>
public void SetTabStops(float firstTabOffset, float[] tabStops)
{
if (firstTabOffset < 0)
throw new ArgumentException(SR.Format(SR.InvalidArgument, "firstTabOffset", firstTabOffset));
int status = SafeNativeMethods.Gdip.GdipSetStringFormatTabStops(new HandleRef(this, nativeFormat), firstTabOffset, tabStops.Length, tabStops);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// Gets the tab stops for this <see cref='StringFormat'/>.
/// </summary>
public float[] GetTabStops(out float firstTabOffset)
{
int count = 0;
int status = SafeNativeMethods.Gdip.GdipGetStringFormatTabStopCount(new HandleRef(this, nativeFormat), out count);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
float[] tabStops = new float[count];
status = SafeNativeMethods.Gdip.GdipGetStringFormatTabStops(new HandleRef(this, nativeFormat), count, out firstTabOffset, tabStops);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return tabStops;
}
// String trimming. How to handle more text than can be displayed
// in the limits available.
/// <summary>
/// Gets or sets the <see cref='StringTrimming'/> for this <see cref='StringFormat'/>.
/// </summary>
public StringTrimming Trimming
{
get
{
StringTrimming trimming;
int status = SafeNativeMethods.Gdip.GdipGetStringFormatTrimming(new HandleRef(this, nativeFormat), out trimming);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return trimming;
}
set
{
if (value < StringTrimming.None || value > StringTrimming.EllipsisPath)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(StringTrimming));
}
int status = SafeNativeMethods.Gdip.GdipSetStringFormatTrimming(new HandleRef(this, nativeFormat), value);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/// <summary>
/// Gets a generic default <see cref='StringFormat'/>.
/// Remarks from MSDN: A generic, default StringFormat object has the following characteristics:
/// - No string format flags are set.
/// - Character alignment and line alignment are set to StringAlignmentNear.
/// - Language ID is set to neutral language, which means that the current language associated with the calling thread is used.
/// - String digit substitution is set to StringDigitSubstituteUser.
/// - Hot key prefix is set to HotkeyPrefixNone.
/// - Number of tab stops is set to zero.
/// - String trimming is set to StringTrimmingCharacter.
/// </summary>
public static StringFormat GenericDefault
{
get
{
IntPtr format;
int status = SafeNativeMethods.Gdip.GdipStringFormatGetGenericDefault(out format);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return new StringFormat(format);
}
}
/// <summary>
/// Gets a generic typographic <see cref='StringFormat'/>.
/// Remarks from MSDN: A generic, typographic StringFormat object has the following characteristics:
/// - String format flags StringFormatFlagsLineLimit, StringFormatFlagsNoClip, and StringFormatFlagsNoFitBlackBox are set.
/// - Character alignment and line alignment are set to StringAlignmentNear.
/// - Language ID is set to neutral language, which means that the current language associated with the calling thread is used.
/// - String digit substitution is set to StringDigitSubstituteUser.
/// - Hot key prefix is set to HotkeyPrefixNone.
/// - Number of tab stops is set to zero.
/// - String trimming is set to StringTrimmingNone.
/// </summary>
public static StringFormat GenericTypographic
{
get
{
IntPtr format;
int status = SafeNativeMethods.Gdip.GdipStringFormatGetGenericTypographic(out format);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return new StringFormat(format);
}
}
public void SetDigitSubstitution(int language, StringDigitSubstitute substitute)
{
int status = SafeNativeMethods.Gdip.GdipSetStringFormatDigitSubstitution(new HandleRef(this, nativeFormat), language, substitute);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// Gets the <see cref='StringDigitSubstitute'/> for this <see cref='StringFormat'/>.
/// </summary>
public StringDigitSubstitute DigitSubstitutionMethod
{
get
{
StringDigitSubstitute digitSubstitute;
int lang = 0;
int status = SafeNativeMethods.Gdip.GdipGetStringFormatDigitSubstitution(new HandleRef(this, nativeFormat), out lang, out digitSubstitute);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return digitSubstitute;
}
}
/// <summary>
/// Gets the language of <see cref='StringDigitSubstitute'/> for this <see cref='StringFormat'/>.
/// </summary>
public int DigitSubstitutionLanguage
{
get
{
StringDigitSubstitute digitSubstitute;
int language = 0;
int status = SafeNativeMethods.Gdip.GdipGetStringFormatDigitSubstitution(new HandleRef(this, nativeFormat), out language, out digitSubstitute);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return language;
}
}
/// <summary>
/// Cleans up Windows resources for this <see cref='StringFormat'/>.
/// </summary>
~StringFormat()
{
Dispose(false);
}
/// <summary>
/// Converts this <see cref='StringFormat'/> to a human-readable string.
/// </summary>
public override string ToString()
{
return "[StringFormat, FormatFlags=" + FormatFlags.ToString() + "]";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System
{
public static class Console
{
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
private static readonly object InternalSyncObject = new object(); // for synchronizing changing of Console's static fields
private static TextReader _in;
private static TextWriter _out, _error;
private static ConsoleCancelEventHandler _cancelCallbacks;
private static ConsolePal.ControlCHandlerRegistrar _registrar;
internal static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class
{
lock (InternalSyncObject)
{
T result = Volatile.Read(ref field);
if (result == null)
{
result = initializer();
Volatile.Write(ref field, result);
}
return result;
}
}
public static TextReader In
{
get
{
return Volatile.Read(ref _in) ?? EnsureInitialized(ref _in, () =>
{
return ConsolePal.GetOrCreateReader();
});
}
}
public static bool KeyAvailable
{
get
{
if (IsInputRedirected)
{
throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile);
}
return ConsolePal.KeyAvailable;
}
}
public static ConsoleKeyInfo ReadKey()
{
return ConsolePal.ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept)
{
return ConsolePal.ReadKey(intercept);
}
public static TextWriter Out
{
get { return Volatile.Read(ref _out) ?? EnsureInitialized(ref _out, () => CreateOutputWriter(OpenStandardOutput())); }
}
public static TextWriter Error
{
get { return Volatile.Read(ref _error) ?? EnsureInitialized(ref _error, () => CreateOutputWriter(OpenStandardError())); }
}
private static TextWriter CreateOutputWriter(Stream outputStream)
{
return SyncTextWriter.GetSynchronizedTextWriter(outputStream == Stream.Null ?
StreamWriter.Null :
new StreamWriter(
stream: outputStream,
encoding: ConsolePal.OutputEncoding,
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true) { AutoFlush = true });
}
private static StrongBox<bool> _isStdInRedirected;
private static StrongBox<bool> _isStdOutRedirected;
private static StrongBox<bool> _isStdErrRedirected;
public static bool IsInputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdInRedirected) ??
EnsureInitialized(ref _isStdInRedirected, () => new StrongBox<bool>(ConsolePal.IsInputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsOutputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdOutRedirected) ??
EnsureInitialized(ref _isStdOutRedirected, () => new StrongBox<bool>(ConsolePal.IsOutputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsErrorRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdErrRedirected) ??
EnsureInitialized(ref _isStdErrRedirected, () => new StrongBox<bool>(ConsolePal.IsErrorRedirectedCore()));
return redirected.Value;
}
}
public static ConsoleColor BackgroundColor
{
get { return ConsolePal.BackgroundColor; }
set { ConsolePal.BackgroundColor = value; }
}
public static ConsoleColor ForegroundColor
{
get { return ConsolePal.ForegroundColor; }
set { ConsolePal.ForegroundColor = value; }
}
public static void ResetColor()
{
ConsolePal.ResetColor();
}
public static int BufferWidth
{
get { return ConsolePal.BufferWidth; }
set { ConsolePal.BufferWidth = value; }
}
public static int BufferHeight
{
get { return ConsolePal.BufferHeight; }
set { ConsolePal.BufferHeight = value; }
}
public static int WindowLeft
{
get { return ConsolePal.WindowLeft; }
set { ConsolePal.WindowLeft = value; }
}
public static int WindowTop
{
get { return ConsolePal.WindowTop; }
set { ConsolePal.WindowTop = value; }
}
public static int WindowWidth
{
get
{
return ConsolePal.WindowWidth;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException("value", value, SR.ArgumentOutOfRange_NeedPosNum);
}
ConsolePal.WindowWidth = value;
}
}
public static int WindowHeight
{
get
{
return ConsolePal.WindowHeight;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException("value", value, SR.ArgumentOutOfRange_NeedPosNum);
}
ConsolePal.WindowHeight = value;
}
}
public static bool CursorVisible
{
get { return ConsolePal.CursorVisible; }
set { ConsolePal.CursorVisible = value; }
}
public static int CursorLeft
{
get { return ConsolePal.CursorLeft; }
set { SetCursorPosition(value, CursorTop); }
}
public static int CursorTop
{
get { return ConsolePal.CursorTop; }
set { SetCursorPosition(CursorLeft, value); }
}
private const int MaxConsoleTitleLength = 24500; // same value as in .NET Framework
public static string Title
{
get { return ConsolePal.Title; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.Length > MaxConsoleTitleLength)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_ConsoleTitleTooLong);
}
ConsolePal.Title = value;
}
}
public static void Beep()
{
ConsolePal.Beep();
}
public static void Clear()
{
ConsolePal.Clear();
}
public static void SetCursorPosition(int left, int top)
{
// Basic argument validation. The PAL implementation may provide further validation.
if (left < 0 || left >= short.MaxValue)
throw new ArgumentOutOfRangeException("left", left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (top < 0 || top >= short.MaxValue)
throw new ArgumentOutOfRangeException("top", top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
ConsolePal.SetCursorPosition(left, top);
}
public static event ConsoleCancelEventHandler CancelKeyPress
{
add
{
lock (InternalSyncObject)
{
_cancelCallbacks += value;
// If we haven't registered our control-C handler, do it.
if (_registrar == null)
{
_registrar = new ConsolePal.ControlCHandlerRegistrar();
_registrar.Register();
}
}
}
remove
{
lock (InternalSyncObject)
{
_cancelCallbacks -= value;
if (_registrar != null && _cancelCallbacks == null)
{
_registrar.Unregister();
_registrar = null;
}
}
}
}
public static Stream OpenStandardInput()
{
return ConsolePal.OpenStandardInput();
}
public static Stream OpenStandardOutput()
{
return ConsolePal.OpenStandardOutput();
}
public static Stream OpenStandardError()
{
return ConsolePal.OpenStandardError();
}
public static void SetIn(TextReader newIn)
{
CheckNonNull(newIn, "newIn");
newIn = SyncTextReader.GetSynchronizedTextReader(newIn);
lock (InternalSyncObject) { _in = newIn; }
}
public static void SetOut(TextWriter newOut)
{
CheckNonNull(newOut, "newOut");
newOut = SyncTextWriter.GetSynchronizedTextWriter(newOut);
lock (InternalSyncObject) { _out = newOut; }
}
public static void SetError(TextWriter newError)
{
CheckNonNull(newError, "newError");
newError = SyncTextWriter.GetSynchronizedTextWriter(newError);
lock (InternalSyncObject) { _error = newError; }
}
private static void CheckNonNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException(paramName);
}
//
// Give a hint to the code generator to not inline the common console methods. The console methods are
// not performance critical. It is unnecessary code bloat to have them inlined.
//
// Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out
// the inlined console writelines from them.
//
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int Read()
{
return In.Read();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static String ReadLine()
{
return In.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine()
{
Out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer)
{
Out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer, int index, int count)
{
Out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(decimal value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(Object value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0)
{
Out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1)
{
Out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg);
else
Out.WriteLine(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0)
{
Out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1)
{
Out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1, Object arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg);
else
Out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(bool value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer)
{
Out.Write(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer, int index, int count)
{
Out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(double value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(decimal value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(float value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(int value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(uint value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(long value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(ulong value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(Object value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String value)
{
Out.Write(value);
}
private sealed class ControlCDelegateData
{
private readonly ConsoleSpecialKey _controlKey;
private readonly ConsoleCancelEventHandler _cancelCallbacks;
internal bool Cancel;
internal bool DelegateStarted;
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks)
{
_controlKey = controlKey;
_cancelCallbacks = cancelCallbacks;
}
// This is the worker delegate that is called on the Threadpool thread to fire the actual events. It sets the DelegateStarted flag so
// the thread that queued the work to the threadpool knows it has started (since it does not want to block indefinitely on the task
// to start).
internal void HandleBreakEvent()
{
DelegateStarted = true;
var args = new ConsoleCancelEventArgs(_controlKey);
_cancelCallbacks(null, args);
Cancel = args.Cancel;
}
}
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey)
{
// The thread that this gets called back on has a very small stack on some systems. There is
// not enough space to handle a managed exception being caught and thrown. So, run a task
// on the threadpool for the actual event callback.
// To avoid the race condition between remove handler and raising the event
ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks;
if (cancelCallbacks == null)
{
return false;
}
var delegateData = new ControlCDelegateData(controlKey, cancelCallbacks);
Task callBackTask = Task.Factory.StartNew(
d => ((ControlCDelegateData)d).HandleBreakEvent(),
delegateData,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Block until the delegate is done. We need to be robust in the face of the task not executing
// but we also want to get control back immediately after it is done and we don't want to give the
// handler a fixed time limit in case it needs to display UI. Wait on the task twice, once with a
// timout and a second time without if we are sure that the handler actually started.
TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds
callBackTask.Wait(controlCWaitTime);
if (!delegateData.DelegateStarted)
{
Debug.Assert(false, "The task to execute the handler did not start within 30 seconds.");
return false;
}
callBackTask.Wait();
return delegateData.Cancel;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using DummyOrm.Dynamix.Impl;
using DummyOrm.Meta;
using DummyOrm.Sql.Command;
namespace DummyOrm.Db.Impl
{
public class DbImpl : IDb, ICommandExecutor
{
private IDbTransaction _tran;
private readonly IDbConnection _conn;
private readonly IDbMeta _meta;
protected internal DbImpl(IDbMeta meta)
{
_meta = meta;
_conn = meta.DbProvider.CreateConnection();
_conn.Open();
}
public virtual void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
{
if (_tran == null)
{
_tran = _conn.BeginTransaction(isolationLevel);
}
}
public virtual void Commit()
{
_tran?.Commit();
}
public virtual void Rollback()
{
_tran?.Rollback();
}
public virtual void Insert<T>(T entity) where T : class, new()
{
var cmd = SimpleCmd<T>().BuildInsertCommand(entity);
var id = ExecuteScalar(cmd);
if (id == null)
{
return;
}
var tableMeta = _meta.GetTable<T>();
tableMeta.IdColumn.GetterSetter.Set(entity, id);
}
public virtual void Update<T>(T entity) where T : class, new()
{
var cmd = SimpleCmd<T>().BuildUpdateCommand(entity);
ExecuteNonQuery(cmd);
}
public virtual void Delete<T>(T entity) where T : class, new()
{
var cmd = SimpleCmd<T>().BuildDeleteCommand(entity);
ExecuteNonQuery(cmd);
}
public virtual void DeleteMany<T>(Expression<Func<T, bool>> filter) where T : class, new()
{
var builder = _meta.DbProvider.CreateDeleteManyCommandBuilder(_meta);
var cmd = builder.Build(filter);
ExecuteNonQuery(cmd);
}
public virtual T GetById<T>(object id) where T : class, new()
{
var cmd = SimpleCmd<T>().BuildGetByIdCommand(id);
using (var reader = ExecuteReaderInternal(cmd))
{
if (!reader.Read())
{
return null;
}
var deserializer = PocoDeserializer.GetDefault<T>();
return deserializer.Deserialize(reader) as T;
}
}
public virtual IQuery<T> Select<T>() where T : class, new()
{
return new QueryImpl<T>(_meta, this);
}
public virtual IList<T> ExecuteQuery<T>(Command selectCommand) where T : class, new()
{
using (var reader = ExecuteReaderInternal(selectCommand))
{
var deserializer = PocoDeserializer.GetDefault<T>();
var list = new List<T>();
while (reader.Read())
{
var entity = (T)deserializer.Deserialize(reader);
list.Add(entity);
}
return list;
}
}
public virtual int ExecuteNonQuery(Command cmd)
{
using (var dbCmd = CreateCommand(cmd))
{
return dbCmd.ExecuteNonQuery();
}
}
public virtual object ExecuteScalar(Command cmd)
{
using (var dbCmd = CreateCommand(cmd))
{
return dbCmd.ExecuteScalar();
}
}
public virtual void Load<T, TProp>(IList<T> entities, Expression<Func<T, TProp>> propExp, Expression<Func<TProp, object>> includeProps = null)
where T : class, new()
where TProp : class, new()
{
var colMeta = _meta.GetColumn(propExp);
colMeta.Loader.Load(entities, this, includeProps);
}
public virtual void LoadMany<T, TProp>(IList<T> entities, Expression<Func<T, IList<TProp>>> listExp, Expression<Func<TProp, object>> includeProps = null)
where T : class, new()
where TProp : class, new()
{
var assoc = _meta.GetAssociation(listExp);
assoc.Loader.Load(entities, this, includeProps);
}
public virtual void Dispose()
{
_conn.Dispose();
_tran?.Dispose();
}
IDataReader ICommandExecutor.ExecuteReader(Command cmd)
{
return ExecuteReaderInternal(cmd);
}
int ICommandExecutor.ExecuteNonQuery(Command cmd)
{
return ExecuteNonQuery(cmd);
}
object ICommandExecutor.ExecuteScalar(Command cmd)
{
return ExecuteScalar(cmd);
}
private ISimpleCommandBuilder SimpleCmd<T>() where T : class, new()
{
return _meta.GetTable<T>().SimpleCommandBuilder;
}
private IDbCommand CreateCommand(Command cmd)
{
var dbCmd = _conn.CreateCommand();
dbCmd.Transaction = _tran;
dbCmd.CommandText = cmd.CommandText;
dbCmd.CommandType = cmd.Type;
foreach (var sqlParameter in cmd.Parameters)
{
var param = dbCmd.CreateParameter();
var paramMeta = sqlParameter.Value.ParameterMeta;
param.ParameterName = sqlParameter.Key;
param.Value = sqlParameter.Value.Value ?? DBNull.Value;
param.DbType = paramMeta.DbType;
param.Size = paramMeta.Size;
param.Scale = paramMeta.Scale;
param.Precision = paramMeta.Precision;
dbCmd.Parameters.Add(param);
}
#if DEBUG
Console.WriteLine(dbCmd.CommandText);
//foreach (var param in dbCmd.Parameters.Cast<IDbDataParameter>())
//{
// Console.WriteLine("{0}: {1}", param.ParameterName, param.Value);
//}
#endif
return dbCmd;
}
private IDataReader ExecuteReaderInternal(Command cmd)
{
using (var dbCmd = CreateCommand(cmd))
{
return dbCmd.ExecuteReader();
}
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.MathUtil.RBF;
using Encog.Util;
namespace Encog.Neural.RBF.Training
{
/// <summary>
/// Perform a SVD decomp on a matrix.
/// Contributed to Encog By M.Fletcher and M.Dean University of Cambridge, Dept.
/// of Physics, UK
/// </summary>
///
public class SVD
{
/// <summary>
/// Perform a SVD fit.
/// </summary>
/// <param name="x">The X matrix.</param>
/// <param name="y">The Y matrix.</param>
/// <param name="a">The A matrix.</param>
/// <param name="funcs">The RBF functions.</param>
/// <returns>The fit.</returns>
public static double Svdfit(double[][] x, double[][] y, double[][] a,
IRadialBasisFunction[] funcs)
{
int i, j, k;
double wmax, tmp, thresh, sum, TOL = 1e-13d;
//Allocated memory for svd matrices
double[][] u = EngineArray.AllocateDouble2D(x.Length, funcs.Length);
double[][] v = EngineArray.AllocateDouble2D(funcs.Length, funcs.Length);
var w = new double[funcs.Length];
//Fill input matrix with values based on fitting functions and input coordinates
for (i = 0; i < x.Length; i++)
{
for (j = 0; j < funcs.Length; j++)
u[i][j] = funcs[j].Calculate(x[i]);
}
//Perform decomposition
Svdcmp(u, w, v);
//Check for w values that are close to zero and replace them with zeros such that they are ignored in backsub
wmax = 0;
for (j = 0; j < funcs.Length; j++)
if (w[j] > wmax)
wmax = w[j];
thresh = TOL*wmax;
for (j = 0; j < funcs.Length; j++)
if (w[j] < thresh)
w[j] = 0;
//Perform back substitution to get result
Svdbksb(u, w, v, y, a);
//Calculate chi squared for the fit
double chisq = 0;
for (k = 0; k < y[0].Length; k++)
{
for (i = 0; i < y.Length; i++)
{
sum = 0.0d;
for (j = 0; j < funcs.Length; j++)
sum += a[j][k]*funcs[j].Calculate(x[i]);
tmp = (y[i][k] - sum);
chisq += tmp*tmp;
}
}
return Math.Sqrt(chisq/(y.Length*y[0].Length));
}
public static void Svdbksb(double[][] u, double[] w, double[][] v,
double[][] b, double[][] x)
{
int jj, j, i, m, n, k;
double s;
m = u.Length;
n = u[0].Length;
var temp = new double[n];
for (k = 0; k < b[0].Length; k++)
{
for (j = 0; j < n; j++)
{
s = 0;
if (w[j] != 0)
{
for (i = 0; i < m; i++)
s += u[i][j]*b[i][k];
s /= w[j];
}
temp[j] = s;
}
for (j = 0; j < n; j++)
{
s = 0;
for (jj = 0; jj < n; jj++)
s += v[j][jj]*temp[jj];
x[j][k] = s;
}
}
}
/// <summary>
/// Given a matrix a[1..m][1..n], this routine computes its singular value
/// decomposition, A = U.W.VT. The matrix U replaces a on output. The diagonal
/// matrix of singular values W is output as a vector w[1..n]. The matrix V (not
/// the transpose VT) is output as v[1..n][1..n].
/// </summary>
/// <param name="a"></param>
/// <param name="w"></param>
/// <param name="v"></param>
public static void Svdcmp(double[][] a, double[] w, double[][] v)
{
bool flag;
int i, its, j, jj, k, l = 0, nm = 0;
double anorm, c, f, g, h, s, scale, x, y, z;
int m = a.Length;
int n = a[0].Length;
var rv1 = new double[n];
g = scale = anorm = 0.0d;
for (i = 0; i < n; i++)
{
l = i + 2;
rv1[i] = scale*g;
g = s = scale = 0.0d;
if (i < m)
{
for (k = i; k < m; k++)
scale += Math.Abs(a[k][i]);
if (scale != 0.0d)
{
for (k = i; k < m; k++)
{
a[k][i] /= scale;
s += a[k][i]*a[k][i];
}
f = a[i][i];
g = -SIGN(Math.Sqrt(s), f);
h = f*g - s;
a[i][i] = f - g;
for (j = l - 1; j < n; j++)
{
for (s = 0.0d, k = i; k < m; k++)
s += a[k][i]*a[k][j];
f = s/h;
for (k = i; k < m; k++)
a[k][j] += f*a[k][i];
}
for (k = i; k < m; k++)
a[k][i] *= scale;
}
}
w[i] = scale*g;
g = s = scale = 0.0d;
if (i + 1 <= m && i + 1 != n)
{
for (k = l - 1; k < n; k++)
scale += Math.Abs(a[i][k]);
if (scale != 0.0d)
{
for (k = l - 1; k < n; k++)
{
a[i][k] /= scale;
s += a[i][k]*a[i][k];
}
f = a[i][l - 1];
g = -SIGN(Math.Sqrt(s), f);
h = f*g - s;
a[i][l - 1] = f - g;
for (k = l - 1; k < n; k++)
rv1[k] = a[i][k]/h;
for (j = l - 1; j < m; j++)
{
for (s = 0.0d, k = l - 1; k < n; k++)
s += a[j][k]*a[i][k];
for (k = l - 1; k < n; k++)
a[j][k] += s*rv1[k];
}
for (k = l - 1; k < n; k++)
a[i][k] *= scale;
}
}
anorm = MAX(anorm, (Math.Abs(w[i]) + Math.Abs(rv1[i])));
}
for (i = n - 1; i >= 0; i--)
{
if (i < n - 1)
{
if (g != 0.0d)
{
for (j = l; j < n; j++)
v[j][i] = (a[i][j]/a[i][l])/g;
for (j = l; j < n; j++)
{
for (s = 0.0d, k = l; k < n; k++)
s += a[i][k]*v[k][j];
for (k = l; k < n; k++)
v[k][j] += s*v[k][i];
}
}
for (j = l; j < n; j++)
v[i][j] = v[j][i] = 0.0d;
}
v[i][i] = 1.0d;
g = rv1[i];
l = i;
}
for (i = MIN(m, n) - 1; i >= 0; i--)
{
l = i + 1;
g = w[i];
for (j = l; j < n; j++)
a[i][j] = 0.0d;
if (g != 0.0d)
{
g = 1.0d/g;
for (j = l; j < n; j++)
{
for (s = 0.0d, k = l; k < m; k++)
s += a[k][i]*a[k][j];
f = (s/a[i][i])*g;
for (k = i; k < m; k++)
a[k][j] += f*a[k][i];
}
for (j = i; j < m; j++)
a[j][i] *= g;
}
else
for (j = i; j < m; j++)
a[j][i] = 0.0d;
++a[i][i];
}
for (k = n - 1; k >= 0; k--)
{
for (its = 0; its < 30; its++)
{
flag = true;
for (l = k; l >= 0; l--)
{
nm = l - 1;
if (Math.Abs(rv1[l]) + anorm == anorm)
{
flag = false;
break;
}
if (Math.Abs(w[nm]) + anorm == anorm)
break;
}
if (flag)
{
c = 0.0d;
s = 1.0d;
for (i = l; i < k + 1; i++)
{
f = s*rv1[i];
rv1[i] = c*rv1[i];
if (Math.Abs(f) + anorm == anorm)
break;
g = w[i];
h = Pythag(f, g);
w[i] = h;
h = 1.0d/h;
c = g*h;
s = -f*h;
for (j = 0; j < m; j++)
{
y = a[j][nm];
z = a[j][i];
a[j][nm] = y*c + z*s;
a[j][i] = z*c - y*s;
}
}
}
z = w[k];
if (l == k)
{
if (z < 0.0d)
{
w[k] = -z;
for (j = 0; j < n; j++)
v[j][k] = -v[j][k];
}
break;
}
if (its == 29)
{
// Debug.Print("no convergence in 30 svdcmp iterations");
}
x = w[l];
nm = k - 1;
y = w[nm];
g = rv1[nm];
h = rv1[k];
f = ((y - z)*(y + z) + (g - h)*(g + h))/(2.0d*h*y);
g = Pythag(f, 1.0d);
f = ((x - z)*(x + z) + h*((y/(f + SIGN(g, f))) - h))/x;
c = s = 1.0d;
for (j = l; j <= nm; j++)
{
i = j + 1;
g = rv1[i];
y = w[i];
h = s*g;
g = c*g;
z = Pythag(f, h);
rv1[j] = z;
c = f/z;
s = h/z;
f = x*c + g*s;
g = g*c - x*s;
h = y*s;
y *= c;
for (jj = 0; jj < n; jj++)
{
x = v[jj][j];
z = v[jj][i];
v[jj][j] = x*c + z*s;
v[jj][i] = z*c - x*s;
}
z = Pythag(f, h);
w[j] = z;
if (z != 0)
{
z = 1.0d/z;
c = f*z;
s = h*z;
}
f = c*g + s*y;
x = c*y - s*g;
for (jj = 0; jj < m; jj++)
{
y = a[jj][j];
z = a[jj][i];
a[jj][j] = y*c + z*s;
a[jj][i] = z*c - y*s;
}
}
rv1[l] = 0.0d;
rv1[k] = f;
w[k] = x;
}
}
}
/// <summary>
/// Take the min of two numbers.
/// </summary>
/// <param name="m">First number.</param>
/// <param name="n">Second number.</param>
/// <returns>The min.</returns>
public static int MIN(int m, int n)
{
return (m < n) ? m : n;
}
/// <summary>
/// Take the max of two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The max.</returns>
public static double MAX(double a, double b)
{
return (a > b) ? a : b;
}
/// <summary>
/// Take the sign of two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns></returns>
public static double SIGN(double a, double b)
{
return (((b) >= 0.0d) ? Math.Abs(a) : -Math.Abs(a));
}
/// <summary>
/// Compute the pythag distance of two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The result.</returns>
public static double Pythag(double a, double b)
{
double absa, absb;
absa = Math.Abs(a);
absb = Math.Abs(b);
if (absa > absb)
return absa*Math.Sqrt(1.0d + (absb/absa)*(absb/absa));
else
return ((absb == 0.0d)
? 0.0d
: absb
*Math.Sqrt(1.0d + (absa/absb)*(absa/absb)));
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.UserModel
{
using System;
using System.IO;
using System.Collections;
using TestCases.HSSF;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
using NPOI.SS.Formula;
using NPOI.Util;
using NPOI.HSSF.UserModel;
using NUnit.Framework;
using NPOI.DDF;
using TestCases.SS.UserModel;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Util;
using System.Collections.Generic;
/**
*
*/
[TestFixture]
public class TestHSSFWorkbook:BaseTestWorkbook
{
public TestHSSFWorkbook()
: base(HSSFITestDataProvider.Instance)
{ }
/**
* gives test code access to the {@link InternalWorkbook} within {@link HSSFWorkbook}
*/
public static InternalWorkbook GetInternalWorkbook(HSSFWorkbook wb)
{
return wb.Workbook;
}
private static HSSFWorkbook OpenSample(String sampleFileName)
{
return HSSFTestDataSamples.OpenSampleWorkbook(sampleFileName);
}
[Test]
public void TestCaseInsensitiveNames()
{
HSSFWorkbook b = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet originalSheet = b.CreateSheet("Sheet1");
NPOI.SS.UserModel.ISheet fetchedSheet = b.GetSheet("sheet1");
if (fetchedSheet == null)
{
throw new AssertionException("Identified bug 44892");
}
Assert.AreEqual(originalSheet, fetchedSheet);
try
{
b.CreateSheet("sHeeT1");
Assert.Fail("should have thrown exceptiuon due to duplicate sheet name");
}
catch (ArgumentException e)
{
// expected during successful Test
Assert.AreEqual("The workbook already contains a sheet of this name", e.Message);
}
}
[Test]
public void TestDuplicateNames()
{
HSSFWorkbook b = new HSSFWorkbook();
b.CreateSheet("Sheet1");
b.CreateSheet();
b.CreateSheet("name1");
try
{
b.CreateSheet("name1");
Assert.Fail();
}
catch (ArgumentException)// pass
{
}
b.CreateSheet();
try
{
b.SetSheetName(3, "name1");
Assert.Fail();
}
catch (ArgumentException)// pass
{
}
try
{
b.SetSheetName(3, "name1");
Assert.Fail();
}
catch (ArgumentException)// pass
{
}
b.SetSheetName(3, "name2");
b.SetSheetName(3, "name2");
b.SetSheetName(3, "name2");
HSSFWorkbook c = new HSSFWorkbook();
c.CreateSheet("Sheet1");
c.CreateSheet("Sheet2");
c.CreateSheet("Sheet3");
c.CreateSheet("Sheet4");
}
[Test]
public void TestWindowOneDefaults()
{
HSSFWorkbook b = new HSSFWorkbook();
try
{
Assert.AreEqual(b.ActiveSheetIndex, 0);
Assert.AreEqual(b.FirstVisibleTab, 0);
}
catch (NullReferenceException)
{
Assert.Fail("WindowOneRecord in Workbook is probably not initialized");
}
}
[Test]
public new void TestSheetSelection()
{
HSSFWorkbook b = new HSSFWorkbook();
b.CreateSheet("Sheet One");
b.CreateSheet("Sheet Two");
b.SetActiveSheet(1);
b.SetSelectedTab(1);
b.FirstVisibleTab = (1);
Assert.AreEqual(1, b.ActiveSheetIndex);
Assert.AreEqual(1, b.FirstVisibleTab);
}
[Test]
public void TestSheetClone()
{
// First up, try a simple file
HSSFWorkbook b = new HSSFWorkbook();
Assert.AreEqual(0, b.NumberOfSheets);
b.CreateSheet("Sheet One");
b.CreateSheet("Sheet Two");
Assert.AreEqual(2, b.NumberOfSheets);
b.CloneSheet(0);
Assert.AreEqual(3, b.NumberOfSheets);
// Now try a problem one with drawing records in it
b = OpenSample("SheetWithDrawing.xls");
Assert.AreEqual(1, b.NumberOfSheets);
b.CloneSheet(0);
Assert.AreEqual(2, b.NumberOfSheets);
}
[Test]
public void TestReadWriteWithCharts()
{
HSSFWorkbook b;
NPOI.SS.UserModel.ISheet s;
// Single chart, two sheets
b = OpenSample("44010-SingleChart.xls");
Assert.AreEqual(2, b.NumberOfSheets);
Assert.AreEqual("Graph2", b.GetSheetName(1));
s = b.GetSheetAt(1);
Assert.AreEqual(0, s.FirstRowNum);
Assert.AreEqual(8, s.LastRowNum);
// Has chart on 1st sheet??
// FIXME
Assert.IsNotNull(b.GetSheetAt(0).DrawingPatriarch);
Assert.IsNull(b.GetSheetAt(1).DrawingPatriarch);
Assert.IsFalse(((HSSFPatriarch)b.GetSheetAt(0).DrawingPatriarch).ContainsChart());
// We've now called DrawingPatriarch so
// everything will be all screwy
// So, start again
b = OpenSample("44010-SingleChart.xls");
b = WriteRead(b);
Assert.AreEqual(2, b.NumberOfSheets);
s = b.GetSheetAt(1);
Assert.AreEqual(0, s.FirstRowNum);
Assert.AreEqual(8, s.LastRowNum);
// Two charts, three sheets
b = OpenSample("44010-TwoCharts.xls");
Assert.AreEqual(3, b.NumberOfSheets);
s = b.GetSheetAt(1);
Assert.AreEqual(0, s.FirstRowNum);
Assert.AreEqual(8, s.LastRowNum);
s = b.GetSheetAt(2);
Assert.AreEqual(0, s.FirstRowNum);
Assert.AreEqual(8, s.LastRowNum);
// Has chart on 1st sheet??
// FIXME
Assert.IsNotNull(b.GetSheetAt(0).DrawingPatriarch);
Assert.IsNull(b.GetSheetAt(1).DrawingPatriarch);
Assert.IsNull(b.GetSheetAt(2).DrawingPatriarch);
Assert.IsFalse(((HSSFPatriarch)b.GetSheetAt(0).DrawingPatriarch).ContainsChart());
// We've now called DrawingPatriarch so
// everything will be all screwy
// So, start again
b = OpenSample("44010-TwoCharts.xls");
b = WriteRead(b);
Assert.AreEqual(3, b.NumberOfSheets);
s = b.GetSheetAt(1);
Assert.AreEqual(0, s.FirstRowNum);
Assert.AreEqual(8, s.LastRowNum);
s = b.GetSheetAt(2);
Assert.AreEqual(0, s.FirstRowNum);
Assert.AreEqual(8, s.LastRowNum);
}
private static HSSFWorkbook WriteRead(HSSFWorkbook b)
{
return HSSFTestDataSamples.WriteOutAndReadBack(b);
}
[Test]
public void TestSelectedSheet_bug44523()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet1 = wb.CreateSheet("Sheet1");
NPOI.SS.UserModel.ISheet sheet2 = wb.CreateSheet("Sheet2");
NPOI.SS.UserModel.ISheet sheet3 = wb.CreateSheet("Sheet3");
NPOI.SS.UserModel.ISheet sheet4 = wb.CreateSheet("Sheet4");
ConfirmActiveSelected(sheet1, true);
ConfirmActiveSelected(sheet2, false);
ConfirmActiveSelected(sheet3, false);
ConfirmActiveSelected(sheet4, false);
wb.SetSelectedTab(1);
// Demonstrate bug 44525:
// Well... not quite, since isActive + isSelected were also Added in the same bug fix
if (sheet1.IsSelected)
{
throw new AssertionException("Identified bug 44523 a");
}
wb.SetActiveSheet(1);
if (sheet1.IsActive)
{
throw new AssertionException("Identified bug 44523 b");
}
ConfirmActiveSelected(sheet1, false);
ConfirmActiveSelected(sheet2, true);
ConfirmActiveSelected(sheet3, false);
ConfirmActiveSelected(sheet4, false);
}
//public void TestSelectMultiple()
//{
// HSSFWorkbook wb = new HSSFWorkbook();
// NPOI.SS.UserModel.Sheet sheet1 = wb.CreateSheet("Sheet1");
// NPOI.SS.UserModel.Sheet sheet2 = wb.CreateSheet("Sheet2");
// NPOI.SS.UserModel.Sheet sheet3 = wb.CreateSheet("Sheet3");
// NPOI.SS.UserModel.Sheet sheet4 = wb.CreateSheet("Sheet4");
// NPOI.SS.UserModel.Sheet sheet5 = wb.CreateSheet("Sheet5");
// NPOI.SS.UserModel.Sheet sheet6 = wb.CreateSheet("Sheet6");
// wb.SetSelectedTabs(new int[] { 0, 2, 3 });
// Assert.AreEqual(true, sheet1.IsSelected);
// Assert.AreEqual(false, sheet2.IsSelected);
// Assert.AreEqual(true, sheet3.IsSelected);
// Assert.AreEqual(true, sheet4.IsSelected);
// Assert.AreEqual(false, sheet5.IsSelected);
// Assert.AreEqual(false, sheet6.IsSelected);
// wb.SetSelectedTabs(new int[] { 1, 3, 5 });
// Assert.AreEqual(false, sheet1.IsSelected);
// Assert.AreEqual(true, sheet2.IsSelected);
// Assert.AreEqual(false, sheet3.IsSelected);
// Assert.AreEqual(true, sheet4.IsSelected);
// Assert.AreEqual(false, sheet5.IsSelected);
// Assert.AreEqual(true, sheet6.IsSelected);
// Assert.AreEqual(true, sheet1.IsActive);
// Assert.AreEqual(false, sheet2.IsActive);
// Assert.AreEqual(true, sheet1.IsActive);
// Assert.AreEqual(false, sheet3.IsActive);
// wb.SetActiveSheet(2);
// Assert.AreEqual(false, sheet1.IsActive);
// Assert.AreEqual(true, sheet3.IsActive);
// if (false)
// { // helpful if viewing this workbook in excel:
// sheet1.CreateRow(0).CreateCell(0).SetCellValue(new HSSFRichTextString("Sheet1"));
// sheet2.CreateRow(0).CreateCell(0).SetCellValue(new HSSFRichTextString("Sheet2"));
// sheet3.CreateRow(0).CreateCell(0).SetCellValue(new HSSFRichTextString("Sheet3"));
// sheet4.CreateRow(0).CreateCell(0).SetCellValue(new HSSFRichTextString("Sheet4"));
// try
// {
// File fOut = TempFile.CreateTempFile("sheetMultiSelect", ".xls");
// FileOutputStream os = new FileOutputStream(fOut);
// wb.Write(os);
// os.Close();
// }
// catch (IOException e)
// {
// throw new RuntimeException(e);
// }
// }
//}
[Test]
public void TestActiveSheetAfterDelete_bug40414()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet0 = wb.CreateSheet("Sheet0");
NPOI.SS.UserModel.ISheet sheet1 = wb.CreateSheet("Sheet1");
NPOI.SS.UserModel.ISheet sheet2 = wb.CreateSheet("Sheet2");
NPOI.SS.UserModel.ISheet sheet3 = wb.CreateSheet("Sheet3");
NPOI.SS.UserModel.ISheet sheet4 = wb.CreateSheet("Sheet4");
// Confirm default activation/selection
ConfirmActiveSelected(sheet0, true);
ConfirmActiveSelected(sheet1, false);
ConfirmActiveSelected(sheet2, false);
ConfirmActiveSelected(sheet3, false);
ConfirmActiveSelected(sheet4, false);
wb.SetActiveSheet(3);
wb.SetSelectedTab(3);
ConfirmActiveSelected(sheet0, false);
ConfirmActiveSelected(sheet1, false);
ConfirmActiveSelected(sheet2, false);
ConfirmActiveSelected(sheet3, true);
ConfirmActiveSelected(sheet4, false);
wb.RemoveSheetAt(3);
// after removing the only active/selected sheet, another should be active/selected in its place
if (!sheet4.IsSelected)
{
throw new AssertionException("identified bug 40414 a");
}
if (!sheet4.IsActive)
{
throw new AssertionException("identified bug 40414 b");
}
ConfirmActiveSelected(sheet0, false);
ConfirmActiveSelected(sheet1, false);
ConfirmActiveSelected(sheet2, false);
ConfirmActiveSelected(sheet4, true);
sheet3 = sheet4; // re-align local vars in this Test case
// Some more cases of removing sheets
// Starting with a multiple selection, and different active sheet
wb.SetSelectedTabs(new int[] { 1, 3, });
wb.SetActiveSheet(2);
ConfirmActiveSelected(sheet0, false, false);
ConfirmActiveSelected(sheet1, false, true);
ConfirmActiveSelected(sheet2, true, false);
ConfirmActiveSelected(sheet3, false, true);
// removing a sheet that is not active, and not the only selected sheet
wb.RemoveSheetAt(3);
ConfirmActiveSelected(sheet0, false, false);
ConfirmActiveSelected(sheet1, false, true);
ConfirmActiveSelected(sheet2, true, false);
// removing the only selected sheet
wb.RemoveSheetAt(1);
ConfirmActiveSelected(sheet0, false, false);
ConfirmActiveSelected(sheet2, true, true);
// The last remaining sheet should always be active+selected
wb.RemoveSheetAt(1);
ConfirmActiveSelected(sheet0, true, true);
}
private static void ConfirmActiveSelected(NPOI.SS.UserModel.ISheet sheet, bool expected)
{
ConfirmActiveSelected(sheet, expected, expected);
}
private static void ConfirmActiveSelected(NPOI.SS.UserModel.ISheet sheet,
bool expectedActive, bool expectedSelected)
{
Assert.AreEqual(expectedActive, sheet.IsActive, "active");
Assert.AreEqual(expectedSelected, sheet.IsSelected, "selected");
}
/**
* If Sheet.GetSize() returns a different result to Sheet.serialize(), this will cause the BOF
* records to be written with invalid offset indexes. Excel does not like this, and such
* errors are particularly hard to track down. This Test ensures that HSSFWorkbook throws
* a specific exception as soon as the situation is detected. See bugzilla 45066
*/
[Test]
public void TestSheetSerializeSizeMisMatch_bug45066()
{
HSSFWorkbook wb = new HSSFWorkbook();
InternalSheet sheet = ((HSSFSheet)wb.CreateSheet("Sheet1")).Sheet;
IList sheetRecords = sheet.Records;
// one way (of many) to cause the discrepancy is with a badly behaved record:
sheetRecords.Add(new BadlyBehavedRecord());
// There is also much logic inside Sheet that (if buggy) might also cause the discrepancy
try
{
wb.GetBytes();
throw new AssertionException("Identified bug 45066 a");
}
catch (InvalidOperationException e)
{
// Expected badly behaved sheet record to cause exception
Assert.IsTrue(e.Message.StartsWith("Actual serialized sheet size"));
}
}
/**
* Checks that us and NPOI.SS.UserModel.Name play nicely with named ranges
* that point to deleted sheets
*/
[Test]
public void TestNamesToDeleteSheets()
{
HSSFWorkbook b = OpenSample("30978-deleted.xls");
Assert.AreEqual(3, b.NumberOfNames);
// Sheet 2 is deleted
Assert.AreEqual("Sheet1", b.GetSheetName(0));
Assert.AreEqual("Sheet3", b.GetSheetName(1));
Area3DPtg ptg;
NameRecord nr;
NPOI.SS.UserModel.IName n;
/* ======= Name pointing to deleted sheet ====== */
// First at low level
nr = b.Workbook.GetNameRecord(0);
Assert.AreEqual("On2", nr.NameText);
Assert.AreEqual(0, nr.SheetNumber);
Assert.AreEqual(1, nr.ExternSheetNumber);
Assert.AreEqual(1, nr.NameDefinition.Length);
ptg = (Area3DPtg)nr.NameDefinition[0];
Assert.AreEqual(1, ptg.ExternSheetIndex);
Assert.AreEqual(0, ptg.FirstColumn);
Assert.AreEqual(0, ptg.FirstRow);
Assert.AreEqual(0, ptg.LastColumn);
Assert.AreEqual(2, ptg.LastRow);
// Now at high level
n = b.GetNameAt(0);
Assert.AreEqual("On2", n.NameName);
Assert.AreEqual("", n.SheetName);
Assert.AreEqual("#REF!$A$1:$A$3", n.RefersToFormula);
/* ======= Name pointing to 1st sheet ====== */
// First at low level
nr = b.Workbook.GetNameRecord(1);
Assert.AreEqual("OnOne", nr.NameText);
Assert.AreEqual(0, nr.SheetNumber);
Assert.AreEqual(0, nr.ExternSheetNumber);
Assert.AreEqual(1, nr.NameDefinition.Length);
ptg = (Area3DPtg)nr.NameDefinition[0];
Assert.AreEqual(0, ptg.ExternSheetIndex);
Assert.AreEqual(0, ptg.FirstColumn);
Assert.AreEqual(2, ptg.FirstRow);
Assert.AreEqual(0, ptg.LastColumn);
Assert.AreEqual(3, ptg.LastRow);
// Now at high level
n = b.GetNameAt(1);
Assert.AreEqual("OnOne", n.NameName);
Assert.AreEqual("Sheet1", n.SheetName);
Assert.AreEqual("Sheet1!$A$3:$A$4", n.RefersToFormula);
/* ======= Name pointing to 3rd sheet ====== */
// First at low level
nr = b.Workbook.GetNameRecord(2);
Assert.AreEqual("OnSheet3", nr.NameText);
Assert.AreEqual(0, nr.SheetNumber);
Assert.AreEqual(2, nr.ExternSheetNumber);
Assert.AreEqual(1, nr.NameDefinition.Length);
ptg = (Area3DPtg)nr.NameDefinition[0];
Assert.AreEqual(2, ptg.ExternSheetIndex);
Assert.AreEqual(0, ptg.FirstColumn);
Assert.AreEqual(0, ptg.FirstRow);
Assert.AreEqual(0, ptg.LastColumn);
Assert.AreEqual(1, ptg.LastRow);
// Now at high level
n = b.GetNameAt(2);
Assert.AreEqual("OnSheet3", n.NameName);
Assert.AreEqual("Sheet3", n.SheetName);
Assert.AreEqual("Sheet3!$A$1:$A$2", n.RefersToFormula);
}
/**
* result returned by getRecordSize() differs from result returned by serialize()
*/
private class BadlyBehavedRecord : Record
{
public BadlyBehavedRecord()
{
//
}
public override short Sid
{
get
{
return unchecked((short)0x777);
}
}
public override int Serialize(int offset, byte[] data)
{
return 4;
}
public override int RecordSize
{
get
{
return 8;
}
}
}
/**
* The sample file provided with bug 45582 seems to have one extra byte after the EOFRecord
*/
[Test]
public void TestExtraDataAfterEOFRecord()
{
try
{
HSSFTestDataSamples.OpenSampleWorkbook("ex45582-22397.xls");
}
catch (RecordFormatException e)
{
if (e.InnerException is NPOI.Util.BufferUnderrunException)
{
throw new AssertionException("Identified bug 45582");
}
}
}
/**
* Test to make sure that NameRecord.SheetNumber is interpreted as a
* 1-based sheet tab index (not a 1-based extern sheet index)
*/
[Test]
public void TestFindBuiltInNameRecord()
{
// TestRRaC has multiple (3) built-in name records
// The second print titles name record has SheetNumber==4
HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("TestRRaC.xls");
NameRecord nr;
Assert.AreEqual(3, wb.Workbook.NumNames);
nr = wb.Workbook.GetNameRecord(2);
// TODO - render full row and full column refs properly
Assert.AreEqual("Sheet2!$A$1:$IV$1", HSSFFormulaParser.ToFormulaString(wb,nr.NameDefinition)); // 1:1
try
{
wb.GetSheetAt(3).RepeatingRows = (CellRangeAddress.ValueOf("9:12"));
wb.GetSheetAt(3).RepeatingColumns = (CellRangeAddress.ValueOf("E:F"));
}
catch (Exception e)
{
if (e.Message.Equals("Builtin (7) already exists for sheet (4)"))
{
// there was a problem in the code which locates the existing print titles name record
throw new Exception("Identified bug 45720b");
}
throw e;
}
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
Assert.AreEqual(3, wb.Workbook.NumNames);
nr = wb.Workbook.GetNameRecord(2);
Assert.AreEqual("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.ToFormulaString(wb,nr.NameDefinition)); // E:F,9:12
}
/**
* Test that the storage clsid property is preserved
*/
[Test]
public void Test47920()
{
POIFSFileSystem fs1 = new POIFSFileSystem(POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("47920.xls"));
IWorkbook wb = new HSSFWorkbook(fs1);
ClassID clsid1 = fs1.Root.StorageClsid;
MemoryStream out1 = new MemoryStream(4096);
wb.Write(out1);
byte[] bytes = out1.ToArray();
POIFSFileSystem fs2 = new POIFSFileSystem(new MemoryStream(bytes));
ClassID clsid2 = fs2.Root.StorageClsid;
Assert.IsTrue(clsid1.Equals(clsid2));
}
/**
* Tests that we can work with both {@link POIFSFileSystem}
* and {@link NPOIFSFileSystem}
*/
[Test]
public void TestDifferentPOIFS()
{
//throw new NotImplementedException("class NPOIFSFileSystem is not implemented");
// Open the two filesystems
DirectoryNode[] files = new DirectoryNode[2];
files[0] = (new POIFSFileSystem(HSSFTestDataSamples.OpenSampleFileStream("Simple.xls"))).Root;
files[1] = (new NPOIFSFileSystem(HSSFTestDataSamples.OpenSampleFileStream("Simple.xls"))).Root;
// Open without preserving nodes
foreach (DirectoryNode dir in files)
{
IWorkbook workbook = new HSSFWorkbook(dir, false);
ISheet sheet = workbook.GetSheetAt(0);
ICell cell = sheet.GetRow(0).GetCell(0);
Assert.AreEqual("replaceMe", cell.RichStringCellValue.String);
}
// Now re-check with preserving
foreach (DirectoryNode dir in files)
{
IWorkbook workbook = new HSSFWorkbook(dir, true);
ISheet sheet = workbook.GetSheetAt(0);
ICell cell = sheet.GetRow(0).GetCell(0);
Assert.AreEqual("replaceMe", cell.RichStringCellValue.String);
}
}
[Test]
public void TestWordDocEmbeddedInXls()
{
//throw new NotImplementedException("class NPOIFSFileSystem is not implemented");
// Open the two filesystems
DirectoryNode[] files = new DirectoryNode[2];
files[0] = (new POIFSFileSystem(HSSFTestDataSamples.OpenSampleFileStream("WithEmbeddedObjects.xls"))).Root;
files[1] = (new NPOIFSFileSystem(HSSFTestDataSamples.OpenSampleFileStream("WithEmbeddedObjects.xls"))).Root;
// Check the embedded parts
foreach (DirectoryNode root in files)
{
HSSFWorkbook hw = new HSSFWorkbook(root, true);
IList<HSSFObjectData> objects = hw.GetAllEmbeddedObjects();
bool found = false;
for (int i = 0; i < objects.Count; i++)
{
HSSFObjectData embeddedObject = objects[i];
if (embeddedObject.HasDirectoryEntry())
{
DirectoryEntry dir = embeddedObject.GetDirectory();
if (dir is DirectoryNode)
{
DirectoryNode dNode = (DirectoryNode)dir;
if (HasEntry(dNode, "WordDocument"))
{
found = true;
}
}
}
}
Assert.IsTrue(found);
}
}
/**
* Checks that we can open a workbook with NPOIFS, and write it out
* again (via POIFS) and have it be valid
* @throws IOException
*/
[Test]
public void TestWriteWorkbookFromNPOIFS()
{
//throw new NotImplementedException("class NPOIFSFileSystem is not implemented");
Stream is1 = HSSFTestDataSamples.OpenSampleFileStream("WithEmbeddedObjects.xls");
NPOIFSFileSystem fs = new NPOIFSFileSystem(is1);
// Start as NPOIFS
HSSFWorkbook wb = new HSSFWorkbook(fs.Root, true);
Assert.AreEqual(3, wb.NumberOfSheets);
Assert.AreEqual("Root xls", wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue);
// Will switch to POIFS
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
Assert.AreEqual(3, wb.NumberOfSheets);
Assert.AreEqual("Root xls", wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue);
}
[Test]
public void TestCellStylesLimit()
{
IWorkbook wb = new HSSFWorkbook();
int numBuiltInStyles = wb.NumCellStyles;
int MAX_STYLES = 4030;
int limit = MAX_STYLES - numBuiltInStyles;
for (int i = 0; i < limit; i++)
{
ICellStyle style = wb.CreateCellStyle();
}
Assert.AreEqual(MAX_STYLES, wb.NumCellStyles);
try
{
ICellStyle style = wb.CreateCellStyle();
Assert.Fail("expected exception");
}
catch (InvalidOperationException e)
{
Assert.AreEqual("The maximum number of cell styles was exceeded. " +
"You can define up to 4000 styles in a .xls workbook", e.Message);
}
Assert.AreEqual(MAX_STYLES, wb.NumCellStyles);
}
[Test]
public void TestSetSheetOrderHSSF()
{
IWorkbook wb = new HSSFWorkbook();
ISheet s1 = wb.CreateSheet("first sheet");
ISheet s2 = wb.CreateSheet("other sheet");
IName name1 = wb.CreateName();
name1.NameName = (/*setter*/"name1");
name1.RefersToFormula = (/*setter*/"'first sheet'!D1");
IName name2 = wb.CreateName();
name2.NameName = (/*setter*/"name2");
name2.RefersToFormula = (/*setter*/"'other sheet'!C1");
IRow s1r1 = s1.CreateRow(2);
ICell c1 = s1r1.CreateCell(3);
c1.SetCellValue(30);
ICell c2 = s1r1.CreateCell(2);
c2.CellFormula = (/*setter*/"SUM('other sheet'!C1,'first sheet'!C1)");
IRow s2r1 = s2.CreateRow(0);
ICell c3 = s2r1.CreateCell(1);
c3.CellFormula = (/*setter*/"'first sheet'!D3");
ICell c4 = s2r1.CreateCell(2);
c4.CellFormula = (/*setter*/"'other sheet'!D3");
// conditional formatting
ISheetConditionalFormatting sheetCF = s1.SheetConditionalFormatting;
IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(
ComparisonOperator.Between, "'first sheet'!D1", "'other sheet'!D1");
IConditionalFormattingRule[] cfRules = { rule1 };
CellRangeAddress[] regions = { new CellRangeAddress(2, 4, 0, 0), // A3:A5
};
sheetCF.AddConditionalFormatting(regions, cfRules);
wb.SetSheetOrder("other sheet", 0);
// names
Assert.AreEqual("'first sheet'!D1", wb.GetName("name1").RefersToFormula);
Assert.AreEqual("'other sheet'!C1", wb.GetName("name2").RefersToFormula);
// cells
Assert.AreEqual("SUM('other sheet'!C1,'first sheet'!C1)", c2.CellFormula);
Assert.AreEqual("'first sheet'!D3", c3.CellFormula);
Assert.AreEqual("'other sheet'!D3", c4.CellFormula);
// conditional formatting
IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0);
Assert.AreEqual("'first sheet'!D1", cf.GetRule(0).Formula1);
Assert.AreEqual("'other sheet'!D1", cf.GetRule(0).Formula2);
}
private bool HasEntry(DirectoryNode dirNode, String entryName)
{
try
{
dirNode.GetEntry(entryName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
[Test]
public void TestClonePictures()
{
IWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("SimpleWithImages.xls");
InternalWorkbook iwb = ((HSSFWorkbook)wb).Workbook;
iwb.FindDrawingGroup();
for (int pictureIndex = 1; pictureIndex <= 4; pictureIndex++)
{
EscherBSERecord bse = iwb.GetBSERecord(pictureIndex);
Assert.AreEqual(1, bse.Ref);
}
wb.CloneSheet(0);
for (int pictureIndex = 1; pictureIndex <= 4; pictureIndex++)
{
EscherBSERecord bse = iwb.GetBSERecord(pictureIndex);
Assert.AreEqual(2, bse.Ref);
}
wb.CloneSheet(0);
for (int pictureIndex = 1; pictureIndex <= 4; pictureIndex++)
{
EscherBSERecord bse = iwb.GetBSERecord(pictureIndex);
Assert.AreEqual(3, bse.Ref);
}
}
[Test]
public void TestChangeSheetNameWithSharedFormulas()
{
ChangeSheetNameWithSharedFormulas("shared_formulas.xls");
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// BasicOperations operations.
/// </summary>
public partial class BasicOperations : IServiceOperations<AutoRestComplexTestService>, IBasicOperations
{
/// <summary>
/// Initializes a new instance of the BasicOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public BasicOperations(AutoRestComplexTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex type {id: 2, name: 'abc', color: 'YELLOW'}
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Basic>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </summary>
/// <param name='complexBody'>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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 = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is invalid for the local strong type
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type whose properties are null
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Basic>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type while the server doesn't provide a response
/// payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using AspNetCoreTest.Data;
namespace AspNetCoreTest.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("AspNetCoreTest.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("AspNetCoreTest.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("AspNetCoreTest.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("AspNetCoreTest.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. 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.
#endregion
using System;
using System.IO;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.Protobuf
{
public class CodedOutputStreamTest
{
/// <summary>
/// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and
/// checks that the result matches the given bytes
/// </summary>
private static void AssertWriteVarint(byte[] data, ulong value)
{
// Only do 32-bit write if the value fits in 32 bits.
if ((value >> 32) == 0)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput);
output.WriteRawVarint32((uint) value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
// Also try computing size.
Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value));
}
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput);
output.WriteRawVarint64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
// Also try computing size.
Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value));
}
// Try different buffer sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
// Only do 32-bit write if the value fits in 32 bits.
if ((value >> 32) == 0)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output =
new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawVarint32((uint) value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
}
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawVarint64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
}
}
}
/// <summary>
/// Tests WriteRawVarint32() and WriteRawVarint64()
/// </summary>
[Test]
public void WriteVarint()
{
AssertWriteVarint(new byte[] {0x00}, 0);
AssertWriteVarint(new byte[] {0x01}, 1);
AssertWriteVarint(new byte[] {0x7f}, 127);
// 14882
AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7));
// 2961488830
AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b},
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x0bL << 28));
// 64-bit
// 7256456126
AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b},
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x1bL << 28));
// 41256202580718336
AssertWriteVarint(
new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49},
(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
(0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49));
// 11964378330978735131
AssertWriteVarint(
new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01},
unchecked((ulong)
((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
(0x05L << 49) | (0x26L << 56) | (0x01L << 63))));
}
/// <summary>
/// Parses the given bytes using WriteRawLittleEndian32() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertWriteLittleEndian32(byte[] data, uint value)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput);
output.WriteRawLittleEndian32(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
// Try different buffer sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
rawOutput = new MemoryStream();
output = new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawLittleEndian32(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
}
}
/// <summary>
/// Parses the given bytes using WriteRawLittleEndian64() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertWriteLittleEndian64(byte[] data, ulong value)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput);
output.WriteRawLittleEndian64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
rawOutput = new MemoryStream();
output = new CodedOutputStream(rawOutput, blockSize);
output.WriteRawLittleEndian64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
}
}
/// <summary>
/// Tests writeRawLittleEndian32() and writeRawLittleEndian64().
/// </summary>
[Test]
public void WriteLittleEndian()
{
AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678);
AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0);
AssertWriteLittleEndian64(
new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12},
0x123456789abcdef0L);
AssertWriteLittleEndian64(
new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a},
0x9abcdef012345678UL);
}
[Test]
public void WriteWholeMessage_VaryingBlockSizes()
{
TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
byte[] rawBytes = message.ToByteArray();
// Try different block sizes.
for (int blockSize = 1; blockSize < 256; blockSize *= 2)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize);
message.WriteTo(output);
output.Flush();
Assert.AreEqual(rawBytes, rawOutput.ToArray());
}
}
[Test]
public void EncodeZigZag32()
{
Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag32(0));
Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag32(-1));
Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag32(1));
Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag32(-2));
Assert.AreEqual(0x7FFFFFFEu, CodedOutputStream.EncodeZigZag32(0x3FFFFFFF));
Assert.AreEqual(0x7FFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0xC0000000)));
Assert.AreEqual(0xFFFFFFFEu, CodedOutputStream.EncodeZigZag32(0x7FFFFFFF));
Assert.AreEqual(0xFFFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0x80000000)));
}
[Test]
public void EncodeZigZag64()
{
Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag64(0));
Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag64(-1));
Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag64(1));
Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag64(-2));
Assert.AreEqual(0x000000007FFFFFFEuL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL)));
Assert.AreEqual(0x000000007FFFFFFFuL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL)));
Assert.AreEqual(0x00000000FFFFFFFEuL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL)));
Assert.AreEqual(0x00000000FFFFFFFFuL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL)));
Assert.AreEqual(0xFFFFFFFFFFFFFFFEL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL)));
Assert.AreEqual(0xFFFFFFFFFFFFFFFFL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0x8000000000000000UL)));
}
[Test]
public void RoundTripZigZag32()
{
// Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
// were chosen semi-randomly via keyboard bashing.
Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
}
[Test]
public void RoundTripZigZag64()
{
Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
Assert.AreEqual(856912304801416L,
CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
Assert.AreEqual(-75123905439571256L,
CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
}
[Test]
public void TestNegativeEnumNoTag()
{
Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue));
byte[] bytes = new byte[10];
CodedOutputStream output = new CodedOutputStream(bytes);
output.WriteEnum((int) SampleEnum.NegativeValue);
Assert.AreEqual(0, output.SpaceLeft);
Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
[Test]
public void TestCodedInputOutputPosition()
{
byte[] content = new byte[110];
for (int i = 0; i < content.Length; i++)
content[i] = (byte)i;
byte[] child = new byte[120];
{
MemoryStream ms = new MemoryStream(child);
CodedOutputStream cout = new CodedOutputStream(ms, 20);
// Field 11: numeric value: 500
cout.WriteTag(11, WireFormat.WireType.Varint);
Assert.AreEqual(1, cout.Position);
cout.WriteInt32(500);
Assert.AreEqual(3, cout.Position);
//Field 12: length delimited 120 bytes
cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
Assert.AreEqual(4, cout.Position);
cout.WriteBytes(ByteString.CopyFrom(content));
Assert.AreEqual(115, cout.Position);
// Field 13: fixed numeric value: 501
cout.WriteTag(13, WireFormat.WireType.Fixed32);
Assert.AreEqual(116, cout.Position);
cout.WriteSFixed32(501);
Assert.AreEqual(120, cout.Position);
cout.Flush();
}
byte[] bytes = new byte[130];
{
CodedOutputStream cout = new CodedOutputStream(bytes);
// Field 1: numeric value: 500
cout.WriteTag(1, WireFormat.WireType.Varint);
Assert.AreEqual(1, cout.Position);
cout.WriteInt32(500);
Assert.AreEqual(3, cout.Position);
//Field 2: length delimited 120 bytes
cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
Assert.AreEqual(4, cout.Position);
cout.WriteBytes(ByteString.CopyFrom(child));
Assert.AreEqual(125, cout.Position);
// Field 3: fixed numeric value: 500
cout.WriteTag(3, WireFormat.WireType.Fixed32);
Assert.AreEqual(126, cout.Position);
cout.WriteSFixed32(501);
Assert.AreEqual(130, cout.Position);
cout.Flush();
}
// Now test Input stream:
{
CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0);
Assert.AreEqual(0, cin.Position);
// Field 1:
uint tag = cin.ReadTag();
Assert.AreEqual(1, tag >> 3);
Assert.AreEqual(1, cin.Position);
Assert.AreEqual(500, cin.ReadInt32());
Assert.AreEqual(3, cin.Position);
//Field 2:
tag = cin.ReadTag();
Assert.AreEqual(2, tag >> 3);
Assert.AreEqual(4, cin.Position);
int childlen = cin.ReadLength();
Assert.AreEqual(120, childlen);
Assert.AreEqual(5, cin.Position);
int oldlimit = cin.PushLimit((int)childlen);
Assert.AreEqual(5, cin.Position);
// Now we are reading child message
{
// Field 11: numeric value: 500
tag = cin.ReadTag();
Assert.AreEqual(11, tag >> 3);
Assert.AreEqual(6, cin.Position);
Assert.AreEqual(500, cin.ReadInt32());
Assert.AreEqual(8, cin.Position);
//Field 12: length delimited 120 bytes
tag = cin.ReadTag();
Assert.AreEqual(12, tag >> 3);
Assert.AreEqual(9, cin.Position);
ByteString bstr = cin.ReadBytes();
Assert.AreEqual(110, bstr.Length);
Assert.AreEqual((byte) 109, bstr[109]);
Assert.AreEqual(120, cin.Position);
// Field 13: fixed numeric value: 501
tag = cin.ReadTag();
Assert.AreEqual(13, tag >> 3);
// ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
Assert.AreEqual(121, cin.Position);
Assert.AreEqual(501, cin.ReadSFixed32());
Assert.AreEqual(125, cin.Position);
Assert.IsTrue(cin.IsAtEnd);
}
cin.PopLimit(oldlimit);
Assert.AreEqual(125, cin.Position);
// Field 3: fixed numeric value: 501
tag = cin.ReadTag();
Assert.AreEqual(3, tag >> 3);
Assert.AreEqual(126, cin.Position);
Assert.AreEqual(501, cin.ReadSFixed32());
Assert.AreEqual(130, cin.Position);
Assert.IsTrue(cin.IsAtEnd);
}
}
[Test]
public void Dispose_DisposesUnderlyingStream()
{
var memoryStream = new MemoryStream();
Assert.IsTrue(memoryStream.CanWrite);
using (var cos = new CodedOutputStream(memoryStream))
{
cos.WriteRawByte(0);
Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
}
Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream
Assert.IsFalse(memoryStream.CanWrite); // Disposed
}
[Test]
public void Dispose_WithLeaveOpen()
{
var memoryStream = new MemoryStream();
Assert.IsTrue(memoryStream.CanWrite);
using (var cos = new CodedOutputStream(memoryStream, true))
{
cos.WriteRawByte(0);
Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
}
Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream
Assert.IsTrue(memoryStream.CanWrite); // We left the stream open
}
}
}
| |
/*
* 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 ParquetSharp.IO;
namespace ParquetSharp.Schema
{
/**
* Represents a group type: a list of fields
*
* @author Julien Le Dem
*
*/
public class GroupType : Type
{
private IList<Type> fields;
private Dictionary<string, int> indexByName;
/**
* @param repetition OPTIONAL, REPEATED, REQUIRED
* @param name the name of the field
* @param fields the contained fields
*/
public GroupType(Repetition repetition, string name, IList<Type> fields)
: this(repetition, name, null, fields, null)
{
}
/**
* @param repetition OPTIONAL, REPEATED, REQUIRED
* @param name the name of the field
* @param fields the contained fields
*/
public GroupType(Repetition repetition, string name, params Type[] fields)
: this(repetition, name, null, fields)
{
}
/**
* @param repetition OPTIONAL, REPEATED, REQUIRED
* @param name the name of the field
* @param originalType (optional) the original type to help with cross schema conversion (LIST, MAP, ...)
* @param fields the contained fields
*/
[Obsolete]
public GroupType(Repetition repetition, string name, OriginalType? originalType, params Type[] fields)
: this(repetition, name, originalType, fields, null)
{
}
/**
* @param repetition OPTIONAL, REPEATED, REQUIRED
* @param name the name of the field
* @param originalType (optional) the original type to help with cross schema conversion (LIST, MAP, ...)
* @param fields the contained fields
*/
[Obsolete]
public GroupType(Repetition repetition, string name, OriginalType? originalType, IList<Type> fields)
: this(repetition, name, originalType, fields, null)
{
}
/**
* @param repetition OPTIONAL, REPEATED, REQUIRED
* @param name the name of the field
* @param originalType (optional) the original type to help with cross schema conversion (LIST, MAP, ...)
* @param fields the contained fields
* @param id the id of the field
*/
internal GroupType(Repetition repetition, string name, OriginalType? originalType, IList<Type> fields, ID id)
: base(name, repetition, originalType, id)
{
this.fields = fields;
this.indexByName = new Dictionary<string, int>();
for (int i = 0; i < fields.Count; i++)
{
indexByName[fields[i].getName()] = i;
}
}
/**
* @param id the field id
* @return a new GroupType with the same fields and a new id
*/
public override Type withId(int id)
{
return new GroupType(getRepetition(), getName(), getOriginalType(), fields, new ID(id));
}
/**
* @param newFields
* @return a group with the same attributes and new fields.
*/
public GroupType withNewFields(IList<Type> newFields)
{
return new GroupType(getRepetition(), getName(), getOriginalType(), newFields, getId());
}
/**
* @param newFields
* @return a group with the same attributes and new fields.
*/
public GroupType withNewFields(params Type[] newFields)
{
return withNewFields((IList<Type>)newFields);
}
/**
* returns the name of the corresponding field
* @param index the index of the desired field in this type
* @return the name of the field at this index
*/
public string getFieldName(int index)
{
return fields[index].getName();
}
/**
* @param name the requested name
* @return whether this type contains a field with that name
*/
public bool containsField(string name)
{
return indexByName.ContainsKey(name);
}
/**
*
* @param name
* @return the index of the field with that name
*/
public int getFieldIndex(string name)
{
if (!indexByName.ContainsKey(name))
{
throw new InvalidRecordException(name + " not found in " + this);
}
return indexByName[name];
}
/**
* @return the fields contained in this type
*/
public IList<Type> getFields()
{
return fields;
}
/**
* @return the number of fields in this type
*/
public int getFieldCount()
{
return fields.Count;
}
/**
* @return false
*/
public override bool isPrimitive()
{
return false;
}
/**
* @param fieldName
* @return the type of this field by name
*/
public Type getType(string fieldName)
{
return getType(getFieldIndex(fieldName));
}
/**
* @param index
* @return the type of this field by index
*/
public Type getType(int index)
{
return fields[index];
}
/**
* appends a display string for of the members of this group to sb
* @param sb where to append
* @param indent the indentation level
*/
protected void membersDisplayString(StringBuilder sb, string indent)
{
foreach (Type field in fields)
{
field.writeToStringBuilder(sb, indent);
if (field.isPrimitive())
{
sb.Append(";");
}
sb.Append("\n");
}
}
/**
* {@inheritDoc}
*/
public override void writeToStringBuilder(StringBuilder sb, string indent)
{
sb.Append(indent)
.Append(getRepetition().ToString().ToLowerInvariant())
.Append(" group ")
.Append(getName())
.Append(getOriginalType() == null ? "" : " (" + getOriginalType() + ")")
.Append(getId() == null ? "" : " = " + getId())
.Append(" {\n");
membersDisplayString(sb, indent + " ");
sb.Append(indent)
.Append("}");
}
/**
* {@inheritDoc}
*/
public override void accept(TypeVisitor visitor)
{
visitor.visit(this);
}
[Obsolete]
protected override int typeHashCode()
{
return GetHashCode();
}
[Obsolete]
protected override bool typeEquals(Type other)
{
return equals(other);
}
/**
* {@inheritDoc}
*/
public override int GetHashCode()
{
// TODO
return base.GetHashCode() * 31 + getFields().GetHashCode();
}
/**
* {@inheritDoc}
*/
protected bool equals(Type otherType)
{
return
!otherType.isPrimitive()
&& base.Equals(otherType)
&& getFields().Equals(otherType.asGroupType().getFields());
}
internal override int getMaxRepetitionLevel(string[] path, int depth)
{
int myVal = isRepetition(Repetition.REPEATED) ? 1 : 0;
if (depth == path.Length)
{
return myVal;
}
return myVal + getType(path[depth]).getMaxRepetitionLevel(path, depth + 1);
}
internal override int getMaxDefinitionLevel(string[] path, int depth)
{
int myVal = !isRepetition(Repetition.REQUIRED) ? 1 : 0;
if (depth == path.Length)
{
return myVal;
}
return myVal + getType(path[depth]).getMaxDefinitionLevel(path, depth + 1);
}
internal override Type getType(string[] path, int depth)
{
if (depth == path.Length)
{
return this;
}
return getType(path[depth]).getType(path, depth + 1);
}
internal override bool containsPath(string[] path, int depth)
{
if (depth == path.Length)
{
return false;
}
return containsField(path[depth]) && getType(path[depth]).containsPath(path, depth + 1);
}
internal override List<string[]> getPaths(int depth)
{
List<string[]> result = new List<string[]>();
foreach (Type field in fields)
{
List<string[]> paths = field.getPaths(depth + 1);
foreach (string[] path in paths)
{
path[depth] = field.getName();
result.Add(path);
}
}
return result;
}
internal override void checkContains(Type subType)
{
base.checkContains(subType);
checkGroupContains(subType);
}
protected void checkGroupContains(Type subType)
{
if (subType.isPrimitive())
{
throw new InvalidRecordException(subType + " found: expected " + this);
}
IList<Type> fields = subType.asGroupType().getFields();
foreach (Type otherType in fields)
{
Type thisType = this.getType(otherType.getName());
thisType.checkContains(otherType);
}
}
internal override T convert<T>(List<GroupType> path, TypeConverter<T> converter)
{
List<GroupType> childrenPath = new List<GroupType>(path);
childrenPath.Add(this);
List<T> children = convertChildren(childrenPath, converter);
return converter.convertGroupType(path, this, children);
}
protected List<T> convertChildren<T>(List<GroupType> path, TypeConverter<T> converter)
{
List<T> children = new List<T>(fields.Count);
foreach (Type field in fields)
{
children.Add(field.convert(path, converter));
}
return children;
}
internal override Type union(Type toMerge)
{
return union(toMerge, true);
}
internal override Type union(Type toMerge, bool strict)
{
if (toMerge.isPrimitive())
{
throw new IncompatibleSchemaModificationException("can not merge primitive type " + toMerge + " into group type " + this);
}
return new GroupType(toMerge.getRepetition(), getName(), mergeFields(toMerge.asGroupType()));
}
/**
* produces the list of fields resulting from merging toMerge into the fields of this
* @param toMerge the group containing the fields to merge
* @return the merged list
*/
internal List<Type> mergeFields(GroupType toMerge)
{
return mergeFields(toMerge, true);
}
/**
* produces the list of fields resulting from merging toMerge into the fields of this
* @param toMerge the group containing the fields to merge
* @param strict should schema primitive types match
* @return the merged list
*/
internal List<Type> mergeFields(GroupType toMerge, bool strict)
{
List<Type> newFields = new List<Type>();
// merge existing fields
foreach (Type type in this.getFields())
{
Type merged;
if (toMerge.containsField(type.getName()))
{
Type fieldToMerge = toMerge.getType(type.getName());
if (fieldToMerge.getRepetition().isMoreRestrictiveThan(type.getRepetition()))
{
throw new IncompatibleSchemaModificationException("repetition constraint is more restrictive: can not merge type " + fieldToMerge + " into " + type);
}
merged = type.union(fieldToMerge, strict);
}
else
{
merged = type;
}
newFields.Add(merged);
}
// add new fields
foreach (Type type in toMerge.getFields())
{
if (!this.containsField(type.getName()))
{
newFields.Add(type);
}
}
return newFields;
}
}
}
| |
// 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.Reflection;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using System.Security.Permissions;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Runtime.InteropServices;
using System.Configuration.Assemblies;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.Reflection
{
[Serializable]
internal enum CorElementType : byte
{
End = 0x00,
Void = 0x01,
Boolean = 0x02,
Char = 0x03,
I1 = 0x04,
U1 = 0x05,
I2 = 0x06,
U2 = 0x07,
I4 = 0x08,
U4 = 0x09,
I8 = 0x0A,
U8 = 0x0B,
R4 = 0x0C,
R8 = 0x0D,
String = 0x0E,
Ptr = 0x0F,
ByRef = 0x10,
ValueType = 0x11,
Class = 0x12,
Var = 0x13,
Array = 0x14,
GenericInst = 0x15,
TypedByRef = 0x16,
I = 0x18,
U = 0x19,
FnPtr = 0x1B,
Object = 0x1C,
SzArray = 0x1D,
MVar = 0x1E,
CModReqd = 0x1F,
CModOpt = 0x20,
Internal = 0x21,
Max = 0x22,
Modifier = 0x40,
Sentinel = 0x41,
Pinned = 0x45,
}
[Serializable]
[Flags()]
internal enum MdSigCallingConvention: byte
{
CallConvMask = 0x0f, // Calling convention is bottom 4 bits
Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmgd = 0x09,
GenericInst = 0x0a, // generic method instantiation
Generic = 0x10, // Generic method sig with explicit number of type arguments (precedes ordinary parameter count)
HasThis = 0x20, // Top bit indicates a 'this' parameter
ExplicitThis = 0x40, // This parameter is explicitly in the signature
}
[Serializable]
[Flags()]
internal enum PInvokeAttributes
{
NoMangle = 0x0001,
CharSetMask = 0x0006,
CharSetNotSpec = 0x0000,
CharSetAnsi = 0x0002,
CharSetUnicode = 0x0004,
CharSetAuto = 0x0006,
BestFitUseAssem = 0x0000,
BestFitEnabled = 0x0010,
BestFitDisabled = 0x0020,
BestFitMask = 0x0030,
ThrowOnUnmappableCharUseAssem = 0x0000,
ThrowOnUnmappableCharEnabled = 0x1000,
ThrowOnUnmappableCharDisabled = 0x2000,
ThrowOnUnmappableCharMask = 0x3000,
SupportsLastError = 0x0040,
CallConvMask = 0x0700,
CallConvWinapi = 0x0100,
CallConvCdecl = 0x0200,
CallConvStdcall = 0x0300,
CallConvThiscall = 0x0400,
CallConvFastcall = 0x0500,
MaxValue = 0xFFFF,
}
[Serializable]
[Flags()]
internal enum MethodSemanticsAttributes
{
Setter = 0x0001,
Getter = 0x0002,
Other = 0x0004,
AddOn = 0x0008,
RemoveOn = 0x0010,
Fire = 0x0020,
}
[Serializable]
internal enum MetadataTokenType
{
Module = 0x00000000,
TypeRef = 0x01000000,
TypeDef = 0x02000000,
FieldDef = 0x04000000,
MethodDef = 0x06000000,
ParamDef = 0x08000000,
InterfaceImpl = 0x09000000,
MemberRef = 0x0a000000,
CustomAttribute = 0x0c000000,
Permission = 0x0e000000,
Signature = 0x11000000,
Event = 0x14000000,
Property = 0x17000000,
ModuleRef = 0x1a000000,
TypeSpec = 0x1b000000,
Assembly = 0x20000000,
AssemblyRef = 0x23000000,
File = 0x26000000,
ExportedType = 0x27000000,
ManifestResource = 0x28000000,
GenericPar = 0x2a000000,
MethodSpec = 0x2b000000,
String = 0x70000000,
Name = 0x71000000,
BaseType = 0x72000000,
Invalid = 0x7FFFFFFF,
}
[Serializable]
internal struct ConstArray
{
public IntPtr Signature { get { return m_constArray; } }
public int Length { get { return m_length; } }
public byte this[int index]
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (index < 0 || index >= m_length)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
unsafe
{
return ((byte*)m_constArray.ToPointer())[index];
}
}
}
// Keep the definition in sync with vm\ManagedMdImport.hpp
internal int m_length;
internal IntPtr m_constArray;
}
[Serializable]
internal struct MetadataToken
{
#region Implicit Cast Operators
public static implicit operator int(MetadataToken token) { return token.Value; }
public static implicit operator MetadataToken(int token) { return new MetadataToken(token); }
#endregion
#region Public Static Members
public static bool IsTokenOfType(int token, params MetadataTokenType[] types)
{
for (int i = 0; i < types.Length; i++)
{
if ((int)(token & 0xFF000000) == (int)types[i])
return true;
}
return false;
}
public static bool IsNullToken(int token)
{
return (token & 0x00FFFFFF) == 0;
}
#endregion
#region Public Data Members
public int Value;
#endregion
#region Constructor
public MetadataToken(int token) { Value = token; }
#endregion
#region Public Members
public bool IsGlobalTypeDefToken { get { return (Value == 0x02000001); } }
public MetadataTokenType TokenType { get { return (MetadataTokenType)(Value & 0xFF000000); } }
public bool IsTypeRef { get { return TokenType == MetadataTokenType.TypeRef; } }
public bool IsTypeDef { get { return TokenType == MetadataTokenType.TypeDef; } }
public bool IsFieldDef { get { return TokenType == MetadataTokenType.FieldDef; } }
public bool IsMethodDef { get { return TokenType == MetadataTokenType.MethodDef; } }
public bool IsMemberRef { get { return TokenType == MetadataTokenType.MemberRef; } }
public bool IsEvent { get { return TokenType == MetadataTokenType.Event; } }
public bool IsProperty { get { return TokenType == MetadataTokenType.Property; } }
public bool IsParamDef { get { return TokenType == MetadataTokenType.ParamDef; } }
public bool IsTypeSpec { get { return TokenType == MetadataTokenType.TypeSpec; } }
public bool IsMethodSpec { get { return TokenType == MetadataTokenType.MethodSpec; } }
public bool IsString { get { return TokenType == MetadataTokenType.String; } }
public bool IsSignature { get { return TokenType == MetadataTokenType.Signature; } }
public bool IsModule { get { return TokenType == MetadataTokenType.Module; } }
public bool IsAssembly { get { return TokenType == MetadataTokenType.Assembly; } }
public bool IsGenericPar { get { return TokenType == MetadataTokenType.GenericPar; } }
#endregion
#region Object Overrides
public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "0x{0:x8}", Value); }
#endregion
}
internal unsafe struct MetadataEnumResult
{
// Keep the definition in sync with vm\ManagedMdImport.hpp
private int[] largeResult;
private int length;
private fixed int smallResult[16];
public int Length
{
get
{
return length;
}
}
public int this[int index]
{
[System.Security.SecurityCritical]
get
{
Contract.Requires(0 <= index && index < Length);
if (largeResult != null)
return largeResult[index];
fixed (int* p = smallResult)
return p[index];
}
}
}
internal struct MetadataImport
{
#region Private Data Members
private IntPtr m_metadataImport2;
private object m_keepalive;
#endregion
#region Override methods from Object
internal static readonly MetadataImport EmptyImport = new MetadataImport((IntPtr)0, null);
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(m_metadataImport2);
}
public override bool Equals(object obj)
{
if(!(obj is MetadataImport))
return false;
return Equals((MetadataImport)obj);
}
private bool Equals(MetadataImport import)
{
return import.m_metadataImport2 == m_metadataImport2;
}
#endregion
#region Static Members
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType,
out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
out int iidParamIndex);
[System.Security.SecurityCritical] // auto-generated
internal static void GetMarshalAs(ConstArray nativeType,
out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType,
out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
out int iidParamIndex)
{
int _unmanagedType, _safeArraySubType, _arraySubType;
_GetMarshalAs(nativeType.Signature, (int)nativeType.Length,
out _unmanagedType, out _safeArraySubType, out safeArrayUserDefinedSubType,
out _arraySubType, out sizeParamIndex, out sizeConst, out marshalType, out marshalCookie,
out iidParamIndex);
unmanagedType = (UnmanagedType)_unmanagedType;
safeArraySubType = (VarEnum)_safeArraySubType;
arraySubType = (UnmanagedType)_arraySubType;
}
#endregion
#region Internal Static Members
internal static void ThrowError(int hResult)
{
throw new MetadataException(hResult);
}
#endregion
#region Constructor
internal MetadataImport(IntPtr metadataImport2, object keepalive)
{
m_metadataImport2 = metadataImport2;
m_keepalive = keepalive;
}
#endregion
#region FCalls
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private unsafe static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result);
[System.Security.SecurityCritical] // auto-generated
public unsafe void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result)
{
_Enum(m_metadataImport2, (int)type, parent, out result);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.TypeDef, mdTypeDef, out result);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe void EnumCustomAttributes(int mdToken, out MetadataEnumResult result)
{
Enum(MetadataTokenType.CustomAttribute, mdToken, out result);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe void EnumParams(int mdMethodDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.ParamDef, mdMethodDef, out result);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe void EnumFields(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.FieldDef, mdTypeDef, out result);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe void EnumProperties(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.Property, mdTypeDef, out result);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe void EnumEvents(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.Event, mdTypeDef, out result);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static extern String _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType);
[System.Security.SecurityCritical] // auto-generated
public String GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType)
{
int _corElementType;
String stringVal;
stringVal = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out _corElementType);
corElementType = (CorElementType)_corElementType;
return stringVal;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static unsafe extern void _GetUserString(IntPtr scope, int mdToken, void** name, out int length);
[System.Security.SecurityCritical] // auto-generated
public unsafe String GetUserString(int mdToken)
{
void* name;
int length;
_GetUserString(m_metadataImport2, mdToken, &name, out length);
if (name == null)
return null;
char[] c = new char[length];
for (int i = 0; i < length; i ++)
{
#if ALIGN_ACCESS
c[i] = (char)Marshal.ReadInt16( (IntPtr) (((char*)name) + i) );
#else
c[i] = ((char*)name)[i];
#endif
}
return new String(c);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static unsafe extern void _GetName(IntPtr scope, int mdToken, void** name);
[System.Security.SecurityCritical] // auto-generated
public unsafe Utf8String GetName(int mdToken)
{
void* name;
_GetName(m_metadataImport2, mdToken, &name);
return new Utf8String(name);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static unsafe extern void _GetNamespace(IntPtr scope, int mdToken, void** namesp);
[System.Security.SecurityCritical] // auto-generated
public unsafe Utf8String GetNamespace(int mdToken)
{
void* namesp;
_GetNamespace(m_metadataImport2, mdToken, &namesp);
return new Utf8String(namesp);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private unsafe static extern void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes);
[System.Security.SecurityCritical] // auto-generated
public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes)
{
int _eventAttributes;
void* _name;
_GetEventProps(m_metadataImport2, mdToken, &_name, out _eventAttributes);
name = _name;
eventAttributes = (EventAttributes)_eventAttributes;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes);
[System.Security.SecurityCritical] // auto-generated
public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes)
{
int _fieldAttributes;
_GetFieldDefProps(m_metadataImport2, mdToken, out _fieldAttributes);
fieldAttributes = (FieldAttributes)_fieldAttributes;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private unsafe static extern void _GetPropertyProps(IntPtr scope,
int mdToken, void** name, out int propertyAttributes, out ConstArray signature);
[System.Security.SecurityCritical] // auto-generated
public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature)
{
int _propertyAttributes;
void* _name;
_GetPropertyProps(m_metadataImport2, mdToken, &_name, out _propertyAttributes, out signature);
name = _name;
propertyAttributes = (PropertyAttributes)_propertyAttributes;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static extern void _GetParentToken(IntPtr scope,
int mdToken, out int tkParent);
[System.Security.SecurityCritical] // auto-generated
public int GetParentToken(int tkToken)
{
int tkParent;
_GetParentToken(m_metadataImport2, tkToken, out tkParent);
return tkParent;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetParamDefProps(IntPtr scope,
int parameterToken, out int sequence, out int attributes);
[System.Security.SecurityCritical] // auto-generated
public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes)
{
int _attributes;
_GetParamDefProps(m_metadataImport2, parameterToken, out sequence, out _attributes);
attributes = (ParameterAttributes)_attributes;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetGenericParamProps(IntPtr scope,
int genericParameter,
out int flags);
[System.Security.SecurityCritical] // auto-generated
public void GetGenericParamProps(
int genericParameter,
out GenericParameterAttributes attributes)
{
int _attributes;
_GetGenericParamProps(m_metadataImport2, genericParameter, out _attributes);
attributes = (GenericParameterAttributes)_attributes;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetScopeProps(IntPtr scope,
out Guid mvid);
[System.Security.SecurityCritical] // auto-generated
public void GetScopeProps(
out Guid mvid)
{
_GetScopeProps(m_metadataImport2, out mvid);
}
[System.Security.SecurityCritical] // auto-generated
public ConstArray GetMethodSignature(MetadataToken token)
{
if (token.IsMemberRef)
return GetMemberRefProps(token);
return GetSigOfMethodDef(token);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetSigOfMethodDef(IntPtr scope,
int methodToken,
ref ConstArray signature);
[System.Security.SecurityCritical] // auto-generated
public ConstArray GetSigOfMethodDef(int methodToken)
{
ConstArray signature = new ConstArray();
_GetSigOfMethodDef(m_metadataImport2, methodToken, ref signature);
return signature;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetSignatureFromToken(IntPtr scope,
int methodToken,
ref ConstArray signature);
[System.Security.SecurityCritical] // auto-generated
public ConstArray GetSignatureFromToken(int token)
{
ConstArray signature = new ConstArray();
_GetSignatureFromToken(m_metadataImport2, token, ref signature);
return signature;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetMemberRefProps(IntPtr scope,
int memberTokenRef,
out ConstArray signature);
[System.Security.SecurityCritical] // auto-generated
public ConstArray GetMemberRefProps(int memberTokenRef)
{
ConstArray signature = new ConstArray();
_GetMemberRefProps(m_metadataImport2, memberTokenRef, out signature);
return signature;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetCustomAttributeProps(IntPtr scope,
int customAttributeToken,
out int constructorToken,
out ConstArray signature);
[System.Security.SecurityCritical] // auto-generated
public void GetCustomAttributeProps(
int customAttributeToken,
out int constructorToken,
out ConstArray signature)
{
_GetCustomAttributeProps(m_metadataImport2, customAttributeToken,
out constructorToken, out signature);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetClassLayout(IntPtr scope,
int typeTokenDef, out int packSize, out int classSize);
[System.Security.SecurityCritical] // auto-generated
public void GetClassLayout(
int typeTokenDef,
out int packSize,
out int classSize)
{
_GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool _GetFieldOffset(IntPtr scope,
int typeTokenDef, int fieldTokenDef, out int offset);
[System.Security.SecurityCritical] // auto-generated
public bool GetFieldOffset(
int typeTokenDef,
int fieldTokenDef,
out int offset)
{
return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetSigOfFieldDef(IntPtr scope,
int fieldToken,
ref ConstArray fieldMarshal);
[System.Security.SecurityCritical] // auto-generated
public ConstArray GetSigOfFieldDef(int fieldToken)
{
ConstArray fieldMarshal = new ConstArray();
_GetSigOfFieldDef(m_metadataImport2, fieldToken, ref fieldMarshal);
return fieldMarshal;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetFieldMarshal(IntPtr scope,
int fieldToken,
ref ConstArray fieldMarshal);
[System.Security.SecurityCritical] // auto-generated
public ConstArray GetFieldMarshal(int fieldToken)
{
ConstArray fieldMarshal = new ConstArray();
_GetFieldMarshal(m_metadataImport2, fieldToken, ref fieldMarshal);
return fieldMarshal;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern void _GetPInvokeMap(IntPtr scope,
int token,
out int attributes,
void** importName,
void** importDll);
[System.Security.SecurityCritical] // auto-generated
public unsafe void GetPInvokeMap(
int token,
out PInvokeAttributes attributes,
out String importName,
out String importDll)
{
int _attributes;
void* _importName, _importDll;
_GetPInvokeMap(m_metadataImport2, token, out _attributes, &_importName, &_importDll);
importName = new Utf8String(_importName).ToString();
importDll = new Utf8String(_importDll).ToString();
attributes = (PInvokeAttributes)_attributes;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool _IsValidToken(IntPtr scope, int token);
[System.Security.SecurityCritical] // auto-generated
public bool IsValidToken(int token)
{
return _IsValidToken(m_metadataImport2, token);
}
#endregion
}
internal class MetadataException : Exception
{
private int m_hr;
internal MetadataException(int hr) { m_hr = hr; }
public override string ToString()
{
return String.Format(CultureInfo.CurrentCulture, "MetadataException HResult = {0:x}.", m_hr);
}
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public sealed class HelicoptersScene : IDemoScene
{
Demo demo;
PhysicsScene scene;
string name;
string instanceIndexName;
string info;
public PhysicsScene PhysicsScene { get { return scene; } }
public string SceneName { get { return name; } }
public string SceneInfo { get { return info; } }
// Declare objects in the scene
Sky skyInstance1;
Quad quadInstance1;
Cursor cursorInstance;
Shot shotInstance;
Helicopter1 helicopter1Instance1;
Helicopter1 helicopter1Instance2;
Helicopter1 helicopter1Instance3;
Helicopter1 helicopter1Instance4;
Camera2 camera2Instance1;
Lights lightInstance;
// Declare controllers in the scene
SkyDraw1 skyDraw1Instance1;
CursorDraw1 cursorDraw1Instance;
Helicopter1Animation1 helicopter1Animation1Instance1;
Helicopter1Animation1 helicopter1Animation1Instance2;
Helicopter1Animation1 helicopter1Animation1Instance3;
Helicopter1Animation1 helicopter1Animation1Instance4;
Camera2Animation1 camera2Animation1Instance1;
Camera2Draw1 camera2Draw1Instance1;
public HelicoptersScene(Demo demo, string name, int instanceIndex, string info)
{
this.demo = demo;
this.name = name;
this.instanceIndexName = " " + instanceIndex.ToString();
this.info = info;
// Create a new objects in the scene
skyInstance1 = new Sky(demo, 1);
quadInstance1 = new Quad(demo, 1);
cursorInstance = new Cursor(demo);
shotInstance = new Shot(demo);
helicopter1Instance1 = new Helicopter1(demo, 1);
helicopter1Instance2 = new Helicopter1(demo, 2);
helicopter1Instance3 = new Helicopter1(demo, 3);
helicopter1Instance4 = new Helicopter1(demo, 4);
camera2Instance1 = new Camera2(demo, 1);
lightInstance = new Lights(demo);
// Create a new controllers in the scene
skyDraw1Instance1 = new SkyDraw1(demo, 1);
cursorDraw1Instance = new CursorDraw1(demo);
helicopter1Animation1Instance1 = new Helicopter1Animation1(demo, 1);
helicopter1Animation1Instance2 = new Helicopter1Animation1(demo, 2);
helicopter1Animation1Instance3 = new Helicopter1Animation1(demo, 3);
helicopter1Animation1Instance4 = new Helicopter1Animation1(demo, 4);
camera2Animation1Instance1 = new Camera2Animation1(demo, 1);
camera2Draw1Instance1 = new Camera2Draw1(demo, 1);
}
public void Create()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null) return;
scene = demo.Engine.Factory.PhysicsSceneManager.Create(sceneInstanceIndexName);
// Initialize maximum number of solver iterations for the scene
scene.MaxIterationCount = 10;
// Initialize time of simulation for the scene
scene.TimeOfSimulation = 1.0f / 15.0f;
Initialize();
// Initialize objects in the scene
skyInstance1.Initialize(scene);
quadInstance1.Initialize(scene);
cursorInstance.Initialize(scene);
shotInstance.Initialize(scene);
helicopter1Instance1.Initialize(scene);
helicopter1Instance2.Initialize(scene);
helicopter1Instance3.Initialize(scene);
helicopter1Instance4.Initialize(scene);
camera2Instance1.Initialize(scene);
lightInstance.Initialize(scene);
// Initialize controllers in the scene
skyDraw1Instance1.Initialize(scene);
cursorDraw1Instance.Initialize(scene);
helicopter1Animation1Instance1.Initialize(scene);
helicopter1Animation1Instance2.Initialize(scene);
helicopter1Animation1Instance3.Initialize(scene);
helicopter1Animation1Instance4.Initialize(scene);
camera2Animation1Instance1.Initialize(scene);
camera2Draw1Instance1.Initialize(scene);
// Create shapes shared for all physics objects in the scene
// These shapes are used by all objects in the scene
Demo.CreateSharedShapes(demo, scene);
// Create shapes for objects in the scene
Sky.CreateShapes(demo, scene);
Quad.CreateShapes(demo, scene);
Cursor.CreateShapes(demo, scene);
Shot.CreateShapes(demo, scene);
Helicopter1.CreateShapes(demo, scene);
Camera2.CreateShapes(demo, scene);
Lights.CreateShapes(demo, scene);
// Create physics objects for objects in the scene
skyInstance1.Create(new Vector3(0.0f, 0.0f, 0.0f));
quadInstance1.Create(new Vector3(0.0f, -40.0f, 20.0f), new Vector3(1000.0f, 31.0f, 1000.0f), Quaternion.Identity);
cursorInstance.Create();
shotInstance.Create();
helicopter1Instance1.Create(new Vector3(0.0f, -11.8f, 20.0f), Vector3.One, Quaternion.Identity);
helicopter1Instance2.Create(new Vector3(0.0f, -11.8f, 60.0f), Vector3.One, Quaternion.Identity);
helicopter1Instance3.Create(new Vector3(0.0f, -11.8f, 100.0f), Vector3.One, Quaternion.Identity);
helicopter1Instance4.Create(new Vector3(0.0f, -11.8f, 140.0f), Vector3.One, Quaternion.Identity);
camera2Instance1.Create(new Vector3(60.0f, 5.0f, 20.0f), Quaternion.Identity, Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(60.0f)), Quaternion.Identity, true);
lightInstance.CreateLightPoint(0, "Glass", new Vector3(20.0f, -3.0f, 20.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(1, "Glass", new Vector3(20.0f, -3.0f, 60.0f), new Vector3(0.5f, 0.7f, 0.1f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(2, "Glass", new Vector3(20.0f, -3.0f, 100.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(3, "Glass", new Vector3(20.0f, -3.0f, 140.0f), new Vector3(1.0f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(4, "Glass", new Vector3(-10.0f, -3.0f, 20.0f), new Vector3(1.0f, 1.0f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(5, "Glass", new Vector3(-10.0f, -3.0f, 60.0f), new Vector3(0.3f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(0, "Glass", new Vector3(5.0f, 17.0f, 4.0f), new Vector3(0.1f, 0.7f, 1.0f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(1, "Glass", new Vector3(5.0f, 17.0f, 44.0f), new Vector3(1.0f, 0.5f, 0.2f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(2, "Glass", new Vector3(5.0f, 17.0f, 84.0f), new Vector3(0.5f, 1.0f, 0.2f), 20.0f, 1.0f);
// Set controllers for objects in the scene
SetControllers();
}
public void Initialize()
{
scene.UserControllers.PostDrawMethods += demo.DrawInfo;
if (scene.Light == null)
{
scene.CreateLight(true);
scene.Light.Type = PhysicsLightType.Directional;
scene.Light.SetDirection(-0.4f, -0.8f, 0.4f, 0.0f);
}
}
public void SetControllers()
{
skyDraw1Instance1.SetControllers();
cursorDraw1Instance.SetControllers();
helicopter1Animation1Instance1.SetControllers(new Vector3(0.0f, 20.0f, 50.0f), new Vector3(0.0f, 0.0f, 50.0f));
helicopter1Animation1Instance2.SetControllers(new Vector3(0.0f, 20.0f, 80.0f), new Vector3(0.0f, 0.0f, 80.0f));
helicopter1Animation1Instance3.SetControllers(new Vector3(0.0f, 20.0f, 110.0f), new Vector3(0.0f, 0.0f, 110.0f));
helicopter1Animation1Instance4.SetControllers(new Vector3(0.0f, 20.0f, 140.0f), new Vector3(0.0f, 0.0f, 140.0f));
camera2Animation1Instance1.SetControllers(false);
camera2Draw1Instance1.SetControllers(false, false, false, false, false, false);
}
public void Refresh(double time)
{
camera2Animation1Instance1.RefreshControllers();
camera2Draw1Instance1.RefreshControllers();
GL.Clear(ClearBufferMask.DepthBufferBit);
scene.Simulate(time);
scene.Draw(time);
if (demo.EnableMenu)
{
GL.Clear(ClearBufferMask.DepthBufferBit);
demo.MenuScene.PhysicsScene.Draw(time);
}
demo.SwapBuffers();
}
public void Remove()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null)
demo.Engine.Factory.PhysicsSceneManager.Remove(sceneInstanceIndexName);
}
public void CreateResources()
{
}
public void DisposeResources()
{
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="DataServiceClientRequestPipelineConfiguration.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Client
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.OData.Core;
using ClientStrings = Microsoft.OData.Client.Strings;
/// <summary>
/// Class that holds a variety of events for writing the payload from the OData to the wire
/// </summary>
public class DataServiceClientRequestPipelineConfiguration
{
/// <summary> Actions to execute before start entry called. </summary>
private readonly List<Action<WritingEntryArgs>> writingStartEntryActions;
/// <summary> Actions to execute before end entry called. </summary>
private readonly List<Action<WritingEntryArgs>> writingEndEntryActions;
/// <summary> Actions to execute before entity reference link written. </summary>
private readonly List<Action<WritingEntityReferenceLinkArgs>> writeEntityReferenceLinkActions;
/// <summary> Actions to execute after before start navigation link called. </summary>
private readonly List<Action<WritingNavigationLinkArgs>> writingStartNavigationLinkActions;
/// <summary> Actions to execute before end navigation link called. </summary>
private readonly List<Action<WritingNavigationLinkArgs>> writingEndNavigationLinkActions;
/// <summary> The message writer setting configurations. </summary>
private readonly List<Action<MessageWriterSettingsArgs>> messageWriterSettingsConfigurationActions;
/// <summary> The delegate that represents how a message is created.</summary>
private Func<DataServiceClientRequestMessageArgs, DataServiceClientRequestMessage> onmessageCreating;
/// <summary>
/// Creates a request pipeline configuration class
/// </summary>
internal DataServiceClientRequestPipelineConfiguration()
{
this.writeEntityReferenceLinkActions = new List<Action<WritingEntityReferenceLinkArgs>>();
this.writingEndEntryActions = new List<Action<WritingEntryArgs>>();
this.writingEndNavigationLinkActions = new List<Action<WritingNavigationLinkArgs>>();
this.writingStartEntryActions = new List<Action<WritingEntryArgs>>();
this.writingStartNavigationLinkActions = new List<Action<WritingNavigationLinkArgs>>();
this.messageWriterSettingsConfigurationActions = new List<Action<MessageWriterSettingsArgs>>();
}
/// <summary>
/// Gets the request message to be used for sending the request. By providing a custom message, users
/// can replace the transport layer.
/// </summary>
public Func<DataServiceClientRequestMessageArgs, DataServiceClientRequestMessage> OnMessageCreating
{
get
{
return this.onmessageCreating;
}
set
{
if (this.ContextUsingSendingRequest)
{
throw new DataServiceClientException(ClientStrings.Context_SendingRequest_InvalidWhenUsingOnMessageCreating);
}
this.onmessageCreating = value;
}
}
/// <summary>
/// Determines if OnMessageCreating is being used or not.
/// </summary>
internal bool HasOnMessageCreating
{
get { return this.OnMessageCreating != null; }
}
/// <summary>
/// Gets or sets the a value indicating whether the context is using the sending request event or not.
/// </summary>
internal bool ContextUsingSendingRequest { get; set; }
/// <summary>
/// Called when [message writer created].
/// </summary>
/// <param name="args">The args.</param>
/// <returns>The request pipeline configuration.</returns>
public DataServiceClientRequestPipelineConfiguration OnMessageWriterSettingsCreated(Action<MessageWriterSettingsArgs> args)
{
WebUtil.CheckArgumentNull(args, "args");
this.messageWriterSettingsConfigurationActions.Add(args);
return this;
}
/// <summary>
/// Called when [entry starting].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The request pipeline configuration.</returns>
public DataServiceClientRequestPipelineConfiguration OnEntryStarting(Action<WritingEntryArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.writingStartEntryActions.Add(action);
return this;
}
/// <summary>
/// Called when [entry ending].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The request pipeline configuration.</returns>
public DataServiceClientRequestPipelineConfiguration OnEntryEnding(Action<WritingEntryArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.writingEndEntryActions.Add(action);
return this;
}
/// <summary>
/// Called when [entity reference link].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The request pipeline configuration.</returns>
public DataServiceClientRequestPipelineConfiguration OnEntityReferenceLink(Action<WritingEntityReferenceLinkArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.writeEntityReferenceLinkActions.Add(action);
return this;
}
/// <summary>
/// Called when [navigation link starting].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The request pipeline configuration.</returns>
public DataServiceClientRequestPipelineConfiguration OnNavigationLinkStarting(Action<WritingNavigationLinkArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.writingStartNavigationLinkActions.Add(action);
return this;
}
/// <summary>
/// Called when [navigation link end].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The request pipeline configuration.</returns>
public DataServiceClientRequestPipelineConfiguration OnNavigationLinkEnding(Action<WritingNavigationLinkArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.writingEndNavigationLinkActions.Add(action);
return this;
}
/// <summary>
/// Called when [create message writer settings configurations].
/// </summary>
/// <param name="writerSettings">The writer settings.</param>
internal void ExecuteWriterSettingsConfiguration(ODataMessageWriterSettingsBase writerSettings)
{
Debug.Assert(writerSettings != null, "writerSettings != null");
if (this.messageWriterSettingsConfigurationActions.Count > 0)
{
MessageWriterSettingsArgs args = new MessageWriterSettingsArgs(new DataServiceClientMessageWriterSettingsShim(writerSettings));
foreach (Action<MessageWriterSettingsArgs> configureWriterSettings in this.messageWriterSettingsConfigurationActions)
{
configureWriterSettings(args);
}
}
}
/// <summary>
/// Fires before entry end.
/// </summary>
/// <param name="entry">The entry.</param>
/// <param name="entity">The entity.</param>
internal void ExecuteOnEntryEndActions(ODataEntry entry, object entity)
{
Debug.Assert(entry != null, "entry != null");
Debug.Assert(entity != null, "entity != entity");
if (this.writingEndEntryActions.Count > 0)
{
WritingEntryArgs args = new WritingEntryArgs(entry, entity);
foreach (Action<WritingEntryArgs> entryArgsAction in this.writingEndEntryActions)
{
entryArgsAction(args);
}
}
}
/// <summary>
/// Fires before entry start.
/// </summary>
/// <param name="entry">The entry.</param>
/// <param name="entity">The entity.</param>
internal void ExecuteOnEntryStartActions(ODataEntry entry, object entity)
{
Debug.Assert(entry != null, "entry != null");
Debug.Assert(entity != null, "entity != entity");
if (this.writingStartEntryActions.Count > 0)
{
WritingEntryArgs args = new WritingEntryArgs(entry, entity);
foreach (Action<WritingEntryArgs> entryArgsAction in this.writingStartEntryActions)
{
entryArgsAction(args);
}
}
}
/// <summary>
/// Fires before navigation end.
/// </summary>
/// <param name="link">The link.</param>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
internal void ExecuteOnNavigationLinkEndActions(ODataNavigationLink link, object source, object target)
{
Debug.Assert(link != null, "link != null");
if (this.writingEndNavigationLinkActions.Count > 0)
{
WritingNavigationLinkArgs args = new WritingNavigationLinkArgs(link, source, target);
foreach (Action<WritingNavigationLinkArgs> navArgsAction in this.writingEndNavigationLinkActions)
{
navArgsAction(args);
}
}
}
/// <summary>
/// Fires before navigation start.
/// </summary>
/// <param name="link">The link.</param>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
internal void ExecuteOnNavigationLinkStartActions(ODataNavigationLink link, object source, object target)
{
Debug.Assert(link != null, "link != null");
if (this.writingStartNavigationLinkActions.Count > 0)
{
WritingNavigationLinkArgs args = new WritingNavigationLinkArgs(link, source, target);
foreach (Action<WritingNavigationLinkArgs> navArgsAction in this.writingStartNavigationLinkActions)
{
navArgsAction(args);
}
}
}
/// <summary>
/// Fires before writing the on entity reference link.
/// </summary>
/// <param name="entityReferenceLink">The entity reference link.</param>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
internal void ExecuteEntityReferenceLinkActions(ODataEntityReferenceLink entityReferenceLink, object source, object target)
{
Debug.Assert(entityReferenceLink != null, "entityReferenceLink != null");
if (this.writeEntityReferenceLinkActions.Count > 0)
{
WritingEntityReferenceLinkArgs args = new WritingEntityReferenceLinkArgs(entityReferenceLink, source, target);
foreach (Action<WritingEntityReferenceLinkArgs> navArgsAction in this.writeEntityReferenceLinkActions)
{
navArgsAction(args);
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Sink.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Dispatch.MessageQueues;
using Akka.Pattern;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Implementation.Stages;
using Reactive.Streams;
// ReSharper disable UnusedMember.Global
namespace Akka.Streams.Dsl
{
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> is a set of stream processing steps that has one open input.
/// Can be used as a <see cref="ISubscriber{T}"/>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
public sealed class Sink<TIn, TMat> : IGraph<SinkShape<TIn>, TMat>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="module">TBD</param>
public Sink(IModule module)
{
Module = module;
}
/// <summary>
/// TBD
/// </summary>
public SinkShape<TIn> Shape => (SinkShape<TIn>)Module.Shape;
/// <summary>
/// TBD
/// </summary>
public IModule Module { get; }
/// <summary>
/// Transform this <see cref="Sink"/> by applying a function to each *incoming* upstream element before
/// it is passed to the <see cref="Sink"/>
///
/// Backpressures when original <see cref="Sink"/> backpressures
///
/// Cancels when original <see cref="Sink"/> backpressures
/// </summary>
/// <typeparam name="TIn2">TBD</typeparam>
/// <param name="function">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn2, TMat> ContraMap<TIn2>(Func<TIn2, TIn> function)
=> Flow.FromFunction(function).ToMaterialized(this, Keep.Right);
/// <summary>
/// Connect this <see cref="Sink{TIn,TMat}"/> to a <see cref="Source{T,TMat}"/> and run it. The returned value is the materialized value
/// of the <see cref="Source{T,TMat}"/>, e.g. the <see cref="ISubscriber{T}"/>.
/// </summary>
/// <typeparam name="TMat2">TBD</typeparam>
/// <param name="source">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public TMat2 RunWith<TMat2>(IGraph<SourceShape<TIn>, TMat2> source, IMaterializer materializer)
=> Source.FromGraph(source).To(this).Run(materializer);
/// <summary>
/// Transform only the materialized value of this Sink, leaving all other properties as they were.
/// </summary>
/// <typeparam name="TMat2">TBD</typeparam>
/// <param name="fn">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn, TMat2> MapMaterializedValue<TMat2>(Func<TMat, TMat2> fn)
=> new Sink<TIn, TMat2>(Module.TransformMaterializedValue(fn));
/// <summary>
/// Change the attributes of this <see cref="IGraph{TShape}"/> to the given ones
/// and seal the list of attributes. This means that further calls will not be able
/// to remove these attributes, but instead add new ones. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.WithAttributes(Attributes attributes)
=> WithAttributes(attributes);
/// <summary>
/// Change the attributes of this <see cref="Sink{TIn,TMat}"/> to the given ones
/// and seal the list of attributes. This means that further calls will not be able
/// to remove these attributes, but instead add new ones. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn, TMat> WithAttributes(Attributes attributes)
=> new Sink<TIn, TMat>(Module.WithAttributes(attributes));
/// <summary>
/// Add the given attributes to this <see cref="IGraph{TShape}"/>.
/// Further calls to <see cref="WithAttributes"/>
/// will not remove these attributes. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.AddAttributes(Attributes attributes)
=> AddAttributes(attributes);
/// <summary>
/// Add the given attributes to this <see cref="Sink{TIn,TMat}"/>.
/// Further calls to <see cref="WithAttributes"/>
/// will not remove these attributes. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn, TMat> AddAttributes(Attributes attributes)
=> WithAttributes(Module.Attributes.And(attributes));
/// <summary>
/// Add a name attribute to this Sink.
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.Named(string name) => Named(name);
/// <summary>
/// Add a name attribute to this Sink.
/// </summary>
/// <param name="name">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn, TMat> Named(string name) => AddAttributes(Attributes.CreateName(name));
/// <summary>
/// Put an asynchronous boundary around this Sink.
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.Async() => Async();
/// <summary>
/// Put an asynchronous boundary around this Sink.
/// </summary>
/// <returns>TBD</returns>
public Sink<TIn, TMat> Async() => AddAttributes(new Attributes(Attributes.AsyncBoundary.Instance));
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => $"Sink({Shape}, {Module})";
}
/// <summary>
/// TBD
/// </summary>
public static class Sink
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="name">TBD</param>
/// <returns>TBD</returns>
public static SinkShape<T> Shape<T>(string name) => new SinkShape<T>(new Inlet<T>(name + ".in"));
/// <summary>
/// A graph with the shape of a sink logically is a sink, this method makes
/// it so also in type.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="graph">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, TMat> Wrap<TIn, TMat>(IGraph<SinkShape<TIn>, TMat> graph)
=> graph is Sink<TIn, TMat>
? (Sink<TIn, TMat>) graph
: new Sink<TIn, TMat>(graph.Module);
/// <summary>
/// Helper to create <see cref="Sink{TIn, TMat}"/> from <see cref="ISubscriber{TIn}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="subscriber">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, object> Create<TIn>(ISubscriber<TIn> subscriber)
=> new Sink<TIn, object>(new SubscriberSink<TIn>(subscriber, DefaultAttributes.SubscriberSink, Shape<TIn>("SubscriberSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the first value received.
/// If the stream completes before signaling at least a single element, the Task will be failed with a <see cref="NoSuchElementException"/>.
/// If the stream signals an error before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <exception cref="InvalidOperationException">TBD</exception>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> First<TIn>()
=> FromGraph(new FirstOrDefault<TIn>(throwOnDefault: true))
.WithAttributes(DefaultAttributes.FirstOrDefaultSink)
.MapMaterializedValue(e =>
{
if (!e.IsFaulted && e.IsCompleted && e.Result == null)
throw new InvalidOperationException("Sink.First materialized on an empty stream");
return e;
});
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the first value received.
/// If the stream completes before signaling at least a single element, the Task will return default value.
/// If the stream signals an error errors before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> FirstOrDefault<TIn>()
=> FromGraph(new FirstOrDefault<TIn>()).WithAttributes(DefaultAttributes.FirstOrDefaultSink);
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the last value received.
/// If the stream completes before signaling at least a single element, the Task will be failed with a <see cref="NoSuchElementException"/>.
/// If the stream signals an error, the Task will be failed with the stream's exception.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> Last<TIn>()
=> FromGraph(new LastOrDefault<TIn>(throwOnDefault: true)).WithAttributes(DefaultAttributes.LastOrDefaultSink);
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the last value received.
/// If the stream completes before signaling at least a single element, the Task will be return a default value.
/// If the stream signals an error, the Task will be failed with the stream's exception.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> LastOrDefault<TIn>()
=> FromGraph(new LastOrDefault<TIn>()).WithAttributes(DefaultAttributes.LastOrDefaultSink);
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that keeps on collecting incoming elements until upstream terminates.
/// As upstream may be unbounded, `Flow.Create{T}().Take` or the stricter `Flow.Create{T}().Limit` (and their variants)
/// may be used to ensure boundedness.
/// Materializes into a <see cref="Task"/> of <see cref="Seq{TIn}"/> containing all the collected elements.
/// `Seq` is limited to <see cref="int.MaxValue"/> elements, this Sink will cancel the stream
/// after having received that many elements.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task<IImmutableList<TIn>>> Seq<TIn>() => FromGraph(new SeqStage<TIn>());
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="IPublisher{TIn}"/>.
/// that can handle one <see cref="ISubscriber{TIn}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, IPublisher<TIn>> Publisher<TIn>()
=> new Sink<TIn, IPublisher<TIn>>(new PublisherSink<TIn>(DefaultAttributes.PublisherSink, Shape<TIn>("PublisherSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into <see cref="IPublisher{TIn}"/>
/// that can handle more than one <see cref="ISubscriber{TIn}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, IPublisher<TIn>> FanoutPublisher<TIn>()
=> new Sink<TIn, IPublisher<TIn>>(new FanoutPublisherSink<TIn>(DefaultAttributes.FanoutPublisherSink, Shape<TIn>("FanoutPublisherSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will consume the stream and discard the elements.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task> Ignore<TIn>() => FromGraph(new IgnoreSink<TIn>());
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will invoke the given <paramref name="action"/> for each received element.
/// The sink is materialized into a <see cref="Task"/> will be completed with success when reaching the
/// normal end of the stream, or completed with a failure if there is a failure signaled in
/// the stream..
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="action">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task> ForEach<TIn>(Action<TIn> action) => Flow.Create<TIn>()
.Select(input =>
{
action(input);
return NotUsed.Instance;
}).ToMaterialized(Ignore<NotUsed>(), Keep.Right).Named("foreachSink");
/// <summary>
/// Combine several sinks with fan-out strategy like <see cref="Broadcast{TIn}"/> or <see cref="Balance{TIn}"/> and returns <see cref="Sink{TIn,TMat}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="strategy">TBD</param>
/// <param name="first">TBD</param>
/// <param name="second">TBD</param>
/// <param name="rest">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> Combine<TIn, TOut, TMat>(Func<int, IGraph<UniformFanOutShape<TIn, TOut>, TMat>> strategy, Sink<TOut, NotUsed> first, Sink<TOut, NotUsed> second, params Sink<TOut, NotUsed>[] rest)
=> FromGraph(GraphDsl.Create(builder =>
{
var d = builder.Add(strategy(rest.Length + 2));
builder.From(d.Out(0)).To(first);
builder.From(d.Out(1)).To(second);
var index = 2;
foreach (var sink in rest)
builder.From(d.Out(index++)).To(sink);
return new SinkShape<TIn>(d.In);
}));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will invoke the given <paramref name="action"/>
/// to each of the elements as they pass in. The sink is materialized into a <see cref="Task"/>.
///
/// If the action throws an exception and the supervision decision is
/// <see cref="Directive.Stop"/> the <see cref="Task"/> will be completed with failure.
///
/// If the action throws an exception and the supervision decision is
/// <see cref="Directive.Resume"/> or <see cref="Directive.Restart"/> the
/// element is dropped and the stream continues.
///
/// <para/>
/// See also <seealso cref="SelectAsyncUnordered{TIn,TOut}"/>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="parallelism">TBD</param>
/// <param name="action">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task> ForEachParallel<TIn>(int parallelism, Action<TIn> action) => Flow.Create<TIn>()
.SelectAsyncUnordered(parallelism, input => Task.Run(() =>
{
action(input);
return NotUsed.Instance;
})).ToMaterialized(Ignore<NotUsed>(), Keep.Right);
/// <summary>
/// A <see cref="Sink{TIn, Task}"/> that will invoke the given <paramref name="aggregate"/> function for every received element,
/// giving it its previous output (or the given <paramref name="zero"/> value) and the element as input.
/// The returned <see cref="Task"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with the streams exception
/// if there is a failure signaled in the stream.
/// <seealso cref="AggregateAsync{TIn,TOut}"/>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="zero">TBD</param>
/// <param name="aggregate">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TOut>> Aggregate<TIn, TOut>(TOut zero, Func<TOut, TIn, TOut> aggregate)
=> Flow.Create<TIn>()
.Aggregate(zero, aggregate)
.ToMaterialized(First<TOut>(), Keep.Right)
.Named("AggregateSink");
/// <summary>
/// A <see cref="Sink{TIn, Task}"/> that will invoke the given asynchronous function for every received element,
/// giving it its previous output (or the given <paramref name="zero"/> value) and the element as input.
/// The returned <see cref="Task"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with "Failure"
/// if there is a failure signaled in the stream.
///
/// <seealso cref="Aggregate{TIn,TOut}"/>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="zero">TBD</param>
/// <param name="aggregate">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TOut>> AggregateAsync<TIn, TOut>(TOut zero, Func<TOut, TIn, Task<TOut>> aggregate)
=> Flow.Create<TIn, Task<TOut>>()
.AggregateAsync(zero, aggregate)
.ToMaterialized(First<TOut>(), Keep.Right)
.Named("AggregateAsyncSink");
/// <summary>
/// <para>
/// A <see cref="Sink{TIn,Task}"/> that will invoke the given <paramref name="reduce"/> for every received element, giving it its previous
/// output (from the second element) and the element as input.
/// The returned <see cref="Task{TIn}"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with `Failure`
/// if there is a failure signaled in the stream.
/// </para>
/// <para>
/// If the stream is empty (i.e. completes before signaling any elements),
/// the sum stage will fail its downstream with a <see cref="NoSuchElementException"/>,
/// which is semantically in-line with that standard library collections do in such situations.
/// </para>
/// <para>
/// Adheres to the <see cref="ActorAttributes.SupervisionStrategy"/> attribute.
/// </para>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="reduce">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> Sum<TIn>(Func<TIn, TIn, TIn> reduce) => Flow.Create<TIn>()
.Sum(reduce)
.ToMaterialized(First<TIn>(), Keep.Right)
.Named("SumSink");
/// <summary>
/// A <see cref="Sink{TIn, NotUsed}"/> that when the flow is completed, either through a failure or normal
/// completion, apply the provided function with <paramref name="success"/> or <paramref name="failure"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="success">TBD</param>
/// <param name="failure">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> OnComplete<TIn>(Action success, Action<Exception> failure)
=> Flow.Create<TIn>()
.Transform(() => new OnCompleted<TIn, NotUsed>(success, failure))
.To(Ignore<NotUsed>())
.Named("OnCompleteSink");
///<summary>
/// Sends the elements of the stream to the given <see cref="IActorRef"/>.
/// If the target actor terminates the stream will be canceled.
/// When the stream is completed successfully the given <paramref name="onCompleteMessage"/>
/// will be sent to the destination actor.
/// When the stream is completed with failure a <see cref="Status.Failure"/>
/// message will be sent to the destination actor.
///
/// It will request at most <see cref="ActorMaterializerSettings.MaxInputBufferSize"/> number of elements from
/// upstream, but there is no back-pressure signal from the destination actor,
/// i.e. if the actor is not consuming the messages fast enough the mailbox
/// of the actor will grow. For potentially slow consumer actors it is recommended
/// to use a bounded mailbox with zero <see cref="BoundedMessageQueue.PushTimeOut"/> or use a rate
/// limiting stage in front of this <see cref="Sink{TIn, TMat}"/>.
///</summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="actorRef">TBD</param>
/// <param name="onCompleteMessage">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> ActorRef<TIn>(IActorRef actorRef, object onCompleteMessage)
=> new Sink<TIn, NotUsed>(new ActorRefSink<TIn>(actorRef, onCompleteMessage, DefaultAttributes.ActorRefSink, Shape<TIn>("ActorRefSink")));
/// <summary>
/// Sends the elements of the stream to the given <see cref="IActorRef"/> that sends back back-pressure signal.
/// First element is always <paramref name="onInitMessage"/>, then stream is waiting for acknowledgement message
/// <paramref name="ackMessage"/> from the given actor which means that it is ready to process
/// elements.It also requires <paramref name="ackMessage"/> message after each stream element
/// to make backpressure work.
///
/// If the target actor terminates the stream will be canceled.
/// When the stream is completed successfully the given <paramref name="onCompleteMessage"/>
/// will be sent to the destination actor.
/// When the stream is completed with failure - result of <paramref name="onFailureMessage"/>
/// function will be sent to the destination actor.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="actorRef">TBD</param>
/// <param name="onInitMessage">TBD</param>
/// <param name="ackMessage">TBD</param>
/// <param name="onCompleteMessage">TBD</param>
/// <param name="onFailureMessage">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> ActorRefWithAck<TIn>(IActorRef actorRef, object onInitMessage, object ackMessage,
object onCompleteMessage, Func<Exception, object> onFailureMessage = null)
{
onFailureMessage = onFailureMessage ?? (ex => new Status.Failure(ex));
return
FromGraph(new ActorRefBackpressureSinkStage<TIn>(actorRef, onInitMessage, ackMessage,
onCompleteMessage, onFailureMessage));
}
///<summary>
/// Creates a <see cref="Sink{TIn,TMat}"/> that is materialized to an <see cref="IActorRef"/> which points to an Actor
/// created according to the passed in <see cref="Props"/>. Actor created by the <paramref name="props"/> should
/// be <see cref="ActorSubscriberSink{TIn}"/>.
///</summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="props">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, IActorRef> ActorSubscriber<TIn>(Props props)
=> new Sink<TIn, IActorRef>(new ActorSubscriberSink<TIn>(props, DefaultAttributes.ActorSubscriberSink, Shape<TIn>("ActorSubscriberSink")));
///<summary>
/// <para>
/// Creates a <see cref="Sink{TIn,TMat}"/> that is materialized as an <see cref="ISinkQueue{TIn}"/>.
/// <see cref="ISinkQueue{TIn}.PullAsync"/> method is pulling element from the stream and returns <see cref="Task{Option}"/>.
/// <see cref="Task"/> completes when element is available.
/// </para>
/// <para>
/// Before calling the pull method a second time you need to wait until previous future completes.
/// Pull returns failed future with <see cref="IllegalStateException"/> if previous future has not yet completed.
/// </para>
/// <para>
/// <see cref="Sink{TIn,TMat}"/> will request at most number of elements equal to size of inputBuffer from
/// upstream and then stop back pressure. You can configure size of input by using WithAttributes method.
/// </para>
/// <para>
/// For stream completion you need to pull all elements from <see cref="ISinkQueue{T}"/> including last None
/// as completion marker.
/// </para>
///</summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, ISinkQueue<TIn>> Queue<TIn>() => FromGraph(new QueueSink<TIn>());
/// <summary>
/// <para>
/// Creates a real <see cref="Sink{TIn,TMat}"/> upon receiving the first element. Internal <see cref="Sink{TIn,TMat}"/> will not be created if there are no elements,
/// because of completion or error.
/// </para>
/// <para>
/// If <paramref name="sinkFactory"/> throws an exception and the supervision decision is <see cref="Supervision.Directive.Stop"/>
/// the <see cref="Task"/> will be completed with failure. For all other supervision options it will try to create sink with next element.
/// </para>
/// <paramref name="fallback"/> will be executed when there was no elements and completed is received from upstream.
/// <para>
/// Adheres to the <see cref="ActorAttributes.SupervisionStrategy"/> attribute.
/// </para>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="sinkFactory">TBD</param>
/// <param name="fallback">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TMat>> LazySink<TIn, TMat>(Func<TIn, Task<Sink<TIn, TMat>>> sinkFactory,
Func<TMat> fallback) => FromGraph(new LazySink<TIn, TMat>(sinkFactory, fallback));
/// <summary>
/// A graph with the shape of a sink logically is a sink, this method makes
/// it so also in type.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="graph">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, TMat> FromGraph<TIn, TMat>(IGraph<SinkShape<TIn>, TMat> graph)
=> graph is Sink<TIn, TMat>
? (Sink<TIn, TMat>) graph
: new Sink<TIn, TMat>(graph.Module);
/// <summary>
/// Helper to create <see cref="Sink{TIn,TMat}"/> from <see cref="ISubscriber{TIn}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="subscriber">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> FromSubscriber<TIn>(ISubscriber<TIn> subscriber)
=> new Sink<TIn, NotUsed>(new SubscriberSink<TIn>(subscriber, DefaultAttributes.SubscriberSink, Shape<TIn>("SubscriberSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that immediately cancels its upstream after materialization.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> Cancelled<TIn>()
=> new Sink<TIn, NotUsed>(new CancelSink<TIn>(DefaultAttributes.CancelledSink, Shape<TIn>("CancelledSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="IPublisher{TIn}"/>.
/// If <paramref name="fanout"/> is true, the materialized <see cref="IPublisher{TIn}"/> will support multiple <see cref="ISubscriber{TIn}"/>`s and
/// the size of the <see cref="ActorMaterializerSettings.MaxInputBufferSize"/> configured for this stage becomes the maximum number of elements that
/// the fastest <see cref="ISubscriber{T}"/> can be ahead of the slowest one before slowing
/// the processing down due to back pressure.
///
/// If <paramref name="fanout"/> is false then the materialized <see cref="IPublisher{TIn}"/> will only support a single <see cref="ISubscriber{TIn}"/> and
/// reject any additional <see cref="ISubscriber{TIn}"/>`s.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="fanout">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, IPublisher<TIn>> AsPublisher<TIn>(bool fanout)
{
SinkModule<TIn, IPublisher<TIn>> publisherSink;
if (fanout)
publisherSink = new FanoutPublisherSink<TIn>(DefaultAttributes.FanoutPublisherSink, Shape<TIn>("FanoutPublisherSink"));
else
publisherSink = new PublisherSink<TIn>(DefaultAttributes.PublisherSink, Shape<TIn>("PublisherSink"));
return new Sink<TIn, IPublisher<TIn>>(publisherSink);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.DistributedTask.Expressions;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Worker
{
public interface IStep
{
IExpressionNode Condition { get; set; }
bool ContinueOnError { get; }
string DisplayName { get; }
Pipelines.StepTarget Target { get; }
bool Enabled { get; }
IExecutionContext ExecutionContext { get; set; }
TimeSpan? Timeout { get; }
Task RunAsync();
}
[ServiceLocator(Default = typeof(StepsRunner))]
public interface IStepsRunner : IAgentService
{
Task RunAsync(IExecutionContext Context, IList<IStep> steps);
}
public sealed class StepsRunner : AgentService, IStepsRunner
{
// StepsRunner should never throw exception to caller
public async Task RunAsync(IExecutionContext jobContext, IList<IStep> steps)
{
ArgUtil.NotNull(jobContext, nameof(jobContext));
ArgUtil.NotNull(steps, nameof(steps));
// TaskResult:
// Abandoned (Server set this.)
// Canceled
// Failed
// Skipped
// Succeeded
// SucceededWithIssues
CancellationTokenRegistration? jobCancelRegister = null;
int stepIndex = 0;
jobContext.Variables.Agent_JobStatus = jobContext.Result ?? TaskResult.Succeeded;
foreach (IStep step in steps)
{
Trace.Info($"Processing step: DisplayName='{step.DisplayName}', ContinueOnError={step.ContinueOnError}, Enabled={step.Enabled}");
ArgUtil.Equal(true, step.Enabled, nameof(step.Enabled));
ArgUtil.NotNull(step.ExecutionContext, nameof(step.ExecutionContext));
ArgUtil.NotNull(step.ExecutionContext.Variables, nameof(step.ExecutionContext.Variables));
stepIndex++;
// Start.
step.ExecutionContext.Start();
var taskStep = step as ITaskRunner;
if (taskStep != null)
{
HostContext.WritePerfCounter($"TaskStart_{taskStep.Task.Reference.Name}_{stepIndex}");
}
// Variable expansion.
step.ExecutionContext.SetStepTarget(step.Target);
List<string> expansionWarnings;
step.ExecutionContext.Variables.RecalculateExpanded(out expansionWarnings);
expansionWarnings?.ForEach(x => step.ExecutionContext.Warning(x));
var expressionManager = HostContext.GetService<IExpressionManager>();
try
{
ArgUtil.NotNull(jobContext, nameof(jobContext)); // I am not sure why this is needed, but static analysis flagged all uses of jobContext below this point
// Register job cancellation call back only if job cancellation token not been fire before each step run
if (!jobContext.CancellationToken.IsCancellationRequested)
{
// Test the condition again. The job was canceled after the condition was originally evaluated.
jobCancelRegister = jobContext.CancellationToken.Register(() =>
{
// mark job as cancelled
jobContext.Result = TaskResult.Canceled;
jobContext.Variables.Agent_JobStatus = jobContext.Result;
step.ExecutionContext.Debug($"Re-evaluate condition on job cancellation for step: '{step.DisplayName}'.");
ConditionResult conditionReTestResult;
if (HostContext.AgentShutdownToken.IsCancellationRequested)
{
step.ExecutionContext.Debug($"Skip Re-evaluate condition on agent shutdown.");
conditionReTestResult = false;
}
else
{
try
{
conditionReTestResult = expressionManager.Evaluate(step.ExecutionContext, step.Condition, hostTracingOnly: true);
}
catch (Exception ex)
{
// Cancel the step since we get exception while re-evaluate step condition.
Trace.Info("Caught exception from expression when re-test condition on job cancellation.");
step.ExecutionContext.Error(ex);
conditionReTestResult = false;
}
}
if (!conditionReTestResult.Value)
{
// Cancel the step.
Trace.Info("Cancel current running step.");
step.ExecutionContext.CancelToken();
}
});
}
else
{
if (jobContext.Result != TaskResult.Canceled)
{
// mark job as cancelled
jobContext.Result = TaskResult.Canceled;
jobContext.Variables.Agent_JobStatus = jobContext.Result;
}
}
// Evaluate condition.
step.ExecutionContext.Debug($"Evaluating condition for step: '{step.DisplayName}'");
Exception conditionEvaluateError = null;
ConditionResult conditionResult;
if (HostContext.AgentShutdownToken.IsCancellationRequested)
{
step.ExecutionContext.Debug($"Skip evaluate condition on agent shutdown.");
conditionResult = false;
}
else
{
try
{
conditionResult = expressionManager.Evaluate(step.ExecutionContext, step.Condition);
}
catch (Exception ex)
{
Trace.Info("Caught exception from expression.");
Trace.Error(ex);
conditionResult = false;
conditionEvaluateError = ex;
}
}
// no evaluate error but condition is false
if (!conditionResult.Value && conditionEvaluateError == null)
{
// Condition == false
Trace.Info("Skipping step due to condition evaluation.");
step.ExecutionContext.Complete(TaskResult.Skipped, resultCode: conditionResult.Trace);
continue;
}
if (conditionEvaluateError != null)
{
// fail the step since there is an evaluate error.
step.ExecutionContext.Error(conditionEvaluateError);
step.ExecutionContext.Complete(TaskResult.Failed);
}
else
{
// Run the step.
await RunStepAsync(step, jobContext.CancellationToken);
}
}
finally
{
if (jobCancelRegister != null)
{
jobCancelRegister?.Dispose();
jobCancelRegister = null;
}
}
// Update the job result.
if (step.ExecutionContext.Result == TaskResult.SucceededWithIssues ||
step.ExecutionContext.Result == TaskResult.Failed)
{
Trace.Info($"Update job result with current step result '{step.ExecutionContext.Result}'.");
jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, step.ExecutionContext.Result.Value);
jobContext.Variables.Agent_JobStatus = jobContext.Result;
}
else
{
Trace.Info($"No need for updating job result with current step result '{step.ExecutionContext.Result}'.");
}
if (taskStep != null)
{
HostContext.WritePerfCounter($"TaskCompleted_{taskStep.Task.Reference.Name}_{stepIndex}");
}
Trace.Info($"Current state: job state = '{jobContext.Result}'");
}
}
private async Task RunStepAsync(IStep step, CancellationToken jobCancellationToken)
{
// Start the step.
Trace.Info("Starting the step.");
step.ExecutionContext.Section(StringUtil.Loc("StepStarting", step.DisplayName));
step.ExecutionContext.SetTimeout(timeout: step.Timeout);
// Windows may not be on the UTF8 codepage; try to fix that
await SwitchToUtf8Codepage(step);
try
{
await step.RunAsync();
}
catch (OperationCanceledException ex)
{
if (step.ExecutionContext.CancellationToken.IsCancellationRequested &&
!jobCancellationToken.IsCancellationRequested)
{
Trace.Error($"Caught timeout exception from step: {ex.Message}");
step.ExecutionContext.Error(StringUtil.Loc("StepTimedOut"));
step.ExecutionContext.Result = TaskResult.Failed;
}
else
{
// Log the exception and cancel the step.
Trace.Error($"Caught cancellation exception from step: {ex}");
step.ExecutionContext.Error(ex);
step.ExecutionContext.Result = TaskResult.Canceled;
}
}
catch (Exception ex)
{
// Log the error and fail the step.
Trace.Error($"Caught exception from step: {ex}");
step.ExecutionContext.Error(ex);
step.ExecutionContext.Result = TaskResult.Failed;
}
// Wait till all async commands finish.
foreach (var command in step.ExecutionContext.AsyncCommands ?? new List<IAsyncCommandContext>())
{
try
{
// wait async command to finish.
await command.WaitAsync();
}
catch (OperationCanceledException ex)
{
if (step.ExecutionContext.CancellationToken.IsCancellationRequested &&
!jobCancellationToken.IsCancellationRequested)
{
// Log the timeout error, set step result to falied if the current result is not canceled.
Trace.Error($"Caught timeout exception from async command {command.Name}: {ex}");
step.ExecutionContext.Error(StringUtil.Loc("StepTimedOut"));
// if the step already canceled, don't set it to failed.
step.ExecutionContext.CommandResult = TaskResultUtil.MergeTaskResults(step.ExecutionContext.CommandResult, TaskResult.Failed);
}
else
{
// log and save the OperationCanceledException, set step result to canceled if the current result is not failed.
Trace.Error($"Caught cancellation exception from async command {command.Name}: {ex}");
step.ExecutionContext.Error(ex);
// if the step already failed, don't set it to canceled.
step.ExecutionContext.CommandResult = TaskResultUtil.MergeTaskResults(step.ExecutionContext.CommandResult, TaskResult.Canceled);
}
}
catch (Exception ex)
{
// Log the error, set step result to falied if the current result is not canceled.
Trace.Error($"Caught exception from async command {command.Name}: {ex}");
step.ExecutionContext.Error(ex);
// if the step already canceled, don't set it to failed.
step.ExecutionContext.CommandResult = TaskResultUtil.MergeTaskResults(step.ExecutionContext.CommandResult, TaskResult.Failed);
}
}
// Merge executioncontext result with command result
if (step.ExecutionContext.CommandResult != null)
{
step.ExecutionContext.Result = TaskResultUtil.MergeTaskResults(step.ExecutionContext.Result, step.ExecutionContext.CommandResult.Value);
}
// Fixup the step result if ContinueOnError.
if (step.ExecutionContext.Result == TaskResult.Failed && step.ContinueOnError)
{
step.ExecutionContext.Result = TaskResult.SucceededWithIssues;
Trace.Info($"Updated step result: {step.ExecutionContext.Result}");
}
else
{
Trace.Info($"Step result: {step.ExecutionContext.Result}");
}
// Complete the step context.
step.ExecutionContext.Section(StringUtil.Loc("StepFinishing", step.DisplayName));
step.ExecutionContext.Complete();
}
private async Task SwitchToUtf8Codepage(IStep step)
{
if (!PlatformUtil.RunningOnWindows)
{
return;
}
try
{
if (step.ExecutionContext.Variables.Retain_Default_Encoding != true && Console.InputEncoding.CodePage != 65001)
{
using (var p = HostContext.CreateService<IProcessInvoker>())
{
// Use UTF8 code page
int exitCode = await p.ExecuteAsync(workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work),
fileName: WhichUtil.Which("chcp", true, Trace),
arguments: "65001",
environment: null,
requireExitCodeZero: false,
outputEncoding: null,
killProcessOnCancel: false,
redirectStandardIn: null,
inheritConsoleHandler: true,
cancellationToken: step.ExecutionContext.CancellationToken);
if (exitCode == 0)
{
Trace.Info("Successfully returned to code page 65001 (UTF8)");
}
else
{
Trace.Warning($"'chcp 65001' failed with exit code {exitCode}");
}
}
}
}
catch (Exception ex)
{
Trace.Warning($"'chcp 65001' failed with exception {ex.Message}");
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TrustManagerMoreInformation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
namespace System.Security.Policy
{
internal class TrustManagerMoreInformation : System.Windows.Forms.Form
{
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
private System.Windows.Forms.Label lblPublisher;
private System.Windows.Forms.Label lblPublisherContent;
private System.Windows.Forms.Label lblMachineAccess;
private System.Windows.Forms.Label lblMachineAccessContent;
private System.Windows.Forms.Label lblInstallation;
private System.Windows.Forms.Label lblInstallationContent;
private System.Windows.Forms.Label lblLocation;
private System.Windows.Forms.Label lblLocationContent;
private System.Windows.Forms.PictureBox pictureBoxPublisher;
private System.Windows.Forms.PictureBox pictureBoxMachineAccess;
private System.Windows.Forms.PictureBox pictureBoxLocation;
private System.Windows.Forms.PictureBox pictureBoxInstallation;
private System.Windows.Forms.Button btnClose;
internal TrustManagerMoreInformation(TrustManagerPromptOptions options, String publisherName)
{
InitializeComponent();
this.Font = SystemFonts.MessageBoxFont;
lblMachineAccess.Font = lblPublisher.Font = lblInstallation.Font = lblLocation.Font = new Font(lblMachineAccess.Font, FontStyle.Bold);
FillContent(options, publisherName);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void FillContent(TrustManagerPromptOptions options, String publisherName)
{
LoadWarningBitmap((publisherName == null) ? TrustManagerWarningLevel.Red : TrustManagerWarningLevel.Green, this.pictureBoxPublisher);
LoadWarningBitmap(((options & (TrustManagerPromptOptions.RequiresPermissions | TrustManagerPromptOptions.WillHaveFullTrust)) != 0) ? TrustManagerWarningLevel.Red : TrustManagerWarningLevel.Green, this.pictureBoxMachineAccess);
LoadWarningBitmap(((options & TrustManagerPromptOptions.AddsShortcut) != 0) ? TrustManagerWarningLevel.Yellow : TrustManagerWarningLevel.Green, this.pictureBoxInstallation);
TrustManagerWarningLevel locationWarningLevel;
if ((options & (TrustManagerPromptOptions.LocalNetworkSource |
TrustManagerPromptOptions.LocalComputerSource |
TrustManagerPromptOptions.TrustedSitesSource)) != 0)
{
locationWarningLevel = TrustManagerWarningLevel.Green;
}
else if ((options & TrustManagerPromptOptions.UntrustedSitesSource) != 0)
{
locationWarningLevel = TrustManagerWarningLevel.Red;
}
else
{
Debug.Assert((options & TrustManagerPromptOptions.InternetSource) != 0);
locationWarningLevel = TrustManagerWarningLevel.Yellow;
}
LoadWarningBitmap(locationWarningLevel, this.pictureBoxLocation);
if (publisherName == null)
{
this.lblPublisherContent.Text = SR.GetString(SR.TrustManagerMoreInfo_UnknownPublisher);
}
else
{
this.lblPublisherContent.Text = SR.GetString(SR.TrustManagerMoreInfo_KnownPublisher, publisherName);
}
if ((options & (TrustManagerPromptOptions.RequiresPermissions | TrustManagerPromptOptions.WillHaveFullTrust)) != 0)
{
this.lblMachineAccessContent.Text = SR.GetString(SR.TrustManagerMoreInfo_UnsafeAccess);
}
else
{
this.lblMachineAccessContent.Text = SR.GetString(SR.TrustManagerMoreInfo_SafeAccess);
}
if ((options & TrustManagerPromptOptions.AddsShortcut) != 0)
{
this.Text = SR.GetString(SR.TrustManagerMoreInfo_InstallTitle);
this.lblInstallationContent.Text = SR.GetString(SR.TrustManagerMoreInfo_WithShortcut);
}
else
{
this.Text = SR.GetString(SR.TrustManagerMoreInfo_RunTitle);
this.lblInstallationContent.Text = SR.GetString(SR.TrustManagerMoreInfo_WithoutShortcut);
}
string source;
if ((options & TrustManagerPromptOptions.LocalNetworkSource) != 0)
{
source = SR.GetString(SR.TrustManagerMoreInfo_LocalNetworkSource);
}
else if ((options & TrustManagerPromptOptions.LocalComputerSource) != 0)
{
source = SR.GetString(SR.TrustManagerMoreInfo_LocalComputerSource);
}
else if ((options & TrustManagerPromptOptions.InternetSource) != 0)
{
source = SR.GetString(SR.TrustManagerMoreInfo_InternetSource);
}
else if ((options & TrustManagerPromptOptions.TrustedSitesSource) != 0)
{
source = SR.GetString(SR.TrustManagerMoreInfo_TrustedSitesSource);
}
else
{
Debug.Assert((options & TrustManagerPromptOptions.UntrustedSitesSource) != 0);
source = SR.GetString(SR.TrustManagerMoreInfo_UntrustedSitesSource);
}
this.lblLocationContent.Text = SR.GetString(SR.TrustManagerMoreInfo_Location, source);
}
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TrustManagerMoreInformation));
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.pictureBoxPublisher = new System.Windows.Forms.PictureBox();
this.pictureBoxMachineAccess = new System.Windows.Forms.PictureBox();
this.pictureBoxInstallation = new System.Windows.Forms.PictureBox();
this.pictureBoxLocation = new System.Windows.Forms.PictureBox();
this.lblPublisher = new System.Windows.Forms.Label();
this.lblPublisherContent = new System.Windows.Forms.Label();
this.lblMachineAccess = new System.Windows.Forms.Label();
this.lblMachineAccessContent = new System.Windows.Forms.Label();
this.lblInstallation = new System.Windows.Forms.Label();
this.lblInstallationContent = new System.Windows.Forms.Label();
this.lblLocation = new System.Windows.Forms.Label();
this.lblLocationContent = new System.Windows.Forms.Label();
this.btnClose = new System.Windows.Forms.Button();
this.tableLayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxPublisher)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxMachineAccess)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxInstallation)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxLocation)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel
//
resources.ApplyResources(this.tableLayoutPanel, "tableLayoutPanel");
this.tableLayoutPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 389F));
this.tableLayoutPanel.Controls.Add(this.pictureBoxPublisher, 0, 0);
this.tableLayoutPanel.Controls.Add(this.pictureBoxMachineAccess, 0, 2);
this.tableLayoutPanel.Controls.Add(this.pictureBoxInstallation, 0, 4);
this.tableLayoutPanel.Controls.Add(this.pictureBoxLocation, 0, 6);
this.tableLayoutPanel.Controls.Add(this.lblPublisher, 1, 0);
this.tableLayoutPanel.Controls.Add(this.lblPublisherContent, 1, 1);
this.tableLayoutPanel.Controls.Add(this.lblMachineAccess, 1, 2);
this.tableLayoutPanel.Controls.Add(this.lblMachineAccessContent, 1, 3);
this.tableLayoutPanel.Controls.Add(this.lblInstallation, 1, 4);
this.tableLayoutPanel.Controls.Add(this.lblInstallationContent, 1, 5);
this.tableLayoutPanel.Controls.Add(this.lblLocation, 1, 6);
this.tableLayoutPanel.Controls.Add(this.lblLocationContent, 1, 7);
this.tableLayoutPanel.Controls.Add(this.btnClose, 1, 8);
this.tableLayoutPanel.Margin = new System.Windows.Forms.Padding(12);
this.tableLayoutPanel.Name = "tableLayoutPanel";
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
//
// pictureBoxPublisher
//
resources.ApplyResources(this.pictureBoxPublisher, "pictureBoxPublisher");
this.pictureBoxPublisher.Margin = new System.Windows.Forms.Padding(0, 0, 3, 0);
this.pictureBoxPublisher.Name = "pictureBoxPublisher";
this.tableLayoutPanel.SetRowSpan(this.pictureBoxPublisher, 2);
this.pictureBoxPublisher.TabStop = false;
//
// pictureBoxMachineAccess
//
resources.ApplyResources(this.pictureBoxMachineAccess, "pictureBoxMachineAccess");
this.pictureBoxMachineAccess.Margin = new System.Windows.Forms.Padding(0, 10, 3, 0);
this.pictureBoxMachineAccess.Name = "pictureBoxMachineAccess";
this.tableLayoutPanel.SetRowSpan(this.pictureBoxMachineAccess, 2);
this.pictureBoxMachineAccess.TabStop = false;
//
// pictureBoxInstallation
//
resources.ApplyResources(this.pictureBoxInstallation, "pictureBoxInstallation");
this.pictureBoxInstallation.Margin = new System.Windows.Forms.Padding(0, 10, 3, 0);
this.pictureBoxInstallation.Name = "pictureBoxInstallation";
this.tableLayoutPanel.SetRowSpan(this.pictureBoxInstallation, 2);
this.pictureBoxInstallation.TabStop = false;
//
// pictureBoxLocation
//
resources.ApplyResources(this.pictureBoxLocation, "pictureBoxLocation");
this.pictureBoxLocation.Margin = new System.Windows.Forms.Padding(0, 10, 3, 0);
this.pictureBoxLocation.Name = "pictureBoxLocation";
this.tableLayoutPanel.SetRowSpan(this.pictureBoxLocation, 2);
this.pictureBoxLocation.TabStop = false;
//
// lblPublisher
//
resources.ApplyResources(this.lblPublisher, "lblPublisher");
this.lblPublisher.Margin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.lblPublisher.Name = "lblPublisher";
//
// lblPublisherContent
//
resources.ApplyResources(this.lblPublisherContent, "lblPublisherContent");
this.lblPublisherContent.Margin = new System.Windows.Forms.Padding(3, 0, 0, 10);
this.lblPublisherContent.Name = "lblPublisherContent";
//
// lblMachineAccess
//
resources.ApplyResources(this.lblMachineAccess, "lblMachineAccess");
this.lblMachineAccess.Margin = new System.Windows.Forms.Padding(3, 10, 0, 0);
this.lblMachineAccess.Name = "lblMachineAccess";
//
// lblMachineAccessContent
//
resources.ApplyResources(this.lblMachineAccessContent, "lblMachineAccessContent");
this.lblMachineAccessContent.Margin = new System.Windows.Forms.Padding(3, 0, 0, 10);
this.lblMachineAccessContent.Name = "lblMachineAccessContent";
//
// lblInstallation
//
resources.ApplyResources(this.lblInstallation, "lblInstallation");
this.lblInstallation.Margin = new System.Windows.Forms.Padding(3, 10, 0, 0);
this.lblInstallation.Name = "lblInstallation";
//
// lblInstallationContent
//
resources.ApplyResources(this.lblInstallationContent, "lblInstallationContent");
this.lblInstallationContent.Margin = new System.Windows.Forms.Padding(3, 0, 0, 10);
this.lblInstallationContent.Name = "lblInstallationContent";
//
// lblLocation
//
resources.ApplyResources(this.lblLocation, "lblLocation");
this.lblLocation.Margin = new System.Windows.Forms.Padding(3, 10, 0, 0);
this.lblLocation.Name = "lblLocation";
//
// lblLocationContent
//
resources.ApplyResources(this.lblLocationContent, "lblLocationContent");
this.lblLocationContent.Margin = new System.Windows.Forms.Padding(3, 0, 0, 10);
this.lblLocationContent.Name = "lblLocationContent";
//
// btnClose
//
resources.ApplyResources(this.btnClose, "btnClose");
this.btnClose.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Margin = new System.Windows.Forms.Padding(0, 10, 0, 0);
this.btnClose.MinimumSize = new System.Drawing.Size(75, 23);
this.btnClose.Name = "btnClose";
this.btnClose.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0);
this.tableLayoutPanel.SetColumnSpan(this.btnClose, 2);
//
// TrustManagerMoreInformation
//
this.AcceptButton = this.btnClose;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.CancelButton = this.btnClose;
this.Controls.Add(this.tableLayoutPanel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "TrustManagerMoreInformation";
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxPublisher)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxMachineAccess)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxInstallation)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxLocation)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
[
SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity")
]
private static void LoadWarningBitmap(TrustManagerWarningLevel warningLevel, System.Windows.Forms.PictureBox pictureBox)
{
Bitmap bitmap;
switch (warningLevel)
{
case TrustManagerWarningLevel.Green:
bitmap = new Bitmap(typeof(System.Windows.Forms.Form), "TrustManagerOKSm.bmp");
pictureBox.AccessibleDescription = string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.TrustManager_WarningIconAccessibleDescription_LowRisk), pictureBox.AccessibleDescription);
break;
case TrustManagerWarningLevel.Yellow:
bitmap = new Bitmap(typeof(System.Windows.Forms.Form), "TrustManagerWarningSm.bmp");
pictureBox.AccessibleDescription = string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.TrustManager_WarningIconAccessibleDescription_MediumRisk), pictureBox.AccessibleDescription);
break;
default:
Debug.Assert(warningLevel == TrustManagerWarningLevel.Red);
bitmap = new Bitmap(typeof(System.Windows.Forms.Form), "TrustManagerHighRiskSm.bmp");
pictureBox.AccessibleDescription = string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.TrustManager_WarningIconAccessibleDescription_HighRisk), pictureBox.AccessibleDescription);
break;
}
if (bitmap != null)
{
bitmap.MakeTransparent();
pictureBox.Image = bitmap;
}
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.OnUserPreferenceChanged);
}
protected override void OnHandleDestroyed(EventArgs e)
{
SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.OnUserPreferenceChanged);
base.OnHandleDestroyed(e);
}
private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
{
if (e.Category == UserPreferenceCategory.Window)
{
this.Font = SystemFonts.MessageBoxFont;
this.lblLocation.Font =
this.lblInstallation.Font =
this.lblMachineAccess.Font =
this.lblPublisher.Font = new Font(this.Font, FontStyle.Bold);
}
Invalidate(); // Workaround a bug where the form's background does not repaint properly
}
}
}
| |
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Messaging;
namespace Orleans.Runtime.Messaging
{
internal sealed class GatewayInboundConnection : Connection
{
private readonly MessageCenter messageCenter;
private readonly ILocalSiloDetails siloDetails;
private readonly MultiClusterOptions multiClusterOptions;
private readonly ConnectionOptions connectionOptions;
private readonly Gateway gateway;
private readonly OverloadDetector overloadDetector;
private readonly CounterStatistic loadSheddingCounter;
private readonly SiloAddress myAddress;
public GatewayInboundConnection(
ConnectionContext connection,
ConnectionDelegate middleware,
IServiceProvider serviceProvider,
Gateway gateway,
OverloadDetector overloadDetector,
MessageFactory messageFactory,
INetworkingTrace trace,
ILocalSiloDetails siloDetails,
IOptions<MultiClusterOptions> multiClusterOptions,
ConnectionOptions connectionOptions,
MessageCenter messageCenter,
ILocalSiloDetails localSiloDetails)
: base(connection, middleware, messageFactory, serviceProvider, trace)
{
this.connectionOptions = connectionOptions;
this.gateway = gateway;
this.overloadDetector = overloadDetector;
this.siloDetails = siloDetails;
this.messageCenter = messageCenter;
this.multiClusterOptions = multiClusterOptions.Value;
this.loadSheddingCounter = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_LOAD_SHEDDING);
this.myAddress = localSiloDetails.SiloAddress;
this.MessageReceivedCounter = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_RECEIVED);
this.MessageSentCounter = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT);
}
protected override ConnectionDirection ConnectionDirection => ConnectionDirection.GatewayToClient;
protected override IMessageCenter MessageCenter => this.messageCenter;
protected override void OnReceivedMessage(Message msg)
{
// Don't process messages that have already timed out
if (msg.IsExpired)
{
msg.DropExpiredMessage(this.Log, MessagingStatisticsGroup.Phase.Receive);
return;
}
// return address translation for geo clients (replace sending address cli/* with gcl/*)
if (this.multiClusterOptions.HasMultiClusterNetwork && msg.SendingAddress.Grain.Category != UniqueKey.Category.GeoClient)
{
msg.SendingGrain = GrainId.NewClientId(msg.SendingAddress.Grain.PrimaryKey, this.siloDetails.ClusterId);
}
// Are we overloaded?
if (this.overloadDetector.Overloaded)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.GatewayTooBusy, "Shedding load");
this.messageCenter.TryDeliverToProxy(rejection);
if (this.Log.IsEnabled(LogLevel.Debug)) this.Log.Debug("Rejecting a request due to overloading: {0}", msg.ToString());
loadSheddingCounter.Increment();
return;
}
SiloAddress targetAddress = this.gateway.TryToReroute(msg);
msg.SendingSilo = this.myAddress;
if (targetAddress == null)
{
// reroute via Dispatcher
msg.TargetSilo = null;
msg.TargetActivation = null;
msg.ClearTargetAddress();
if (msg.TargetGrain.IsSystemTarget)
{
msg.TargetSilo = this.myAddress;
msg.TargetActivation = ActivationId.GetSystemActivation(msg.TargetGrain, this.myAddress);
}
MessagingStatisticsGroup.OnMessageReRoute(msg);
this.messageCenter.RerouteMessage(msg);
}
else
{
// send directly
msg.TargetSilo = targetAddress;
this.messageCenter.SendMessage(msg);
}
}
protected override async Task RunInternal()
{
var (grainId, protocolVersion, siloAddress) = await ConnectionPreamble.Read(this.Context);
if (protocolVersion >= NetworkProtocolVersion.Version2)
{
await ConnectionPreamble.Write(
this.Context,
Constants.SiloDirectConnectionId,
this.connectionOptions.ProtocolVersion,
this.myAddress);
}
if (grainId.Equals(Constants.SiloDirectConnectionId))
{
throw new InvalidOperationException($"Unexpected direct silo connection on proxy endpoint from {siloAddress?.ToString() ?? "unknown silo"}");
}
// refuse clients that are connecting to the wrong cluster
if (grainId.Category == UniqueKey.Category.GeoClient)
{
if (grainId.Key.ClusterId != this.siloDetails.ClusterId)
{
var message = string.Format(
"Refusing connection by client {0} because of cluster id mismatch: client={1} silo={2}",
grainId, grainId.Key.ClusterId, this.siloDetails.ClusterId);
this.Log.Error(ErrorCode.GatewayAcceptor_WrongClusterId, message);
throw new InvalidOperationException(message);
}
}
else
{
//convert handshake cliendId to a GeoClient ID
if (this.multiClusterOptions.HasMultiClusterNetwork)
{
grainId = GrainId.NewClientId(grainId.PrimaryKey, this.siloDetails.ClusterId);
}
}
try
{
this.gateway.RecordOpenedConnection(this, grainId);
await base.RunInternal();
}
finally
{
this.gateway.RecordClosedConnection(this);
}
}
protected override bool PrepareMessageForSend(Message msg)
{
// Don't send messages that have already timed out
if (msg.IsExpired)
{
msg.DropExpiredMessage(this.Log, MessagingStatisticsGroup.Phase.Send);
return false;
}
// Fill in the outbound message with our silo address, if it's not already set
if (msg.SendingSilo == null)
msg.SendingSilo = this.myAddress;
return true;
}
public void FailMessage(Message msg, string reason)
{
MessagingStatisticsGroup.OnFailedSentMessage(msg);
if (msg.Direction == Message.Directions.Request)
{
if (this.Log.IsEnabled(LogLevel.Debug)) this.Log.Debug(ErrorCode.MessagingSendingRejection, "Silo {siloAddress} is rejecting message: {message}. Reason = {reason}", this.myAddress, msg, reason);
// Done retrying, send back an error instead
this.messageCenter.SendRejection(msg, Message.RejectionTypes.Transient, String.Format("Silo {0} is rejecting message: {1}. Reason = {2}", this.myAddress, msg, reason));
}
else
{
this.Log.Info(ErrorCode.Messaging_OutgoingMS_DroppingMessage, "Silo {siloAddress} is dropping message: {message}. Reason = {reason}", this.myAddress, msg, reason);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
protected override void RetryMessage(Message msg, Exception ex = null)
{
if (msg == null) return;
if (msg.RetryCount < MessagingOptions.DEFAULT_MAX_MESSAGE_SEND_RETRIES)
{
msg.RetryCount = msg.RetryCount + 1;
this.messageCenter.SendMessage(msg);
}
else
{
var reason = new StringBuilder("Retry count exceeded. ");
if (ex != null)
{
reason.Append("Original exception is: ").Append(ex.ToString());
}
reason.Append("Msg is: ").Append(msg);
FailMessage(msg, reason.ToString());
}
}
protected override void OnSendMessageFailure(Message message, string error)
{
this.FailMessage(message, error);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
/// <summary>
/// The Express Route API provides programmatic access to the functionality
/// needed by the customer to set up Dedicated Circuits and Dedicated
/// Circuit Links. The Express Route Customer API is a REST API. All API
/// operations are performed over SSL and mutually authenticated using
/// X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public partial class ExpressRouteManagementClient : ServiceClient<ExpressRouteManagementClient>, Microsoft.WindowsAzure.Management.ExpressRoute.IExpressRouteManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IAuthorizedDedicatedCircuitOperations _authorizedDedicatedCircuits;
public virtual IAuthorizedDedicatedCircuitOperations AuthorizedDedicatedCircuits
{
get { return this._authorizedDedicatedCircuits; }
}
private IBorderGatewayProtocolPeeringOperations _borderGatewayProtocolPeerings;
public virtual IBorderGatewayProtocolPeeringOperations BorderGatewayProtocolPeerings
{
get { return this._borderGatewayProtocolPeerings; }
}
private ICrossConnectionOperations _crossConnections;
public virtual ICrossConnectionOperations CrossConnections
{
get { return this._crossConnections; }
}
private IDedicatedCircuitLinkAuthorizationMicrosoftIdOperations _dedicatedCircuitLinkAuthorizationMicrosoftIds;
public virtual IDedicatedCircuitLinkAuthorizationMicrosoftIdOperations DedicatedCircuitLinkAuthorizationMicrosoftIds
{
get { return this._dedicatedCircuitLinkAuthorizationMicrosoftIds; }
}
private IDedicatedCircuitLinkAuthorizationOperations _dedicatedCircuitLinkAuthorizations;
public virtual IDedicatedCircuitLinkAuthorizationOperations DedicatedCircuitLinkAuthorizations
{
get { return this._dedicatedCircuitLinkAuthorizations; }
}
private IDedicatedCircuitLinkOperations _dedicatedCircuitLinks;
public virtual IDedicatedCircuitLinkOperations DedicatedCircuitLinks
{
get { return this._dedicatedCircuitLinks; }
}
private IDedicatedCircuitOperations _dedicatedCircuits;
public virtual IDedicatedCircuitOperations DedicatedCircuits
{
get { return this._dedicatedCircuits; }
}
private IDedicatedCircuitServiceProviderOperations _dedicatedCircuitServiceProviders;
public virtual IDedicatedCircuitServiceProviderOperations DedicatedCircuitServiceProviders
{
get { return this._dedicatedCircuitServiceProviders; }
}
/// <summary>
/// Initializes a new instance of the ExpressRouteManagementClient
/// class.
/// </summary>
private ExpressRouteManagementClient()
: base()
{
this._authorizedDedicatedCircuits = new AuthorizedDedicatedCircuitOperations(this);
this._borderGatewayProtocolPeerings = new BorderGatewayProtocolPeeringOperations(this);
this._crossConnections = new CrossConnectionOperations(this);
this._dedicatedCircuitLinkAuthorizationMicrosoftIds = new DedicatedCircuitLinkAuthorizationMicrosoftIdOperations(this);
this._dedicatedCircuitLinkAuthorizations = new DedicatedCircuitLinkAuthorizationOperations(this);
this._dedicatedCircuitLinks = new DedicatedCircuitLinkOperations(this);
this._dedicatedCircuits = new DedicatedCircuitOperations(this);
this._dedicatedCircuitServiceProviders = new DedicatedCircuitServiceProviderOperations(this);
this._apiVersion = "2011-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ExpressRouteManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public ExpressRouteManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ExpressRouteManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public ExpressRouteManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ExpressRouteManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private ExpressRouteManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._authorizedDedicatedCircuits = new AuthorizedDedicatedCircuitOperations(this);
this._borderGatewayProtocolPeerings = new BorderGatewayProtocolPeeringOperations(this);
this._crossConnections = new CrossConnectionOperations(this);
this._dedicatedCircuitLinkAuthorizationMicrosoftIds = new DedicatedCircuitLinkAuthorizationMicrosoftIdOperations(this);
this._dedicatedCircuitLinkAuthorizations = new DedicatedCircuitLinkAuthorizationOperations(this);
this._dedicatedCircuitLinks = new DedicatedCircuitLinkOperations(this);
this._dedicatedCircuits = new DedicatedCircuitOperations(this);
this._dedicatedCircuitServiceProviders = new DedicatedCircuitServiceProviderOperations(this);
this._apiVersion = "2011-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ExpressRouteManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ExpressRouteManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ExpressRouteManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ExpressRouteManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// ExpressRouteManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of ExpressRouteManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<ExpressRouteManagementClient> client)
{
base.Clone(client);
if (client is ExpressRouteManagementClient)
{
ExpressRouteManagementClient clonedClient = ((ExpressRouteManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// Parse enum values for type BgpPeeringAccessType.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static BgpPeeringAccessType ParseBgpPeeringAccessType(string value)
{
if ("private".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return BgpPeeringAccessType.Private;
}
if ("public".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return BgpPeeringAccessType.Public;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type BgpPeeringAccessType to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string BgpPeeringAccessTypeToString(BgpPeeringAccessType value)
{
if (value == BgpPeeringAccessType.Private)
{
return "private";
}
if (value == BgpPeeringAccessType.Public)
{
return "public";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type UpdateCrossConnectionOperation.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static UpdateCrossConnectionOperation ParseUpdateCrossConnectionOperation(string value)
{
if ("NotifyCrossConnectionProvisioned".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return UpdateCrossConnectionOperation.NotifyCrossConnectionProvisioned;
}
if ("NotifyCrossConnectionNotProvisioned".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return UpdateCrossConnectionOperation.NotifyCrossConnectionNotProvisioned;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type UpdateCrossConnectionOperation to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string UpdateCrossConnectionOperationToString(UpdateCrossConnectionOperation value)
{
if (value == UpdateCrossConnectionOperation.NotifyCrossConnectionProvisioned)
{
return "NotifyCrossConnectionProvisioned";
}
if (value == UpdateCrossConnectionOperation.NotifyCrossConnectionNotProvisioned)
{
return "NotifyCrossConnectionNotProvisioned";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// The Get Express Route operation status gets information on the
/// status of Express Route operations in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx
/// for more information)
/// </summary>
/// <param name='operationId'>
/// Required. The id of the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken)
{
// Validate
if (operationId == null)
{
throw new ArgumentNullException("operationId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationId", operationId);
Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/services/networking/operation/" + operationId.Trim();
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ExpressRouteOperationStatusResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationElement != null)
{
XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure"));
if (dataElement != null)
{
string dataInstance = dataElement.Value;
result.Data = dataInstance;
}
XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading.Tasks;
using EnvDTE;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeNamespaceTests : AbstractFileCodeElementTests
{
public FileCodeNamespaceTests()
: base(@"using System;
namespace Foo
{
public class Alpha
{
}
public class Beta
{
}
namespace Bar
{
}
}
namespace A.B
{
public class Alpha
{
}
public class Beta
{
}
}")
{
}
private CodeNamespace GetCodeNamespace(params object[] path)
{
return (CodeNamespace)GetCodeElement(path);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Children()
{
CodeNamespace testObject = GetCodeNamespace("Foo");
Assert.Equal(3, testObject.Children.Count);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Members()
{
CodeNamespace testObject = GetCodeNamespace("Foo");
Assert.Equal(3, testObject.Members.Count);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Parent()
{
CodeNamespace outer = GetCodeNamespace("Foo");
CodeNamespace inner = outer.Members.Item("Bar") as CodeNamespace;
Assert.Equal(outer.Name, ((CodeNamespace)inner.Parent).Name);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Kind()
{
CodeNamespace testObject = GetCodeNamespace("Foo");
Assert.Equal(vsCMElement.vsCMElementNamespace, testObject.Kind);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Name()
{
CodeNamespace testObject = GetCodeNamespace(2);
Assert.Equal("Foo", testObject.Name);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Name_Dotted()
{
CodeNamespace testObject = GetCodeNamespace(3);
Assert.Equal("A.B", testObject.Name);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<COMException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody);
Assert.Equal(20, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(18, startPoint.Line);
Assert.Equal(11, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(18, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<COMException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody);
Assert.Equal(27, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartName));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(18, endPoint.Line);
Assert.Equal(14, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(27, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
TextPoint startPoint = testObject.StartPoint;
Assert.Equal(18, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
TextPoint endPoint = testObject.EndPoint;
Assert.Equal(27, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Language()
{
CodeNamespace testObject = GetCodeNamespace("A.B");
Assert.Equal(CodeModelLanguageConstants.vsCMLanguageCSharp, testObject.Language);
}
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
using RandomExtended;
namespace RandomExtensions.Tests
{
[TestFixture]
public class LongTests
{
private static readonly Random Random = new();
[Test]
public void Is_Distributed()
{
Assertion.IsDistributed(
Random,
x => x.Long(long.MinValue, long.MaxValue),
x => Assert.IsTrue(x.Count > Assertion.Amount / 2, "x.Count > Assertion.Amount / 2")
);
}
[Test]
public void Exclusive()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Random.Long(1, 2, Rule.Exclusive));
Assert.Throws<ArgumentOutOfRangeException>(() => Random.Long(2, 3, Rule.Exclusive));
Assert.Throws<ArgumentOutOfRangeException>(() => Random.Long(3, 4, Rule.Exclusive));
Assert.Throws<ArgumentOutOfRangeException>(() => Random.Long(1, 1, Rule.Exclusive));
Assert.DoesNotThrow(() => Random.Long(1, 3, Rule.Exclusive));
// The only viable number to randomize is 2 with these numbers.
for (var i = 0; i < Assertion.Amount; i++)
Assert.AreEqual(2, Random.Long(1, 3, Rule.Exclusive));
}
[Test]
public void Inclusive()
{
Assert.AreEqual(
long.MaxValue,
Random.Long(long.MaxValue, long.MaxValue, Rule.Inclusive),
"Can return maxValue"
);
Assertion.IsDistributed(
Random,
x => x.Int(int.MaxValue - 1, int.MaxValue, Rule.Inclusive),
x => Assert.True(x.Count == 2, "x.Count == 2")
);
for (var i = 0; i < Assertion.Amount; i++)
Assert.AreEqual(1, Random.Long(1, 1, Rule.Inclusive));
}
[Test]
public void InclusiveExclusive()
{
Assert.AreEqual(
int.MaxValue,
Random.Long(int.MaxValue, int.MaxValue, Rule.InclusiveExclusive),
"Can return maxValue"
);
Assert.AreEqual(1, Random.Long(1, 1, Rule.InclusiveExclusive));
Assert.AreEqual(1, Random.Long(1, 2, Rule.InclusiveExclusive));
Assert.AreEqual(2, Random.Long(2, 3, Rule.InclusiveExclusive));
Assert.AreEqual(3, Random.Long(3, 4, Rule.InclusiveExclusive));
}
[Test]
public void ExclusiveInclusive()
{
Assert.AreEqual(
int.MaxValue,
Random.Long(int.MaxValue, int.MaxValue, Rule.ExclusiveInclusive),
"Can return maxValue"
);
Assert.AreEqual(
int.MaxValue,
Random.Long(int.MaxValue - 1, int.MaxValue, Rule.ExclusiveInclusive),
"Can return maxValue"
);
Assert.AreEqual(1, Random.Long(1, 1, Rule.ExclusiveInclusive));
Assert.AreEqual(2, Random.Long(1, 2, Rule.ExclusiveInclusive));
Assert.AreEqual(3, Random.Long(2, 3, Rule.ExclusiveInclusive));
Assert.AreEqual(4, Random.Long(3, 4, Rule.ExclusiveInclusive));
Assertion.IsDistributed(
Random,
x => x.Int(1, 3, Rule.ExclusiveInclusive),
x => Assert.True(x.Count == 2, "x.Count == 2")
);
Assertion.IsDistributed(
Random,
x => x.Int(1, 4, Rule.ExclusiveInclusive),
x => Assert.True(x.Count == 3, "x.Count == 3")
);
Assertion.IsDistributed(
Random,
x => x.Int(1, 5, Rule.ExclusiveInclusive),
x => Assert.True(x.Count == 4, "x.Count == 4")
);
}
[Test]
public void Min_Max_Arg_Is_Deterministic_With_Seed()
{
Assertion.IsDeterministic(i => new Random(i), x => x.Long(0, 50));
}
[Test]
public void Min_Max_Arg_Is_Not_Deterministic_With_Different_Seed()
{
Assertion.IsNotDeterministic(i => new Random(i), x => x.Long(0, 50));
}
[Test]
public void All_Values_Are_Between_Min_And_Max()
{
var longs = new long[Assertion.Amount];
const long min = 100;
const long max = 200;
for (var i = 0; i < Assertion.Amount; i++)
longs[i] = Random.Long(min, max);
longs.AssertNotAllValuesAreTheSame();
Assert.True(
longs.All(x => x >= min && x < max),
"longs.All(x => x >= min && x < max)"
);
}
[Test]
public void Inclusive_Min_Arg()
{
var longs = new long[Assertion.Amount];
const long arg = 100;
for (var i = 0; i < Assertion.Amount; i++)
longs[i] = Random.Long(arg, arg);
Assert.True(
longs.All(x => x == arg),
"longs.All(x => x == arg)"
);
}
[Test]
public void Exclusive_Max_Arg()
{
var longs = new long[Assertion.Amount];
const long max = 100;
const long min = max - 1;
for (var i = 0; i < Assertion.Amount; i++)
longs[i] = Random.Long(min, max);
Assert.True(
longs.All(x => x == min),
"longs.All(x => x == min)"
);
}
[Test]
public void Min_Equal_To_Max_Does_Not_Throw()
{
const long max = 100;
const long min = max;
Assertion.DoesNotThrow(() => Random.Long(min, max));
}
[Test]
public void Min_Greater_Than_Max_Does_Throw()
{
const long max = 100;
const long min = max + 1;
Assert.Throws<ArgumentOutOfRangeException>(() => Random.Long(min, max));
}
[Test]
public void MinValue_And_MaxValue_Does_Not_Throw()
{
Assertion.DoesNotThrow(() => Random.Long(long.MinValue, long.MaxValue));
}
[Test]
public void MinValue_And_MaxValue_Does_Not_Produce_Same_Values()
{
Assertion.IsDistributed(
Random,
x => x.Long(long.MinValue, long.MaxValue),
_ => { }
);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Runtime.Serialization;
using Microsoft.Research.DryadLinq.Internal;
namespace Microsoft.Research.DryadLinq
{
// Various methods to support Expression manipulation.
internal static class DryadLinqExpression
{
#region TOCSHARPSTRING
public static ParameterExpression GetParameterMemberAccess(Expression expr)
{
while (expr is MemberExpression)
{
if (!(((MemberExpression)expr).Member is FieldInfo) &&
!(((MemberExpression)expr).Member is PropertyInfo))
{
return null;
}
expr = ((MemberExpression)expr).Expression;
}
return (expr as ParameterExpression);
}
public static Expression CreateMemberAccess(Expression expr, params string[] fieldNames)
{
Expression resultExpr = expr;
foreach (string name in fieldNames)
{
if (expr.Type.GetField(name) != null)
{
resultExpr = Expression.Field(resultExpr, name);
}
else if (expr.Type.GetProperty(name) != null)
{
resultExpr = Expression.Property(resultExpr, name);
}
else
{
throw new DryadLinqException(DryadLinqErrorCode.Internal,
String.Format(SR.TypeDoesNotContainMember, expr.Type, name));
}
}
return resultExpr;
}
// TBD: Not quite complete
public static bool IsConstant(Expression expr)
{
if (expr is ConstantExpression) return true;
if (expr is MemberExpression)
{
Expression expr1 = ((MemberExpression)expr).Expression;
return expr1 == null || IsConstant(expr1);
}
return false;
}
public static LambdaExpression GetLambda(Expression expr)
{
while (expr.NodeType == ExpressionType.Quote)
{
expr = ((UnaryExpression)expr).Operand;
}
return expr as LambdaExpression;
}
public static bool Contains(ParameterExpression param, Expression expr)
{
FreeParameters freeParams = new FreeParameters();
freeParams.Visit(expr);
return freeParams.Parameters.Contains(param);
}
internal static bool IsAssociative(LambdaExpression expr)
{
if (AttributeSystem.GetAssociativeAttrib(expr) != null)
{
return true;
}
ParameterExpression param1 = expr.Parameters[0];
ParameterExpression param2 = expr.Parameters[1];
Expression operand1 = null;
Expression operand2 = null;
BinaryExpression body = expr.Body as BinaryExpression;
if (body == null)
{
MethodCallExpression mcExpr = expr.Body as MethodCallExpression;
if (mcExpr != null && mcExpr.Method.DeclaringType == typeof(System.Math))
{
if (mcExpr.Method.Name == "Max" || mcExpr.Method.Name == "Min")
{
operand1 = mcExpr.Arguments[0];
operand2 = mcExpr.Arguments[1];
}
}
}
else if (body.NodeType == ExpressionType.Add ||
body.NodeType == ExpressionType.AddChecked ||
body.NodeType == ExpressionType.Multiply ||
body.NodeType == ExpressionType.MultiplyChecked ||
body.NodeType == ExpressionType.And ||
body.NodeType == ExpressionType.Or ||
body.NodeType == ExpressionType.ExclusiveOr)
{
if (body.Method == null)
{
operand1 = body.Left;
operand2 = body.Right;
}
}
if (operand1 != null)
{
if (operand1 == param1)
{
return !Contains(param1, operand2);
}
if (operand2 == param1)
{
return !Contains(param1, operand1);
}
}
return false;
}
internal static ExpressionType GetNodeType(string opName)
{
switch (opName)
{
case "op_Addition":
return ExpressionType.Add;
case "op_Subtraction":
return ExpressionType.Subtract;
case "op_Multiply":
return ExpressionType.Multiply;
case "op_Division":
return ExpressionType.Divide;
case "op_Modulus":
return ExpressionType.Modulo;
case "op_BitwiseAnd":
return ExpressionType.And;
case "op_BitwiseOr":
return ExpressionType.Or;
case "op_ExclusiveOr":
return ExpressionType.ExclusiveOr;
case "op_LeftShift":
return ExpressionType.LeftShift;
case "op_RightShift":
return ExpressionType.RightShift;
case "op_Equality":
return ExpressionType.Equal;
case "op_Inequality":
return ExpressionType.NotEqual;
case "op_LessThan":
return ExpressionType.LessThan;
case "op_GreaterThan":
return ExpressionType.GreaterThan;
case "op_LessThanOrEqual":
return ExpressionType.LessThanOrEqual;
case "op_GreaterThanOrEqual":
return ExpressionType.GreaterThanOrEqual;
case "op_UnaryPlus":
return ExpressionType.UnaryPlus;
case "op_UnaryNegation":
return ExpressionType.Negate;
case "op_LogicalNot":
return ExpressionType.Not;
default:
throw new DryadLinqException(DryadLinqErrorCode.UnrecognizedOperatorName,
String.Format(SR.UnrecognizedOperatorName , opName));
}
}
internal static LambdaExpression GetAssociativeCombiner(LambdaExpression expr)
{
AssociativeAttribute attrib = AttributeSystem.GetAssociativeAttrib(expr);
if (attrib == null)
{
BinaryExpression bexpr = expr.Body as BinaryExpression;
if (bexpr == null)
{
MethodCallExpression mcExpr = expr.Body as MethodCallExpression;
ParameterExpression px = Expression.Parameter(mcExpr.Arguments[0].Type, "x");
ParameterExpression py = Expression.Parameter(mcExpr.Arguments[1].Type, "y");
Expression body = Expression.Call(mcExpr.Method, px, py);
return Expression.Lambda(body, px, py);
}
else
{
ParameterExpression px = Expression.Parameter(bexpr.Left.Type, "x");
ParameterExpression py = Expression.Parameter(bexpr.Right.Type, "y");
Expression body = Expression.MakeBinary(bexpr.NodeType, px, py, bexpr.IsLiftedToNull, bexpr.Method);
return Expression.Lambda(body, px, py);
}
}
else
{
Type[] funcTypeArgs = expr.Type.GetGenericArguments();
MethodInfo cInfo = null;
Type associativeType = attrib.AssociativeType;
if (associativeType == null)
{
if (expr.Body is MethodCallExpression)
{
cInfo = ((MethodCallExpression)expr.Body).Method;
}
else if (expr.Body is BinaryExpression)
{
cInfo = ((BinaryExpression)expr.Body).Method;
}
ParameterInfo[] pInfos = cInfo.GetParameters();
if (cInfo == null || pInfos.Length != 2)
{
throw new DryadLinqException(DryadLinqErrorCode.AssociativeMethodHasWrongForm,
string.Format(SR.AssociativeMethodHasWrongForm, cInfo.Name));
}
if (funcTypeArgs[0] != pInfos[0].ParameterType || pInfos[0].ParameterType != pInfos[1].ParameterType)
{
throw new DryadLinqException(DryadLinqErrorCode.AssociativeMethodHasWrongForm,
string.Format(SR.AssociativeMethodHasWrongForm, cInfo.Name));
}
}
else
{
// determine if the attribute specifies an IAssociative.
if (associativeType.ContainsGenericParameters)
{
if (associativeType.GetGenericArguments().Length != 1)
{
throw new DryadLinqException(DryadLinqErrorCode.AssociativeTypeDoesNotImplementInterface,
String.Format(SR.AssociativeTypeDoesNotImplementInterface,
associativeType.FullName));
}
if (associativeType.GetGenericArguments()[0].IsGenericParameter)
{
associativeType = associativeType.MakeGenericType(funcTypeArgs[0]);
}
}
Type implementedInterface = null;
Type[] interfaces = associativeType.GetInterfaces();
foreach (Type inter in interfaces)
{
if (inter.GetGenericTypeDefinition() == typeof(IAssociative<>))
{
if (implementedInterface != null)
{
throw new DryadLinqException(DryadLinqErrorCode.AssociativeTypeImplementsTooManyInterfaces,
String.Format(SR.AssociativeTypeImplementsTooManyInterfaces,
associativeType.FullName));
}
implementedInterface = inter;
}
}
if (implementedInterface == null)
{
throw new DryadLinqException(DryadLinqErrorCode.AssociativeTypeDoesNotImplementInterface,
String.Format(SR.AssociativeTypeDoesNotImplementInterface,
associativeType.FullName));
}
if (implementedInterface.GetGenericArguments()[0] != funcTypeArgs[0])
{
throw new DryadLinqException(DryadLinqErrorCode.AssociativeTypesDoNotMatch,
String.Format(SR.AssociativeTypesDoNotMatch,
associativeType.FullName));
}
if (!associativeType.IsPublic && !associativeType.IsNestedPublic)
{
throw new DryadLinqException(DryadLinqErrorCode.AssociativeTypeMustBePublic,
String.Format(SR.AssociativeTypeMustBePublic,
associativeType.FullName));
}
try
{
associativeType = typeof(GenericAssociative<,>).MakeGenericType(associativeType, funcTypeArgs[0]);
}
catch (Exception)
{
throw new DryadLinqException(DryadLinqErrorCode.AssociativeTypeDoesNotHavePublicDefaultCtor,
String.Format(SR.AssociativeTypeDoesNotHavePublicDefaultCtor,
associativeType.FullName));
}
cInfo = associativeType.GetMethod("Accumulate", new Type[] { funcTypeArgs[0], funcTypeArgs[0] });
Debug.Assert(cInfo != null, "problem finding method on associativeType");
}
ParameterExpression px = Expression.Parameter(funcTypeArgs[0], "x");
ParameterExpression py = Expression.Parameter(funcTypeArgs[0], "y");
Expression body;
if (cInfo.Name.StartsWith("op_", StringComparison.Ordinal))
{
body = Expression.MakeBinary(GetNodeType(cInfo.Name), px, py, false, cInfo);
}
else
{
body = Expression.Call(cInfo, px, py);
}
return Expression.Lambda(body, px, py);
}
}
public static LambdaExpression Rewrite(LambdaExpression expr, LambdaExpression selector, Substitution pSubst)
{
if (expr != null)
{
Type resultType = selector.Body.Type;
ParameterExpression resultParam = Expression.Parameter(resultType, "key_1");
// Perform substitutions
ExpressionSubst subst = new ExpressionSubst(pSubst);
subst.AddSubst(selector.Body, resultParam);
if (selector.Body is NewExpression)
{
NewExpression newBody = (NewExpression)selector.Body;
if (newBody.Constructor != null)
{
resultType = newBody.Constructor.DeclaringType;
}
if (TypeSystem.IsAnonymousType(resultType))
{
PropertyInfo[] props = resultType.GetProperties();
//the following test is never expected to occur, and an assert would most likely suffice.
if (props.Length != newBody.Arguments.Count)
{
throw new DryadLinqException(DryadLinqErrorCode.Internal, SR.BugInHandlingAnonymousClass);
}
for (int i = 0; i < props.Length; i++)
{
Expression leftExpr = newBody.Arguments[i];
Expression rightExpr = CreateMemberAccess(resultParam, props[i].Name);
subst.AddSubst(leftExpr, rightExpr);
}
}
}
if (selector.Body is MemberInitExpression)
{
ReadOnlyCollection<MemberBinding> bindings = ((MemberInitExpression)selector.Body).Bindings;
for (int i = 0; i < bindings.Count; i++)
{
if (bindings[i] is MemberAssignment)
{
Expression leftExpr = ((MemberAssignment)bindings[i]).Expression;
Expression rightExpr = CreateMemberAccess(resultParam, ((MemberAssignment)bindings[i]).Member.Name);
subst.AddSubst(leftExpr, rightExpr);
}
}
}
else
{
FieldMappingAttribute[] attribs = AttributeSystem.GetFieldMappingAttribs(selector);
if (attribs != null)
{
foreach (FieldMappingAttribute attrib in attribs)
{
string[] srcFieldNames = attrib.Source.Split('.');
string paramName = srcFieldNames[0];
ParameterInfo[] paramInfos = null;
if (selector.Body is MethodCallExpression)
{
paramInfos = ((MethodCallExpression)selector.Body).Method.GetParameters();
}
else if (selector.Body is NewExpression)
{
paramInfos = ((NewExpression)selector.Body).Constructor.GetParameters();
}
if (paramInfos != null)
{
int argIdx = -1;
for (int i = 0; i < paramInfos.Length; i++)
{
if (paramInfos[i].Name == paramName)
{
argIdx = i;
break;
}
}
Expression leftExpr = null;
if (argIdx != -1)
{
if (selector.Body is MethodCallExpression)
{
leftExpr = ((MethodCallExpression)selector.Body).Arguments[argIdx];
}
else if (selector.Body is NewExpression)
{
leftExpr = ((NewExpression)selector.Body).Arguments[argIdx];
}
}
if (leftExpr == null)
{
throw new DryadLinqException(DryadLinqErrorCode.Internal,
"The source of the FieldMapping annotation was wrong. " +
paramName + " is not a formal parameter.");
}
string[] fieldNames = new string[srcFieldNames.Length - 1];
for (int i = 1; i < srcFieldNames.Length; i++)
{
fieldNames[i] = srcFieldNames[i-1];
}
leftExpr = CreateMemberAccess(leftExpr, fieldNames);
Expression rightExpr = CreateMemberAccess(resultParam, attrib.Destination.Split('.'));
subst.AddSubst(leftExpr, rightExpr);
}
}
}
}
Expression resultBody = subst.Visit(expr.Body);
// Check if the substitutions are complete
FreeParameters freeParams = new FreeParameters();
freeParams.Visit(resultBody);
if (freeParams.Parameters.Count == 1 && freeParams.Parameters.Contains(resultParam))
{
Type funcType = typeof(Func<,>).MakeGenericType(resultType, expr.Body.Type);
return Expression.Lambda(funcType, resultBody, resultParam);
}
}
return null;
}
public static string EscapeString(char ch)
{
switch (ch)
{
case '\'':
case '\"':
case '\\':
return "\\" + ch;
case '\0':
return "\\0";
case '\a':
return "\\a";
case '\b':
return "\\b";
case '\f':
return "\\f";
case '\n':
return "\\n";
case '\r':
return "\\r";
case '\t':
return "\\t";
case '\v':
return "\\v";
default:
return null;
}
}
private static Dictionary<string, string> s_transIdMap = new Dictionary<string, string>();
public static string ToCSharpString(Expression expr)
{
return ToCSharpString(expr, new Dictionary<Type, string>());
}
public static string ToCSharpString(Expression expr, Dictionary<Type, string> typeNames)
{
StringBuilder builder = new StringBuilder();
BuildExpression(builder, expr, typeNames);
return builder.ToString();
}
private static void BuildExpression(StringBuilder builder,
Expression expr,
Dictionary<Type, string> typeNames)
{
if (IsConstant(expr))
{
object val = ExpressionSimplifier.Evaluate(expr);
if (val == null)
{
builder.Append("(" + TypeSystem.TypeName(expr.Type, typeNames) + ")");
builder.Append("null");
}
else
{
Type valType = val.GetType();
if (valType.IsPrimitive)
{
TypeCode tcode = Type.GetTypeCode(expr.Type);
if (tcode == TypeCode.Boolean)
{
builder.Append(((bool)val) ? "true" : "false");
}
else if (tcode == TypeCode.Char)
{
string escapeStr = EscapeString((char)val);
if (escapeStr == null)
{
builder.Append("'" + val + "'");
}
else
{
builder.Append("'" + escapeStr + "'");
}
}
else
{
builder.Append("((" + TypeSystem.TypeName(valType, typeNames) + ")(");
builder.Append(val + "))");
}
}
else if (valType.IsEnum)
{
builder.Append(TypeSystem.TypeName(valType, typeNames) + "." + val);
}
else if (val is string)
{
builder.Append("@\"");
builder.Append(((string)val).Replace("\"", "\"\""));
builder.Append("\"");
}
else if (val is Expression)
{
BuildExpression(builder, (Expression)val, typeNames);
}
else
{
int valIdx = DryadLinqObjectStore.Put(val);
builder.Append("((" + TypeSystem.TypeName(expr.Type, typeNames) + ")");
builder.Append("DryadLinqObjectStore.Get(" + valIdx + "))");
}
}
}
else if (expr is BinaryExpression)
{
BuildBinaryExpression(builder, (BinaryExpression)expr, typeNames);
}
else if (expr is ConditionalExpression)
{
BuildConditionalExpression(builder, (ConditionalExpression)expr, typeNames);
}
else if (expr is ConstantExpression)
{
BuildConstantExpression(builder, (ConstantExpression)expr, typeNames);
}
else if (expr is InvocationExpression)
{
BuildInvocationExpression(builder, (InvocationExpression)expr, typeNames);
}
else if (expr is LambdaExpression)
{
BuildLambdaExpression(builder, (LambdaExpression)expr, typeNames);
}
else if (expr is MemberExpression)
{
BuildMemberExpression(builder, (MemberExpression)expr, typeNames);
}
else if (expr is MethodCallExpression)
{
BuildMethodCallExpression(builder, (MethodCallExpression)expr, typeNames);
}
else if (expr is NewExpression)
{
BuildNewExpression(builder, (NewExpression)expr, typeNames);
}
else if (expr is NewArrayExpression)
{
BuildNewArrayExpression(builder, (NewArrayExpression)expr, typeNames);
}
else if (expr is MemberInitExpression)
{
BuildMemberInitExpression(builder, (MemberInitExpression)expr, typeNames);
}
else if (expr is ListInitExpression)
{
BuildListInitExpression(builder, (ListInitExpression)expr, typeNames);
}
else if (expr is ParameterExpression)
{
BuildParameterExpression(builder, (ParameterExpression)expr, typeNames);
}
else if (expr is TypeBinaryExpression)
{
BuildTypeBinaryExpression(builder, (TypeBinaryExpression)expr, typeNames);
}
else if (expr is UnaryExpression)
{
BuildUnaryExpression(builder, (UnaryExpression)expr, typeNames);
}
else
{
throw new DryadLinqException(DryadLinqErrorCode.UnsupportedExpressionsType,
String.Format(SR.UnsupportedExpressionsType, expr.NodeType));
}
}
private static void BuildInvocationExpression(StringBuilder builder,
InvocationExpression expr,
Dictionary<Type, string> typeNames)
{
builder.Append("(");
builder.Append("(");
// type cast to method
builder.Append("(");
builder.Append(TypeSystem.TypeName(expr.Expression.Type, typeNames));
builder.Append(")");
// method name
builder.Append("(");
BuildExpression(builder, expr.Expression, typeNames);
builder.Append(")");
builder.Append(")");
// method invocation
builder.Append("(");
bool isFirst = true;
foreach (Expression arg in expr.Arguments)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.Append(", ");
}
BuildExpression(builder, arg, typeNames);
}
builder.Append(")");
builder.Append(")");
}
private static void BuildBinaryExpression(StringBuilder builder,
BinaryExpression expr,
Dictionary<Type, string> typeNames)
{
if (expr.NodeType == ExpressionType.ArrayIndex)
{
BuildExpression(builder, expr.Left, typeNames);
builder.Append("[");
BuildExpression(builder, expr.Right, typeNames);
builder.Append("]");
}
else
{
string op = GetBinaryOperator(expr);
if (op != null)
{
bool isChecked = (expr.NodeType == ExpressionType.AddChecked ||
expr.NodeType == ExpressionType.SubtractChecked ||
expr.NodeType == ExpressionType.MultiplyChecked);
if (isChecked) builder.Append("checked(");
builder.Append("(");
BuildExpression(builder, expr.Left, typeNames);
builder.Append(" ");
builder.Append(op);
builder.Append(" ");
BuildExpression(builder, expr.Right, typeNames);
builder.Append(")");
if (isChecked) builder.Append(")");
}
else {
builder.Append(expr.NodeType);
builder.Append("(");
BuildExpression(builder, expr.Left, typeNames);
builder.Append(", ");
BuildExpression(builder, expr.Right, typeNames);
builder.Append(")");
}
}
}
internal static string GetBinaryOperator(BinaryExpression expr)
{
switch (expr.NodeType)
{
case ExpressionType.Add:
case ExpressionType.AddChecked:
return "+";
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return "-";
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return "*";
case ExpressionType.Divide:
return "/";
case ExpressionType.Modulo:
return "%";
case ExpressionType.And:
return (expr.Type == typeof(bool) || expr.Type == typeof(bool?)) ? "&&" : "&";
case ExpressionType.AndAlso:
return "&&";
case ExpressionType.Or:
return (expr.Type == typeof(bool) || expr.Type == typeof(bool?)) ? "||" : "|";
case ExpressionType.OrElse:
return "||";
case ExpressionType.LessThan:
return "<";
case ExpressionType.LessThanOrEqual:
return "<=";
case ExpressionType.GreaterThan:
return ">";
case ExpressionType.GreaterThanOrEqual:
return ">=";
case ExpressionType.Equal:
return "==";
case ExpressionType.NotEqual:
return "!=";
case ExpressionType.Coalesce:
return "??";
case ExpressionType.RightShift:
return ">>";
case ExpressionType.LeftShift:
return "<<";
case ExpressionType.ExclusiveOr:
case ExpressionType.Power:
return "^";
}
return null;
}
private static void BuildConditionalExpression(StringBuilder builder,
ConditionalExpression expr,
Dictionary<Type, string> typeNames)
{
builder.Append("(");
builder.Append("(");
BuildExpression(builder, expr.Test, typeNames);
builder.Append(") ? (");
BuildExpression(builder, expr.IfTrue, typeNames);
builder.Append(") : (");
BuildExpression(builder, expr.IfFalse, typeNames);
builder.Append(")");
builder.Append(")");
}
private static void BuildConstantExpression(StringBuilder builder,
ConstantExpression expr,
Dictionary<Type, string> typeNames)
{
if (expr.Value == null)
{
builder.Append("null");
}
else
{
if (expr.Value is string)
{
builder.Append("@\"");
builder.Append(expr.Value);
builder.Append("\"");
}
else if (expr.Value.ToString() == expr.Value.GetType().ToString())
{
builder.Append("value(");
builder.Append(expr.Value);
builder.Append(")");
}
else
{
builder.Append(expr.Value);
}
}
}
private static void BuildLambdaExpression(StringBuilder builder,
LambdaExpression expr,
Dictionary<Type, string> typeNames)
{
foreach (ParameterExpression param in expr.Parameters)
{
if (TypeSystem.IsTransparentIdentifier(param.Name))
{
string newName = DryadLinqCodeGen.MakeUniqueName("h__TransparentIdentifier");
s_transIdMap[param.Name] = newName;
}
}
if (expr.Parameters.Count == 1)
{
BuildExpression(builder, expr.Parameters[0], typeNames);
}
else
{
builder.Append("(");
for (int i = 0, n = expr.Parameters.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
BuildExpression(builder, expr.Parameters[i], typeNames);
}
builder.Append(")");
}
builder.Append(" => ");
BuildExpression(builder, expr.Body, typeNames);
}
private static void BuildMemberExpression(StringBuilder builder,
MemberExpression expr,
Dictionary<Type, string> typeNames)
{
if (expr.Expression == null)
{
builder.Append(TypeSystem.TypeName(expr.Member.DeclaringType, typeNames));
}
else
{
ParameterExpression param = expr.Expression as ParameterExpression;
if (param != null)
{
BuildExpression(builder, param, typeNames);
}
else
{
BuildExpression(builder, expr.Expression, typeNames);
}
}
builder.Append(".");
string memberName = expr.Member.Name;
if (TypeSystem.IsTransparentIdentifier(memberName))
{
if (s_transIdMap.ContainsKey(memberName))
{
memberName = s_transIdMap[memberName];
}
else
{
string newName = DryadLinqCodeGen.MakeUniqueName("h__TransparentIdentifier");
s_transIdMap[memberName] = newName;
memberName = newName;
}
}
builder.Append(memberName);
}
private static void BuildMethodCallExpression(StringBuilder builder,
MethodCallExpression expr,
Dictionary<Type, string> typeNames)
{
Expression obj = expr.Object;
int start = 0;
if (Attribute.GetCustomAttribute(expr.Method, typeof(System.Runtime.CompilerServices.ExtensionAttribute)) != null)
{
start = 1;
obj = expr.Arguments[0];
}
bool desugar = expr.Method.IsStatic && !TypeSystem.IsQueryOperatorCall(expr);
if (obj == null || desugar)
{
Type type = expr.Method.DeclaringType;
builder.Append(TypeSystem.TypeName(type, typeNames));
}
else
{
BuildExpression(builder, obj, typeNames);
}
if (TypeSystem.IsProperty(expr.Method))
{
// Special case: an indexer property
builder.Append("[");
for (int i = start, n = expr.Arguments.Count; i < n; i++)
{
if (i > start) builder.Append(", ");
BuildExpression(builder, expr.Arguments[i], typeNames);
}
builder.Append("]");
}
else
{
bool isArrayIndexer = (expr.Method.DeclaringType.IsArray && expr.Method.Name == "Get");
if (isArrayIndexer)
{
builder.Append("[");
}
else
{
builder.Append(".");
builder.Append(expr.Method.Name);
if (expr.Method.IsGenericMethod &&
!TypeSystem.ContainsAnonymousType(expr.Method.GetGenericArguments()))
{
builder.Append("<");
bool first = true;
foreach (Type t in expr.Method.GetGenericArguments())
{
if (first)
{
first = false;
}
else
{
builder.Append(",");
}
builder.Append(TypeSystem.TypeName(t, typeNames));
}
builder.Append(">");
}
builder.Append("(");
}
bool isFirst = true;
if (obj != null && desugar)
{
isFirst = false;
BuildExpression(builder, obj, typeNames);
}
for (int i = start, n = expr.Arguments.Count; i < n; i++)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.Append(", ");
}
BuildExpression(builder, expr.Arguments[i], typeNames);
}
builder.Append((isArrayIndexer) ? "]" : ")");
}
}
private static void BuildNewExpression(StringBuilder builder,
NewExpression expr,
Dictionary<Type, string> typeNames)
{
Type type = (expr.Constructor == null) ? expr.Type : expr.Constructor.DeclaringType;
builder.Append("new ");
string typeName = null;
if (TypeSystem.IsAnonymousType(type))
{
if (!typeNames.TryGetValue(type, out typeName))
{
PropertyInfo[] props = type.GetProperties();
System.Array.Sort(props, (x, y) => x.MetadataToken.CompareTo(y.MetadataToken));
builder.Append("{");
for (int i = 0; i < props.Length; i++)
{
if (i > 0) builder.Append(", ");
string propName = props[i].Name;
if (TypeSystem.IsTransparentIdentifier(propName))
{
if (s_transIdMap.ContainsKey(propName))
{
propName = s_transIdMap[propName];
}
else
{
string newName = DryadLinqCodeGen.MakeUniqueName("h__TransparentIdentifier");
s_transIdMap.Add(propName, newName);
propName = newName;
}
}
builder.Append(propName + " = ");
BuildExpression(builder, expr.Arguments[i], typeNames);
}
builder.Append("}");
return;
}
}
else
{
typeName = TypeSystem.TypeName(type, typeNames);
}
builder.Append(typeName);
builder.Append("(");
for (int i = 0; i < expr.Arguments.Count; i++)
{
if (i > 0) builder.Append(", ");
BuildExpression(builder, expr.Arguments[i], typeNames);
}
builder.Append(")");
}
private static void BuildNewArrayExpression(StringBuilder builder,
NewArrayExpression expr,
Dictionary<Type, string> typeNames)
{
builder.Append("new ");
if (expr.NodeType == ExpressionType.NewArrayBounds)
{
Type baseType = expr.Type.GetElementType();
while (baseType.IsArray)
{
baseType = baseType.GetElementType();
}
builder.Append(TypeSystem.TypeName(baseType, typeNames));
builder.Append("[");
for (int i = 0, n = expr.Expressions.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
BuildExpression(builder, expr.Expressions[i], typeNames);
}
builder.Append("]");
Type elemType = expr.Type.GetElementType();
while (elemType.IsArray)
{
builder.Append("[");
int rank = elemType.GetArrayRank();
for (int i = 1; i < rank; i++)
{
builder.Append(',');
}
builder.Append("]");
elemType = elemType.GetElementType();
}
}
else
{
Debug.Assert(expr.NodeType == ExpressionType.NewArrayInit);
builder.Append(TypeSystem.TypeName(expr.Type, typeNames));
builder.Append(" {");
for (int i = 0, n = expr.Expressions.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
BuildExpression(builder, expr.Expressions[i], typeNames);
}
builder.Append("}");
}
}
private static void BuildMemberInitExpression(StringBuilder builder,
MemberInitExpression expr,
Dictionary<Type, string> typeNames)
{
if (expr.NewExpression.Arguments.Count == 0 &&
expr.NewExpression.Type.Name.Contains("<"))
{
// anonymous type constructor
builder.Append("new");
}
else
{
BuildExpression(builder, expr.NewExpression, typeNames);
}
builder.Append(" {");
for (int i = 0, n = expr.Bindings.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
BuildMemberBinding(builder, expr.Bindings[i], typeNames);
}
builder.Append("}");
}
private static void BuildListInitExpression(StringBuilder builder,
ListInitExpression expr,
Dictionary<Type, string> typeNames)
{
BuildExpression(builder, expr.NewExpression, typeNames);
builder.Append(" {");
for (int i = 0, n = expr.Initializers.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
BuildElementInit(builder, expr.Initializers[i], typeNames);
}
builder.Append("}");
}
private static void BuildParameterExpression(StringBuilder builder,
ParameterExpression expr,
Dictionary<Type, string> typeNames)
{
if (expr.Name == null)
{
throw new DryadLinqException(DryadLinqErrorCode.Internal, SR.UnnamedParameterExpression);
}
string paramName = expr.Name;
if (s_transIdMap.ContainsKey(paramName))
{
paramName = s_transIdMap[paramName];
}
builder.Append(paramName);
}
private static void BuildTypeBinaryExpression(StringBuilder builder,
TypeBinaryExpression expr,
Dictionary<Type, string> typeNames)
{
Debug.Assert(expr.NodeType == ExpressionType.TypeIs);
builder.Append("(");
BuildExpression(builder, expr.Expression, typeNames);
builder.Append(" is ");
builder.Append(TypeSystem.TypeName(expr.TypeOperand, typeNames));
builder.Append(")");
}
private static void BuildUnaryExpression(StringBuilder builder,
UnaryExpression expr,
Dictionary<Type, string> typeNames)
{
switch (expr.NodeType)
{
case ExpressionType.ArrayLength:
{
BuildExpression(builder, expr.Operand, typeNames);
builder.Append(".Length");
break;
}
case ExpressionType.Convert:
{
bool isChecked = (expr.NodeType == ExpressionType.ConvertChecked);
if (isChecked) builder.Append("checked(");
builder.Append("((");
builder.Append(TypeSystem.TypeName(expr.Type, typeNames));
builder.Append(")");
BuildExpression(builder, expr.Operand, typeNames);
builder.Append(")");
if (isChecked) builder.Append(")");
break;
}
case ExpressionType.TypeAs:
{
builder.Append("(");
BuildExpression(builder, expr.Operand, typeNames);
builder.Append(" as ");
builder.Append(TypeSystem.TypeName(expr.Type, typeNames));
builder.Append(")");
break;
}
case ExpressionType.Not:
{
//bug 15050.. Not is represented in C# two ways, depending on operand type.
// see http://msdn.microsoft.com/en-us/library/bb361179.aspx
if (expr.Operand.Type == typeof(bool) || expr.Operand.Type == typeof(bool?))
{
builder.Append("(!(");
BuildExpression(builder, expr.Operand, typeNames);
builder.Append("))");
}
else
{
builder.Append("(~(");
BuildExpression(builder, expr.Operand, typeNames);
builder.Append("))");
}
break;
}
case ExpressionType.Negate:
{
builder.Append("(-(");
BuildExpression(builder, expr.Operand, typeNames);
builder.Append("))");
break;
}
case ExpressionType.NegateChecked:
{
builder.Append("checked(-(");
BuildExpression(builder, expr.Operand, typeNames);
builder.Append("))");
break;
}
case ExpressionType.Quote:
{
BuildExpression(builder, expr.Operand, typeNames);
break;
}
default:
{
builder.Append(expr.NodeType);
builder.Append("(");
BuildExpression(builder, expr.Operand, typeNames);
builder.Append(")");
break;
}
}
}
private static void BuildMemberBinding(StringBuilder builder,
MemberBinding binding,
Dictionary<Type, string> typeNames)
{
if (binding is MemberAssignment)
{
builder.Append(binding.Member.Name);
builder.Append(" = ");
BuildExpression(builder, ((MemberAssignment)binding).Expression, typeNames);
}
else if (binding is MemberMemberBinding)
{
builder.Append(binding.Member.Name);
builder.Append(" = {");
MemberMemberBinding mmBinding = (MemberMemberBinding)binding;
for (int i = 0, n = mmBinding.Bindings.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
BuildMemberBinding(builder, mmBinding.Bindings[i], typeNames);
}
builder.Append("}");
}
else
{
Debug.Assert(binding is MemberListBinding);
builder.Append(binding.Member.Name);
builder.Append(" = {");
MemberListBinding mlBinding = (MemberListBinding)binding;
for (int i = 0, n = mlBinding.Initializers.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
BuildElementInit(builder, mlBinding.Initializers[i], typeNames);
}
builder.Append("}");
}
}
private static void BuildElementInit(StringBuilder builder,
ElementInit elemInit,
Dictionary<Type, string> typeNames)
{
// An ElementInitExpression is something like: "Add(arg1, arg2..)"
// which corresponds to C# syntax such as:
// 1. new Dictionary<T> { {arg1, arg2} };
// AND/OR
// 2. Dictionary<T> x = new Dictionary<T>(); x.Add(arg1,arg2);
//
// The caller of BuildElementInit looks after the multiple *items* added to a collection, but this method must cope with
// Add() methods that take one or more arguments.
//
// The main example for multi-argument Add() methods is Dictionary.Add(key,val), but user-defined classes
// can also participate. C# uses duck-typing for this and similar language extensions.
// Bug 15049: when emitting inline (syntax #1) don't emit elemInit.AddMethod, but do emit braces to demarcate the parameters
builder.Append("{");
bool isFirst = true;
foreach (Expression argument in elemInit.Arguments)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.Append(",");
}
BuildExpression(builder, argument, typeNames);
}
builder.Append("}");
}
#endregion
#region SUMMARIZE
// summarizing expressions: like ToString, but more compact
public static string Summarize(Expression expr)
{
return Summarize(expr, 0);
}
public static string Summarize(Expression expr, int level)
{
StringBuilder builder = new StringBuilder();
Summarize(builder, expr, level);
return builder.ToString();
}
private static void Summarize(StringBuilder builder, Expression expr, int level)
{
if (IsConstant(expr))
{
object val = ExpressionSimplifier.Evaluate(expr);
if (val == null)
{
builder.Append("null");
}
else
{
Type valType = val.GetType();
if (valType.IsPrimitive)
{
TypeCode tcode = Type.GetTypeCode(expr.Type);
if (tcode == TypeCode.Char)
{
string escapeStr = EscapeString((char)val);
if (escapeStr == null)
{
builder.Append("'" + val + "'");
}
else
{
builder.Append("'" + escapeStr + "'");
}
}
else
{
builder.Append(val.ToString());
}
}
else if (val is Expression)
{
Summarize(builder, (Expression)val, level);
}
else if (val is Delegate)
{
builder.Append(((Delegate)val).Method.Name);
}
else
{
builder.Append('_');
}
}
}
else if (expr is BinaryExpression)
{
SummarizeBinaryExpression(builder, (BinaryExpression)expr, level);
}
else if (expr is ConditionalExpression)
{
SummarizeConditionalExpression(builder, (ConditionalExpression)expr, level);
}
else if (expr is ConstantExpression)
{
SummarizeConstantExpression(builder, (ConstantExpression)expr);
}
else if (expr is InvocationExpression)
{
SummarizeInvocationExpression(builder, (InvocationExpression)expr, level);
}
else if (expr is LambdaExpression)
{
SummarizeLambdaExpression(builder, (LambdaExpression)expr, level);
}
else if (expr is MemberExpression)
{
SummarizeMemberExpression(builder, (MemberExpression)expr, level);
}
else if (expr is MethodCallExpression)
{
SummarizeMethodCallExpression(builder, (MethodCallExpression)expr, level);
}
else if (expr is NewExpression)
{
SummarizeNewExpression(builder, (NewExpression)expr, level);
}
else if (expr is NewArrayExpression)
{
SummarizeNewArrayExpression(builder, (NewArrayExpression)expr, level);
}
else if (expr is MemberInitExpression)
{
SummarizeMemberInitExpression(builder, (MemberInitExpression)expr, level);
}
else if (expr is ListInitExpression)
{
SummarizeListInitExpression(builder, (ListInitExpression)expr, level);
}
else if (expr is ParameterExpression)
{
SummarizeParameterExpression(builder, (ParameterExpression)expr);
}
else if (expr is TypeBinaryExpression)
{
SummarizeTypeBinaryExpression(builder, (TypeBinaryExpression)expr, level);
}
else if (expr is UnaryExpression)
{
SummarizeUnaryExpression(builder, (UnaryExpression)expr, level);
}
else
{
throw new DryadLinqException(DryadLinqErrorCode.UnsupportedExpressionType,
String.Format(SR.UnsupportedExpressionType, expr.NodeType));
}
}
private static void SummarizeInvocationExpression(StringBuilder builder, InvocationExpression expr, int level)
{
bool isConstant = expr.Expression is ConstantExpression;
if (!isConstant)
builder.Append("(");
Summarize(builder, expr.Expression, level);
if (!isConstant)
builder.Append(")");
// method invocation
builder.Append("(");
bool isFirst = true;
foreach (Expression arg in expr.Arguments)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.Append(", ");
}
Summarize(builder, arg, level);
}
builder.Append(")");
}
private static void SummarizeBinaryExpression(StringBuilder builder, BinaryExpression expr, int level)
{
if (expr.NodeType == ExpressionType.ArrayIndex)
{
Summarize(builder, expr.Left, level);
builder.Append("[");
Summarize(builder, expr.Right, level);
builder.Append("]");
}
else
{
string op = GetBinaryOperator(expr);
if (op != null)
{
builder.Append("(");
Summarize(builder, expr.Left, level);
builder.Append(" ");
builder.Append(op);
builder.Append(" ");
Summarize(builder, expr.Right, level);
builder.Append(")");
}
else
{
builder.Append(expr.NodeType);
builder.Append("(");
Summarize(builder, expr.Left, level);
builder.Append(", ");
Summarize(builder, expr.Right, level);
builder.Append(")");
}
}
}
private static void SummarizeConditionalExpression(StringBuilder builder, ConditionalExpression expr, int level)
{
builder.Append("(");
Summarize(builder, expr.Test, level);
builder.Append(") ? (");
Summarize(builder, expr.IfTrue, level);
builder.Append(") : (");
Summarize(builder, expr.IfFalse, level);
builder.Append(")");
}
private static void SummarizeConstantExpression(StringBuilder builder, ConstantExpression expr)
{
builder.Append('_');
}
private static void SummarizeLambdaExpression(StringBuilder builder, LambdaExpression expr, int level)
{
if (expr.Parameters.Count == 1)
{
Summarize(builder, expr.Parameters[0], level);
}
else
{
builder.Append("(");
for (int i = 0, n = expr.Parameters.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
Summarize(builder, expr.Parameters[i], level);
}
builder.Append(")");
}
builder.Append(" => ");
Summarize(builder, expr.Body, level);
}
private static void SummarizeMemberExpression(StringBuilder builder, MemberExpression expr, int level)
{
if (expr.Expression == null)
{
builder.Append(TypeSystem.TypeName(expr.Member.DeclaringType));
}
else
{
Summarize(builder, expr.Expression, level);
}
builder.Append(".");
builder.Append(expr.Member.Name);
}
private static void SummarizeMethodCallExpression(StringBuilder builder, MethodCallExpression expr, int level)
{
Expression obj = expr.Object;
int start = 0;
if (Attribute.GetCustomAttribute(expr.Method, typeof(System.Runtime.CompilerServices.ExtensionAttribute)) != null)
{
start = 1;
obj = expr.Arguments[0];
}
if (obj == null)
{
Type type = expr.Method.DeclaringType;
builder.Append(DryadLinqUtil.SimpleName(TypeSystem.TypeName(type)));
}
else if (level > 0)
{
builder.Append('_');
}
else
{
Summarize(builder, obj, level);
}
if (TypeSystem.IsProperty(expr.Method))
{
// Special case: an indexer property
builder.Append("[");
for (int i = start, n = expr.Arguments.Count; i < n; i++)
{
if (i > start) builder.Append(", ");
Summarize(builder, expr.Arguments[i], level);
}
builder.Append("]");
}
else
{
builder.Append(".");
builder.Append(DryadLinqUtil.SimpleName(expr.Method.Name));
builder.Append("(");
for (int i = start, n = expr.Arguments.Count; i < n; i++)
{
if (i > start) builder.Append(", ");
Summarize(builder, expr.Arguments[i], level);
}
builder.Append(")");
}
}
private static string SummarizeType(string typename)
{
// drop common 'System.*' prefixes
string result = Regex.Replace(typename, @"System[a-zA-Z\.]*\.([a-zA-Z]+)", "$1");
return result;
}
private static void SummarizeNewExpression(StringBuilder builder, NewExpression expr, int level)
{
Type type = (expr.Constructor == null) ? expr.Type : expr.Constructor.DeclaringType;
builder.Append("new ");
builder.Append(SummarizeType(TypeSystem.TypeName(type)));
int n = expr.Arguments.Count;
builder.Append("(");
for (int i = 0; i < n; i++)
{
if (i > 0) builder.Append(", ");
Summarize(builder, expr.Arguments[i], level);
}
builder.Append(")");
}
private static void SummarizeNewArrayExpression(StringBuilder builder, NewArrayExpression expr, int level)
{
if (expr.NodeType == ExpressionType.NewArrayBounds)
{
builder.Append("new ");
builder.Append(expr.Type.ToString());
builder.Append("(");
for (int i = 0, n = expr.Expressions.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
Summarize(builder, expr.Expressions[i], level);
}
builder.Append(")");
}
else
{
Debug.Assert(expr.NodeType == ExpressionType.NewArrayInit);
builder.Append("new ");
builder.Append("[] {");
for (int i = 0, n = expr.Expressions.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
Summarize(builder, expr.Expressions[i], level);
}
builder.Append("}");
}
}
private static void SummarizeMemberInitExpression(StringBuilder builder, MemberInitExpression expr, int level)
{
if (expr.NewExpression.Arguments.Count == 0 &&
expr.NewExpression.Type.Name.Contains("<"))
{
// anonymous type constructor
builder.Append("new");
}
else
{
Summarize(builder, expr.NewExpression, level);
}
builder.Append(" {");
for (int i = 0, n = expr.Bindings.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
SummarizeMemberBinding(builder, expr.Bindings[i], level);
}
builder.Append("}");
}
private static void SummarizeListInitExpression(StringBuilder builder, ListInitExpression expr, int level)
{
Summarize(builder, expr.NewExpression, level);
builder.Append(" {");
for (int i = 0, n = expr.Initializers.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
SummarizeElementInit(builder, expr.Initializers[i], level);
}
builder.Append("}");
}
private static void SummarizeParameterExpression(StringBuilder builder, ParameterExpression expr)
{
if (expr.Name != null)
{
builder.Append(expr.Name);
}
else
{
builder.Append('_');
}
}
private static void SummarizeTypeBinaryExpression(StringBuilder builder, TypeBinaryExpression expr, int level)
{
Debug.Assert(expr.NodeType == ExpressionType.TypeIs);
builder.Append("(");
Summarize(builder, expr.Expression, level);
builder.Append(" is ");
builder.Append(TypeSystem.TypeName(expr.TypeOperand));
builder.Append(")");
}
private static void SummarizeUnaryExpression(StringBuilder builder, UnaryExpression expr, int level)
{
switch (expr.NodeType)
{
case ExpressionType.ArrayLength:
{
Summarize(builder, expr.Operand, level);
builder.Append(".Length");
break;
}
case ExpressionType.Convert:
{
// do not show type casts
Summarize(builder, expr.Operand, level);
break;
}
case ExpressionType.TypeAs:
{
// do not show type casts
Summarize(builder, expr.Operand, level);
break;
}
case ExpressionType.Not:
{
builder.Append("!(");
Summarize(builder, expr.Operand, level);
builder.Append(")");
break;
}
case ExpressionType.Negate:
{
builder.Append("-(");
Summarize(builder, expr.Operand, level);
builder.Append(")");
break;
}
case ExpressionType.Quote:
{
Summarize(builder, expr.Operand, level);
break;
}
default:
{
builder.Append(expr.NodeType);
builder.Append("(");
Summarize(builder, expr.Operand, level);
builder.Append(")");
break;
}
}
}
private static void SummarizeMemberBinding(StringBuilder builder, MemberBinding binding, int level)
{
if (binding is MemberAssignment)
{
builder.Append(binding.Member.Name);
builder.Append(" = ");
Summarize(builder, ((MemberAssignment)binding).Expression, level);
}
else if (binding is MemberMemberBinding)
{
builder.Append(binding.Member.Name);
builder.Append(" = {");
MemberMemberBinding mmBinding = (MemberMemberBinding)binding;
for (int i = 0, n = mmBinding.Bindings.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
SummarizeMemberBinding(builder, mmBinding.Bindings[i], level);
}
builder.Append("}");
}
else
{
Debug.Assert(binding is MemberListBinding);
builder.Append(binding.Member.Name);
builder.Append(" = {");
MemberListBinding mlBinding = (MemberListBinding)binding;
for (int i = 0, n = mlBinding.Initializers.Count; i < n; i++)
{
if (i > 0) builder.Append(", ");
SummarizeElementInit(builder, mlBinding.Initializers[i], level);
}
builder.Append("}");
}
}
private static void SummarizeElementInit(StringBuilder builder, ElementInit elemInit, int level)
{
builder.Append(elemInit.AddMethod.Name);
builder.Append("(");
bool isFirst = true;
foreach (Expression argument in elemInit.Arguments)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.Append(",");
}
Summarize(builder, argument, level);
}
builder.Append(")");
}
#endregion
}
}
| |
/*
* Copyright 2010 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 ZXing.Common;
using ZXing.Common.Detector;
using ZXing.Common.ReedSolomon;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
/// is rotated or skewed, or partially obscured.
/// </summary>
/// <author>David Olivier</author>
internal sealed class Detector
{
private readonly BitMatrix image;
private bool compact;
private int nbLayers;
private int nbDataBlocks;
private int nbCenterLayers;
private int shift;
/// <summary>
/// Initializes a new instance of the <see cref="Detector"/> class.
/// </summary>
/// <param name="image">The image.</param>
public Detector(BitMatrix image)
{
this.image = image;
}
/// <summary>
/// Detects an Aztec Code in an image.
/// </summary>
public AztecDetectorResult detect()
{
return detect(false);
}
/// <summary>
/// Detects an Aztec Code in an image.
/// </summary>
/// <param name="isMirror">if set to <c>true</c> [is mirror].</param>
/// <returns>
/// encapsulating results of detecting an Aztec Code
/// </returns>
public AztecDetectorResult detect(bool isMirror)
{
// 1. Get the center of the aztec matrix
var pCenter = getMatrixCenter();
if (pCenter == null)
return null;
// 2. Get the center points of the four diagonal points just outside the bull's eye
// [topRight, bottomRight, bottomLeft, topLeft]
var bullsEyeCorners = getBullsEyeCorners(pCenter);
if (bullsEyeCorners == null)
{
return null;
}
if (isMirror)
{
ResultPoint temp = bullsEyeCorners[0];
bullsEyeCorners[0] = bullsEyeCorners[2];
bullsEyeCorners[2] = temp;
}
// 3. Get the size of the matrix and other parameters from the bull's eye
if (!extractParameters(bullsEyeCorners))
{
return null;
}
// 4. Sample the grid
var bits = sampleGrid(image,
bullsEyeCorners[shift%4],
bullsEyeCorners[(shift + 1)%4],
bullsEyeCorners[(shift + 2)%4],
bullsEyeCorners[(shift + 3)%4]);
if (bits == null)
{
return null;
}
// 5. Get the corners of the matrix.
var corners = getMatrixCornerPoints(bullsEyeCorners);
if (corners == null)
{
return null;
}
return new AztecDetectorResult(bits, corners, compact, nbDataBlocks, nbLayers);
}
/// <summary>
/// Extracts the number of data layers and data blocks from the layer around the bull's eye
/// </summary>
/// <param name="bullsEyeCorners">bullEyeCornerPoints the array of bull's eye corners</param>
/// <returns></returns>
private bool extractParameters(ResultPoint[] bullsEyeCorners)
{
if (!isValid(bullsEyeCorners[0]) || !isValid(bullsEyeCorners[1]) ||
!isValid(bullsEyeCorners[2]) || !isValid(bullsEyeCorners[3]))
{
return false;
}
int length = 2 * nbCenterLayers;
// Get the bits around the bull's eye
int[] sides =
{
sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
};
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
shift = getRotation(sides, length);
if (shift < 0)
return false;
// Flatten the parameter bits into a single 28- or 40-bit long
long parameterData = 0;
for (int i = 0; i < 4; i++)
{
int side = sides[(shift + i) % 4];
if (compact)
{
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
}
else
{
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
int correctedData = getCorrectedParameterData(parameterData, compact);
if (correctedData < 0)
return false;
if (compact)
{
// 8 bits: 2 bits layers and 6 bits data blocks
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3F) + 1;
}
else
{
// 16 bits: 5 bits layers and 11 bits data blocks
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7FF) + 1;
}
return true;
}
private static readonly int[] EXPECTED_CORNER_BITS =
{
0xee0, // 07340 XXX .XX X.. ...
0x1dc, // 00734 ... XXX .XX X..
0x83b, // 04073 X.. ... XXX .XX
0x707, // 03407 .XX X.. ... XXX
};
private static int getRotation(int[] sides, int length)
{
// In a normal pattern, we expect to See
// ** .* D A
// * *
//
// . *
// .. .. C B
//
// Grab the 3 bits from each of the sides the form the locator pattern and concatenate
// into a 12-bit integer. Start with the bit at A
int cornerBits = 0;
foreach (int side in sides)
{
// XX......X where X's are orientation marks
int t = ((side >> (length - 2)) << 1) + (side & 1);
cornerBits = (cornerBits << 3) + t;
}
// Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
// together. cornerBits is now:
// 3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
cornerBits = ((cornerBits & 1) << 11) + (cornerBits >> 1);
// The result shift indicates which element of BullsEyeCorners[] goes into the top-left
// corner. Since the four rotation values have a Hamming distance of 8, we
// can easily tolerate two errors.
for (int shift = 0; shift < 4; shift++)
{
if (SupportClass.bitCount(cornerBits ^ EXPECTED_CORNER_BITS[shift]) <= 2)
{
return shift;
}
}
return -1;
}
/// <summary>
/// Corrects the parameter bits using Reed-Solomon algorithm
/// </summary>
/// <param name="parameterData">paremeter bits</param>
/// <param name="compact">compact true if this is a compact Aztec code</param>
/// <returns></returns>
private static int getCorrectedParameterData(long parameterData, bool compact)
{
int numCodewords;
int numDataCodewords;
if (compact)
{
numCodewords = 7;
numDataCodewords = 2;
}
else
{
numCodewords = 10;
numDataCodewords = 4;
}
int numECCodewords = numCodewords - numDataCodewords;
int[] parameterWords = new int[numCodewords];
for (int i = numCodewords - 1; i >= 0; --i)
{
parameterWords[i] = (int)parameterData & 0xF;
parameterData >>= 4;
}
var rsDecoder = new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);
if (!rsDecoder.decode(parameterWords, numECCodewords))
return -1;
// Toss the error correction. Just return the data as an integer
int result = 0;
for (int i = 0; i < numDataCodewords; i++)
{
result = (result << 4) + parameterWords[i];
}
return result;
}
/// <summary>
/// Finds the corners of a bull-eye centered on the passed point
/// This returns the centers of the diagonal points just outside the bull's eye
/// Returns [topRight, bottomRight, bottomLeft, topLeft]
/// </summary>
/// <param name="pCenter">Center point</param>
/// <returns>The corners of the bull-eye</returns>
private ResultPoint[] getBullsEyeCorners(Point pCenter)
{
Point pina = pCenter;
Point pinb = pCenter;
Point pinc = pCenter;
Point pind = pCenter;
bool color = true;
for (nbCenterLayers = 1; nbCenterLayers < 9; nbCenterLayers++)
{
Point pouta = getFirstDifferent(pina, color, 1, -1);
Point poutb = getFirstDifferent(pinb, color, 1, 1);
Point poutc = getFirstDifferent(pinc, color, -1, 1);
Point poutd = getFirstDifferent(pind, color, -1, -1);
//d a
//
//c b
if (nbCenterLayers > 2)
{
float q = distance(poutd, pouta)*nbCenterLayers/(distance(pind, pina)*(nbCenterLayers + 2));
if (q < 0.75 || q > 1.25 || !isWhiteOrBlackRectangle(pouta, poutb, poutc, poutd))
{
break;
}
}
pina = pouta;
pinb = poutb;
pinc = poutc;
pind = poutd;
color = !color;
}
if (nbCenterLayers != 5 && nbCenterLayers != 7)
{
return null;
}
compact = nbCenterLayers == 5;
// Expand the square by .5 pixel in each direction so that we're on the border
// between the white square and the black square
var pinax = new ResultPoint(pina.X + 0.5f, pina.Y - 0.5f);
var pinbx = new ResultPoint(pinb.X + 0.5f, pinb.Y + 0.5f);
var pincx = new ResultPoint(pinc.X - 0.5f, pinc.Y + 0.5f);
var pindx = new ResultPoint(pind.X - 0.5f, pind.Y - 0.5f);
// Expand the square so that its corners are the centers of the points
// just outside the bull's eye.
return expandSquare(new[] {pinax, pinbx, pincx, pindx},
2*nbCenterLayers - 3,
2*nbCenterLayers);
}
/// <summary>
/// Finds a candidate center point of an Aztec code from an image
/// </summary>
/// <returns>the center point</returns>
private Point getMatrixCenter()
{
ResultPoint pointA;
ResultPoint pointB;
ResultPoint pointC;
ResultPoint pointD;
int cx;
int cy;
//Get a white rectangle that can be the border of the matrix in center bull's eye or
var whiteDetector = WhiteRectangleDetector.Create(image);
if (whiteDetector == null)
return null;
ResultPoint[] cornerPoints = whiteDetector.detect();
if (cornerPoints != null)
{
pointA = cornerPoints[0];
pointB = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
}
else
{
// This exception can be in case the initial rectangle is white
// In that case, surely in the bull's eye, we try to expand the rectangle.
cx = image.Width/2;
cy = image.Height/2;
pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
pointB = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
//Compute the center of the rectangle
cx = MathUtils.round((pointA.X + pointD.X + pointB.X + pointC.X) / 4.0f);
cy = MathUtils.round((pointA.Y + pointD.Y + pointB.Y + pointC.Y) / 4.0f);
// Redetermine the white rectangle starting from previously computed center.
// This will ensure that we end up with a white rectangle in center bull's eye
// in order to compute a more accurate center.
whiteDetector = WhiteRectangleDetector.Create(image, 15, cx, cy);
if (whiteDetector == null)
return null;
cornerPoints = whiteDetector.detect();
if (cornerPoints != null)
{
pointA = cornerPoints[0];
pointB = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
}
else
{
// This exception can be in case the initial rectangle is white
// In that case we try to expand the rectangle.
pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
pointB = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
// Recompute the center of the rectangle
cx = MathUtils.round((pointA.X + pointD.X + pointB.X + pointC.X) / 4.0f);
cy = MathUtils.round((pointA.Y + pointD.Y + pointB.Y + pointC.Y) / 4.0f);
return new Point(cx, cy);
}
/// <summary>
/// Gets the Aztec code corners from the bull's eye corners and the parameters.
/// </summary>
/// <param name="bullsEyeCorners">the array of bull's eye corners</param>
/// <returns>the array of aztec code corners</returns>
private ResultPoint[] getMatrixCornerPoints(ResultPoint[] bullsEyeCorners)
{
return expandSquare(bullsEyeCorners, 2 * nbCenterLayers, getDimension());
}
/// <summary>
/// Creates a BitMatrix by sampling the provided image.
/// topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
/// diagonal just outside the bull's eye.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="topLeft">The top left.</param>
/// <param name="bottomLeft">The bottom left.</param>
/// <param name="bottomRight">The bottom right.</param>
/// <param name="topRight">The top right.</param>
/// <returns></returns>
private BitMatrix sampleGrid(BitMatrix image,
ResultPoint topLeft,
ResultPoint topRight,
ResultPoint bottomRight,
ResultPoint bottomLeft)
{
GridSampler sampler = GridSampler.Instance;
int dimension = getDimension();
float low = dimension/2.0f - nbCenterLayers;
float high = dimension/2.0f + nbCenterLayers;
return sampler.sampleGrid(image,
dimension,
dimension,
low, low, // topleft
high, low, // topright
high, high, // bottomright
low, high, // bottomleft
topLeft.X, topLeft.Y,
topRight.X, topRight.Y,
bottomRight.X, bottomRight.Y,
bottomLeft.X, bottomLeft.Y);
}
/// <summary>
/// Samples a line
/// </summary>
/// <param name="p1">start point (inclusive)</param>
/// <param name="p2">end point (exclusive)</param>
/// <param name="size">number of bits</param>
/// <returns> the array of bits as an int (first bit is high-order bit of result)</returns>
private int sampleLine(ResultPoint p1, ResultPoint p2, int size)
{
int result = 0;
float d = distance(p1, p2);
float moduleSize = d / size;
float px = p1.X;
float py = p1.Y;
float dx = moduleSize * (p2.X - p1.X) / d;
float dy = moduleSize * (p2.Y - p1.Y) / d;
for (int i = 0; i < size; i++)
{
if (image[MathUtils.round(px + i * dx), MathUtils.round(py + i * dy)])
{
result |= 1 << (size - i - 1);
}
}
return result;
}
/// <summary>
/// Determines whether [is white or black rectangle] [the specified p1].
/// </summary>
/// <param name="p1">The p1.</param>
/// <param name="p2">The p2.</param>
/// <param name="p3">The p3.</param>
/// <param name="p4">The p4.</param>
/// <returns>true if the border of the rectangle passed in parameter is compound of white points only
/// or black points only</returns>
private bool isWhiteOrBlackRectangle(Point p1, Point p2, Point p3, Point p4)
{
const int corr = 3;
p1 = new Point(p1.X - corr, p1.Y + corr);
p2 = new Point(p2.X - corr, p2.Y - corr);
p3 = new Point(p3.X + corr, p3.Y - corr);
p4 = new Point(p4.X + corr, p4.Y + corr);
int cInit = getColor(p4, p1);
if (cInit == 0)
{
return false;
}
int c = getColor(p1, p2);
if (c != cInit)
{
return false;
}
c = getColor(p2, p3);
if (c != cInit)
{
return false;
}
c = getColor(p3, p4);
return c == cInit;
}
/// <summary>
/// Gets the color of a segment
/// </summary>
/// <param name="p1">The p1.</param>
/// <param name="p2">The p2.</param>
/// <returns>1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else</returns>
private int getColor(Point p1, Point p2)
{
float d = distance(p1, p2);
float dx = (p2.X - p1.X) / d;
float dy = (p2.Y - p1.Y) / d;
int error = 0;
float px = p1.X;
float py = p1.Y;
bool colorModel = image[p1.X, p1.Y];
for (int i = 0; i < d; i++)
{
px += dx;
py += dy;
if (image[MathUtils.round(px), MathUtils.round(py)] != colorModel)
{
error++;
}
}
float errRatio = error / d;
if (errRatio > 0.1f && errRatio < 0.9f)
{
return 0;
}
return (errRatio <= 0.1f) == colorModel ? 1 : -1;
}
/// <summary>
/// Gets the coordinate of the first point with a different color in the given direction
/// </summary>
/// <param name="init">The init.</param>
/// <param name="color">if set to <c>true</c> [color].</param>
/// <param name="dx">The dx.</param>
/// <param name="dy">The dy.</param>
/// <returns></returns>
private Point getFirstDifferent(Point init, bool color, int dx, int dy)
{
int x = init.X + dx;
int y = init.Y + dy;
while (isValid(x, y) && image[x, y] == color)
{
x += dx;
y += dy;
}
x -= dx;
y -= dy;
while (isValid(x, y) && image[x, y] == color)
{
x += dx;
}
x -= dx;
while (isValid(x, y) && image[x, y] == color)
{
y += dy;
}
y -= dy;
return new Point(x, y);
}
/// <summary>
/// Expand the square represented by the corner points by pushing out equally in all directions
/// </summary>
/// <param name="cornerPoints">the corners of the square, which has the bull's eye at its center</param>
/// <param name="oldSide">the original length of the side of the square in the target bit matrix</param>
/// <param name="newSide">the new length of the size of the square in the target bit matrix</param>
/// <returns>the corners of the expanded square</returns>
private static ResultPoint[] expandSquare(ResultPoint[] cornerPoints, float oldSide, float newSide)
{
float ratio = newSide/(2*oldSide);
float dx = cornerPoints[0].X - cornerPoints[2].X;
float dy = cornerPoints[0].Y - cornerPoints[2].Y;
float centerx = (cornerPoints[0].X + cornerPoints[2].X)/2.0f;
float centery = (cornerPoints[0].Y + cornerPoints[2].Y)/2.0f;
var result0 = new ResultPoint(centerx + ratio*dx, centery + ratio*dy);
var result2 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
dx = cornerPoints[1].X - cornerPoints[3].X;
dy = cornerPoints[1].Y - cornerPoints[3].Y;
centerx = (cornerPoints[1].X + cornerPoints[3].X)/2.0f;
centery = (cornerPoints[1].Y + cornerPoints[3].Y)/2.0f;
var result1 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
var result3 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
return new ResultPoint[] {result0, result1, result2, result3};
}
private bool isValid(int x, int y)
{
return x >= 0 && x < image.Width && y > 0 && y < image.Height;
}
private bool isValid(ResultPoint point)
{
int x = MathUtils.round(point.X);
int y = MathUtils.round(point.Y);
return isValid(x, y);
}
// L2 distance
private static float distance(Point a, Point b)
{
return MathUtils.distance(a.X, a.Y, b.X, b.Y);
}
private static float distance(ResultPoint a, ResultPoint b)
{
return MathUtils.distance(a.X, a.Y, b.X, b.Y);
}
private int getDimension()
{
if (compact)
{
return 4 * nbLayers + 11;
}
if (nbLayers <= 4)
{
return 4 * nbLayers + 15;
}
return 4 * nbLayers + 2 * ((nbLayers - 4) / 8 + 1) + 15;
}
internal sealed class Point
{
public int X { get; private set; }
public int Y { get; private set; }
public ResultPoint toResultPoint()
{
return new ResultPoint(X, Y);
}
internal Point(int x, int y)
{
X = x;
Y = y;
}
public override String ToString()
{
return "<" + X + ' ' + Y + '>';
}
}
}
}
| |
// 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.DirectoryServices.ActiveDirectory
{
using System;
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
public class ActiveDirectorySchemaClassCollection : CollectionBase
{
private DirectoryEntry _classEntry = null;
private string _propertyName = null;
private ActiveDirectorySchemaClass _schemaClass = null;
private bool _isBound = false;
private DirectoryContext _context = null;
internal ActiveDirectorySchemaClassCollection(DirectoryContext context,
ActiveDirectorySchemaClass schemaClass,
bool isBound,
string propertyName,
ICollection classNames,
bool onlyNames)
{
_schemaClass = schemaClass;
_propertyName = propertyName;
_isBound = isBound;
_context = context;
foreach (string ldapDisplayName in classNames)
{
// all properties in writeable class collection are non-defunct
// so calling constructor for non-defunct class
this.InnerList.Add(new ActiveDirectorySchemaClass(context, ldapDisplayName, (DirectoryEntry)null, null));
}
}
internal ActiveDirectorySchemaClassCollection(DirectoryContext context,
ActiveDirectorySchemaClass schemaClass,
bool isBound,
string propertyName,
ICollection classes)
{
_schemaClass = schemaClass;
_propertyName = propertyName;
_isBound = isBound;
_context = context;
foreach (ActiveDirectorySchemaClass schClass in classes)
{
this.InnerList.Add(schClass);
}
}
public ActiveDirectorySchemaClass this[int index]
{
get
{
return (ActiveDirectorySchemaClass)List[index];
}
set
{
if (value == null)
throw new ArgumentNullException("value");
if (!value.isBound)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , value.Name));
}
if (!Contains(value))
{
List[index] = value;
}
else
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , value), "value");
}
}
}
public int Add(ActiveDirectorySchemaClass schemaClass)
{
if (schemaClass == null)
{
throw new ArgumentNullException("schemaClass");
}
if (!schemaClass.isBound)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
}
if (!Contains(schemaClass))
{
return List.Add(schemaClass);
}
else
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , schemaClass), "schemaClass");
}
}
public void AddRange(ActiveDirectorySchemaClass[] schemaClasses)
{
if (schemaClasses == null)
{
throw new ArgumentNullException("schemaClasses");
}
foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses)
{
if (schemaClass == null)
{
throw new ArgumentException("schemaClasses");
}
}
for (int i = 0; ((i) < (schemaClasses.Length)); i = ((i) + (1)))
{
this.Add((ActiveDirectorySchemaClass)schemaClasses[i]);
}
}
public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses)
{
if (schemaClasses == null)
{
throw new ArgumentNullException("schemaClasses");
}
foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses)
{
if (schemaClass == null)
{
throw new ArgumentException("schemaClasses");
}
}
int currentCount = schemaClasses.Count;
for (int i = 0; i < currentCount; i++)
{
this.Add(schemaClasses[i]);
}
}
public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses)
{
if (schemaClasses == null)
{
throw new ArgumentNullException("schemaClasses");
}
foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses)
{
if (schemaClass == null)
{
throw new ArgumentException("schemaClasses");
}
}
int currentCount = schemaClasses.Count;
for (int i = 0; i < currentCount; i++)
{
this.Add(schemaClasses[i]);
}
}
public void Remove(ActiveDirectorySchemaClass schemaClass)
{
if (schemaClass == null)
{
throw new ArgumentNullException("schemaClass");
}
if (!schemaClass.isBound)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
}
for (int i = 0; i < InnerList.Count; i++)
{
ActiveDirectorySchemaClass tmp = (ActiveDirectorySchemaClass)InnerList[i];
if (Utils.Compare(tmp.Name, schemaClass.Name) == 0)
{
List.Remove(tmp);
return;
}
}
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotFoundInCollection , schemaClass), "schemaClass");
}
public void Insert(int index, ActiveDirectorySchemaClass schemaClass)
{
if (schemaClass == null)
{
throw new ArgumentNullException("schemaClass");
}
if (!schemaClass.isBound)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
}
if (!Contains(schemaClass))
{
List.Insert(index, schemaClass);
}
else
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , schemaClass), "schemaClass");
}
}
public bool Contains(ActiveDirectorySchemaClass schemaClass)
{
if (schemaClass == null)
{
throw new ArgumentNullException("schemaClass");
}
if (!schemaClass.isBound)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
}
for (int i = 0; i < InnerList.Count; i++)
{
ActiveDirectorySchemaClass tmp = (ActiveDirectorySchemaClass)InnerList[i];
if (Utils.Compare(tmp.Name, schemaClass.Name) == 0)
{
return true;
}
}
return false;
}
public void CopyTo(ActiveDirectorySchemaClass[] schemaClasses, int index)
{
List.CopyTo(schemaClasses, index);
}
public int IndexOf(ActiveDirectorySchemaClass schemaClass)
{
if (schemaClass == null)
throw new ArgumentNullException("schemaClass");
if (!schemaClass.isBound)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
}
for (int i = 0; i < InnerList.Count; i++)
{
ActiveDirectorySchemaClass tmp = (ActiveDirectorySchemaClass)InnerList[i];
if (Utils.Compare(tmp.Name, schemaClass.Name) == 0)
{
return i;
}
}
return -1;
}
protected override void OnClearComplete()
{
if (_isBound)
{
if (_classEntry == null)
{
_classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
}
try
{
if (_classEntry.Properties.Contains(_propertyName))
{
_classEntry.Properties[_propertyName].Clear();
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
}
protected override void OnInsertComplete(int index, object value)
{
if (_isBound)
{
if (_classEntry == null)
{
_classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
}
try
{
_classEntry.Properties[_propertyName].Add(((ActiveDirectorySchemaClass)value).Name);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
}
protected override void OnRemoveComplete(int index, object value)
{
if (_isBound)
{
if (_classEntry == null)
{
_classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
}
// because this collection can contain values from the superior classes,
// these values would not exist in the classEntry
// and therefore cannot be removed
// we need to throw an exception here
string valueName = ((ActiveDirectorySchemaClass)value).Name;
try
{
if (_classEntry.Properties[_propertyName].Contains(valueName))
{
_classEntry.Properties[_propertyName].Remove(valueName);
}
else
{
throw new ActiveDirectoryOperationException(SR.ValueCannotBeModified);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
}
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
if (_isBound)
{
// remove the old value
OnRemoveComplete(index, oldValue);
// add the new value
OnInsertComplete(index, newValue);
}
}
protected override void OnValidate(Object value)
{
if (value == null) throw new ArgumentNullException("value");
if (!(value is ActiveDirectorySchemaClass))
throw new ArgumentException("value");
if (!((ActiveDirectorySchemaClass)value).isBound)
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , ((ActiveDirectorySchemaClass)value).Name));
}
internal string[] GetMultiValuedProperty()
{
string[] values = new string[InnerList.Count];
for (int i = 0; i < InnerList.Count; i++)
{
values[i] = ((ActiveDirectorySchemaClass)InnerList[i]).Name;
}
return values;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: PoweredBy.cs 640 2009-06-01 17:22:02Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using Assembly = System.Reflection.Assembly;
using HttpUtility = System.Web.HttpUtility;
using Cache = System.Web.Caching.Cache;
using CacheItemPriority = System.Web.Caching.CacheItemPriority;
using HttpRuntime = System.Web.HttpRuntime;
#endregion
/// <summary>
/// Displays a "Powered-by ELMAH" message that also contains the assembly
/// file version informatin and copyright notice.
/// </summary>
public sealed class PoweredBy : WebControl
{
private AboutSet _about;
/// <summary>
/// Renders the contents of the control into the specified writer.
/// </summary>
protected override void RenderContents(HtmlTextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
//
// Write out the assembly title, version number, copyright and
// license.
//
AboutSet about = this.About;
writer.Write("Powered by ");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "http://elmah.googlecode.com/");
writer.RenderBeginTag(HtmlTextWriterTag.A);
HttpUtility.HtmlEncode(Mask.EmptyString(about.Product, "(product)"), writer);
writer.RenderEndTag();
writer.Write(", version ");
string version = about.GetFileVersionString();
if (version.Length == 0)
version = about.GetVersionString();
HttpUtility.HtmlEncode(Mask.EmptyString(version, "?.?.?.?"), writer);
#if DEBUG
writer.Write(" (" + Build.Configuration + ")");
#endif
writer.Write(". ");
string copyright = about.Copyright;
if (copyright.Length > 0)
{
HttpUtility.HtmlEncode(copyright, writer);
writer.Write(' ');
}
writer.Write("Licensed under ");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "http://www.apache.org/licenses/LICENSE-2.0");
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("Apache License, Version 2.0");
writer.RenderEndTag();
writer.Write(". ");
}
private AboutSet About
{
get
{
return _about ?? (_about = GetAbout(Cache, (version, fileVersion, product, copyright) => new AboutSet
{
Version = version,
FileVersion = fileVersion,
Product = product,
Copyright = copyright,
}));
}
}
private Cache Cache
{
get
{
//
// Get the cache from the container page, or failing that,
// from the runtime. The Page property can be null
// if the control has not been added to a page's controls
// hierarchy.
//
return this.Page != null? this.Page.Cache : HttpRuntime.Cache;
}
}
internal static T GetAbout<T>(Cache cache, Func<Version, Version, string, string, T> selector)
{
var cacheKey = typeof(PoweredBy).FullName;
//
// If cache is available then check if the version
// information is already residing in there.
//
if (cache != null)
{
Debug.Assert(cacheKey != null);
var tuple = (object[]) cache[cacheKey];
if (tuple != null)
return selector((Version) tuple[0], (Version) tuple[1], (string) tuple[2], (string) tuple[3]);
}
//
// Not found in the cache? Go out and get the version
// information of the assembly housing this component.
//
//
// NOTE: The assembly information is picked up from the
// applied attributes rather that the more convenient
// FileVersionInfo because the latter required elevated
// permissions and may throw a security exception if
// called from a partially trusted environment, such as
// the medium trust level in ASP.NET.
//
var assembly = typeof(ErrorLog).Assembly;
var attributes = new
{
Version = (AssemblyFileVersionAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyFileVersionAttribute)),
Product = (AssemblyProductAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyProductAttribute)),
Copyright = (AssemblyCopyrightAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute)),
};
var version = assembly.GetName().Version;
var fileVersion = attributes.Version != null ? new Version(attributes.Version.Version) : null;
var product = attributes.Product != null ? attributes.Product.Product : null;
var copyright = attributes.Copyright != null ? attributes.Copyright.Copyright : null;
//
// Cache for next time if the cache is available.
//
if (cache != null)
{
cache.Add(cacheKey,
new object[] { version, fileVersion, product, copyright, },
/* absoluteExpiration */ null, Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(2), CacheItemPriority.Normal, null);
}
return selector(version, fileVersion, product, copyright);
}
[ Serializable ]
private sealed class AboutSet
{
private string _product;
private Version _version;
private Version _fileVersion;
private string _copyright;
public string Product
{
get { return _product ?? string.Empty; }
set { _product = value; }
}
public Version Version
{
get { return _version; }
set { _version = value; }
}
public string GetVersionString()
{
return _version != null ? _version.ToString() : string.Empty;
}
public Version FileVersion
{
get { return _fileVersion; }
set { _fileVersion = value; }
}
public string GetFileVersionString()
{
return _fileVersion != null ? _fileVersion.ToString() : string.Empty;
}
public string Copyright
{
get { return _copyright ?? string.Empty; }
set { _copyright = 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.
namespace System.ServiceModel.Security
{
using System.IdentityModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.Runtime.CompilerServices;
using Microsoft.Xml;
using DictionaryManager = System.IdentityModel.DictionaryManager;
using ISecurityElement = System.IdentityModel.ISecurityElement;
[TypeForwardedFrom("System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal abstract class EncryptedType : ISecurityElement
{
internal static readonly XmlDictionaryString NamespaceUri = XD.XmlEncryptionDictionary.Namespace;
internal static readonly XmlDictionaryString EncodingAttribute = XD.XmlEncryptionDictionary.Encoding;
internal static readonly XmlDictionaryString MimeTypeAttribute = XD.XmlEncryptionDictionary.MimeType;
internal static readonly XmlDictionaryString TypeAttribute = XD.XmlEncryptionDictionary.Type;
internal static readonly XmlDictionaryString CipherDataElementName = XD.XmlEncryptionDictionary.CipherData;
internal static readonly XmlDictionaryString CipherValueElementName = XD.XmlEncryptionDictionary.CipherValue;
private string _encoding;
private EncryptionMethodElement _encryptionMethod;
private string _id;
private string _wsuId;
private SecurityKeyIdentifier _keyIdentifier;
private string _mimeType;
private EncryptionState _state;
private string _type;
private SecurityTokenSerializer _tokenSerializer;
private bool _shouldReadXmlReferenceKeyInfoClause;
protected EncryptedType()
{
_encryptionMethod.Init();
_state = EncryptionState.New;
}
public string Encoding
{
get
{
return _encoding;
}
set
{
_encoding = value;
}
}
public string EncryptionMethod
{
get
{
return _encryptionMethod.algorithm;
}
set
{
_encryptionMethod.algorithm = value;
}
}
public XmlDictionaryString EncryptionMethodDictionaryString
{
get
{
return _encryptionMethod.algorithmDictionaryString;
}
set
{
_encryptionMethod.algorithmDictionaryString = value;
}
}
public bool HasId
{
get
{
return true;
}
}
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
// This is set to true on the client side. And this means that when this knob is set to true and the default serializers on the client side fail
// to read the KeyInfo clause from the incoming response message from a service; then the ckient should
// try to read the keyInfo clause as GenericXmlSecurityKeyIdentifierClause before throwing.
public bool ShouldReadXmlReferenceKeyInfoClause
{
get
{
return _shouldReadXmlReferenceKeyInfoClause;
}
set
{
_shouldReadXmlReferenceKeyInfoClause = value;
}
}
public string WsuId
{
get
{
return _wsuId;
}
set
{
_wsuId = value;
}
}
public SecurityKeyIdentifier KeyIdentifier
{
get
{
return _keyIdentifier;
}
set
{
_keyIdentifier = value;
}
}
public string MimeType
{
get
{
return _mimeType;
}
set
{
_mimeType = value;
}
}
public string Type
{
get
{
return _type;
}
set
{
_type = value;
}
}
protected abstract XmlDictionaryString OpeningElementName
{
get;
}
protected EncryptionState State
{
get
{
return _state;
}
set
{
_state = value;
}
}
protected abstract void ForceEncryption();
protected virtual void ReadAdditionalAttributes(XmlDictionaryReader reader)
{
}
protected virtual void ReadAdditionalElements(XmlDictionaryReader reader)
{
}
protected abstract void ReadCipherData(XmlDictionaryReader reader);
protected abstract void ReadCipherData(XmlDictionaryReader reader, long maxBufferSize);
public void ReadFrom(XmlReader reader)
{
ReadFrom(reader, 0);
}
public void ReadFrom(XmlDictionaryReader reader)
{
ReadFrom(reader, 0);
}
public void ReadFrom(XmlReader reader, long maxBufferSize)
{
ReadFrom(XmlDictionaryReader.CreateDictionaryReader(reader), maxBufferSize);
}
public void ReadFrom(XmlDictionaryReader reader, long maxBufferSize)
{
ValidateReadState();
reader.MoveToStartElement(OpeningElementName, NamespaceUri);
_encoding = reader.GetAttribute(EncodingAttribute, null);
_id = reader.GetAttribute(XD.XmlEncryptionDictionary.Id, null) ?? SecurityUniqueId.Create().Value;
_wsuId = reader.GetAttribute(XD.XmlEncryptionDictionary.Id, XD.UtilityDictionary.Namespace) ?? SecurityUniqueId.Create().Value;
_mimeType = reader.GetAttribute(MimeTypeAttribute, null);
_type = reader.GetAttribute(TypeAttribute, null);
ReadAdditionalAttributes(reader);
reader.Read();
if (reader.IsStartElement(EncryptionMethodElement.ElementName, NamespaceUri))
{
_encryptionMethod.ReadFrom(reader);
}
if (_tokenSerializer.CanReadKeyIdentifier(reader))
{
XmlElement xml = null;
XmlDictionaryReader localReader;
if (this.ShouldReadXmlReferenceKeyInfoClause)
{
// We create the dom only when needed to not affect perf.
XmlDocument doc = new XmlDocument();
xml = (doc.ReadNode(reader) as XmlElement);
localReader = XmlDictionaryReader.CreateDictionaryReader(new XmlNodeReader(xml));
}
else
{
localReader = reader;
}
try
{
this.KeyIdentifier = _tokenSerializer.ReadKeyIdentifier(localReader);
}
catch (Exception e)
{
// In case when the issued token ( custom token) is used as an initiator token; we will fail
// to read the keyIdentifierClause using the plugged in default serializer. So We need to try to read it as an XmlReferencekeyIdentifierClause
// if it is the client side.
if (Fx.IsFatal(e) || !this.ShouldReadXmlReferenceKeyInfoClause)
{
throw;
}
_keyIdentifier = ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader.CreateDictionaryReader(new XmlNodeReader(xml)), e);
}
}
reader.ReadStartElement(CipherDataElementName, EncryptedType.NamespaceUri);
reader.ReadStartElement(CipherValueElementName, EncryptedType.NamespaceUri);
if (maxBufferSize == 0)
ReadCipherData(reader);
else
ReadCipherData(reader, maxBufferSize);
reader.ReadEndElement(); // CipherValue
reader.ReadEndElement(); // CipherData
ReadAdditionalElements(reader);
reader.ReadEndElement(); // OpeningElementName
this.State = EncryptionState.Read;
}
private SecurityKeyIdentifier ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader localReader, Exception previousException)
{
throw new NotImplementedException();
}
protected virtual void WriteAdditionalAttributes(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
}
protected virtual void WriteAdditionalElements(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
}
protected abstract void WriteCipherData(XmlDictionaryWriter writer);
public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
ValidateWriteState();
writer.WriteStartElement(XmlEncryptionStrings.Prefix, this.OpeningElementName, NamespaceUri);
if (_id != null && _id.Length != 0)
{
writer.WriteAttributeString(XD.XmlEncryptionDictionary.Id, null, this.Id);
}
if (_type != null)
{
writer.WriteAttributeString(TypeAttribute, null, this.Type);
}
if (_mimeType != null)
{
writer.WriteAttributeString(MimeTypeAttribute, null, this.MimeType);
}
if (_encoding != null)
{
writer.WriteAttributeString(EncodingAttribute, null, this.Encoding);
}
WriteAdditionalAttributes(writer, dictionaryManager);
if (_encryptionMethod.algorithm != null)
{
_encryptionMethod.WriteTo(writer);
}
if (this.KeyIdentifier != null)
{
_tokenSerializer.WriteKeyIdentifier(writer, this.KeyIdentifier);
}
writer.WriteStartElement(CipherDataElementName, NamespaceUri);
writer.WriteStartElement(CipherValueElementName, NamespaceUri);
WriteCipherData(writer);
writer.WriteEndElement(); // CipherValue
writer.WriteEndElement(); // CipherData
WriteAdditionalElements(writer, dictionaryManager);
writer.WriteEndElement(); // OpeningElementName
}
private void ValidateReadState()
{
if (this.State != EncryptionState.New)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityMessageSerializationException(SRServiceModel.BadEncryptionState));
}
}
private void ValidateWriteState()
{
if (this.State == EncryptionState.EncryptionSetup)
{
ForceEncryption();
}
else if (this.State == EncryptionState.New)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityMessageSerializationException(SRServiceModel.BadEncryptionState));
}
}
protected enum EncryptionState
{
New,
Read,
DecryptionSetup,
Decrypted,
EncryptionSetup,
Encrypted
}
private struct EncryptionMethodElement
{
internal string algorithm;
internal XmlDictionaryString algorithmDictionaryString;
internal static readonly XmlDictionaryString ElementName = XD.XmlEncryptionDictionary.EncryptionMethod;
public void Init()
{
this.algorithm = null;
}
public void ReadFrom(XmlDictionaryReader reader)
{
reader.MoveToStartElement(ElementName, XD.XmlEncryptionDictionary.Namespace);
bool isEmptyElement = reader.IsEmptyElement;
this.algorithm = reader.GetAttribute(XD.XmlSignatureDictionary.Algorithm, null);
if (this.algorithm == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityMessageSerializationException(
string.Format(SRServiceModel.RequiredAttributeMissing, XD.XmlSignatureDictionary.Algorithm.Value, ElementName.Value)));
}
reader.Read();
if (!isEmptyElement)
{
while (reader.IsStartElement())
{
reader.Skip();
}
reader.ReadEndElement();
}
}
public void WriteTo(XmlDictionaryWriter writer)
{
writer.WriteStartElement(XmlEncryptionStrings.Prefix, ElementName, XD.XmlEncryptionDictionary.Namespace);
if (this.algorithmDictionaryString != null)
{
writer.WriteStartAttribute(XD.XmlSignatureDictionary.Algorithm, null);
writer.WriteString(this.algorithmDictionaryString);
writer.WriteEndAttribute();
}
else
{
writer.WriteAttributeString(XD.XmlSignatureDictionary.Algorithm, null, this.algorithm);
}
if (this.algorithm == XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap.Value)
{
writer.WriteStartElement(XmlSignatureStrings.Prefix, XD.XmlSignatureDictionary.DigestMethod, XD.XmlSignatureDictionary.Namespace);
writer.WriteStartAttribute(XD.XmlSignatureDictionary.Algorithm, null);
writer.WriteString(XD.SecurityAlgorithmDictionary.Sha1Digest);
writer.WriteEndAttribute();
writer.WriteEndElement();
}
writer.WriteEndElement(); // EncryptionMethod
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
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 UnityEditor;
using UnityEditor.Callbacks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;
[InitializeOnLoad]
class ONSPAudioPluginUpdater
{
private static bool restartPending = false;
private static bool unityRunningInBatchmode = false;
private static System.Version invalidVersion = new System.Version("0.0.0");
static ONSPAudioPluginUpdater()
{
EditorApplication.delayCall += OnDelayCall;
}
static void OnDelayCall()
{
if (System.Environment.CommandLine.Contains("-batchmode"))
{
unityRunningInBatchmode = true;
}
if (ShouldAttemptPluginUpdate())
{
AttemptSpatializerPluginUpdate(true);
}
}
private static string GetCurrentProjectPath()
{
return Directory.GetParent(Application.dataPath).FullName;
}
private static string GetUtilitiesRootPath()
{
var so = ScriptableObject.CreateInstance(typeof(ONSPAudioPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string assetPath = AssetDatabase.GetAssetPath(script);
string editorDir = Directory.GetParent(assetPath).FullName;
string ovrDir = Directory.GetParent(editorDir).FullName;
return ovrDir;
}
public static string GetVersionDescription(System.Version version)
{
bool isVersionValid = (version != invalidVersion);
return isVersionValid ? version.ToString() : "(Unknown)";
}
private static bool ShouldAttemptPluginUpdate()
{
if (unityRunningInBatchmode)
{
return false;
}
else
{
return (autoUpdateEnabled && !restartPending && !Application.isPlaying);
}
}
private static readonly string autoUpdateEnabledKey = "Oculus_Utilities_ONSPAudioPluginUpdater_AutoUpdate_" + 1.0;//PASOVRManager.utilitiesVersion;
private static bool autoUpdateEnabled
{
get
{
return PlayerPrefs.GetInt(autoUpdateEnabledKey, 1) == 1;
}
set
{
PlayerPrefs.SetInt(autoUpdateEnabledKey, value ? 1 : 0);
}
}
[MenuItem("Oculus/Tools/Update Spatializer Plugin")]
private static void RunSpatializerPluginUpdate()
{
autoUpdateEnabled = true;
AttemptSpatializerPluginUpdate(false);
}
// Separate entry point needed since "-executeMethod" does not support parameters or default parameter values
private static void BatchmodePluginUpdate()
{
OnDelayCall(); // manually invoke when running editor in batchmode
AttemptSpatializerPluginUpdate(false);
}
private static string GetSpatializerPluginsRootPath()
{
string ovrPath = GetUtilitiesRootPath();
string spatializerPluginsPath = Path.GetFullPath(Path.Combine(ovrPath, "../Spatializer/Plugins"));
return spatializerPluginsPath;
}
private static bool RenameSpatializerPluginToOld(string currentPluginPath)
{
if (File.Exists(currentPluginPath))
{
int index = 0;
string targetPluginPath;
string targetPluginMetaPath;
for (; ; )
{
targetPluginPath = currentPluginPath + ".old" + index.ToString();
targetPluginMetaPath = targetPluginPath + ".meta";
if (!File.Exists(targetPluginPath) && !File.Exists(targetPluginPath))
break;
++index;
}
try
{
File.Move(currentPluginPath, targetPluginPath);
File.Move(currentPluginPath + ".meta", targetPluginMetaPath);
UnityEngine.Debug.LogFormat("Spatializer plugin renamed: {0} to {1}", currentPluginPath, targetPluginPath);
return true;
}
catch (Exception e)
{
UnityEngine.Debug.LogWarningFormat("Unable to rename spatializer plugin: {0}, exception {1}", currentPluginPath, e.Message);
return false;
}
}
return false;
}
private static void AttemptSpatializerPluginUpdate(bool triggeredByAutoUpdate)
{
// We use a simplified path to update spatializer plugins:
// If there is a new AudioPluginOculusSpatializer.dll.new, we'll rename the original one to .old, and the new one to .dll, and restart the editor
string pluginsPath = GetSpatializerPluginsRootPath();
string newX86PluginPath = Path.GetFullPath(Path.Combine(pluginsPath, "x86/AudioPluginOculusSpatializer.dll.new"));
string newX64PluginPath = Path.GetFullPath(Path.Combine(pluginsPath, "x86_64/AudioPluginOculusSpatializer.dll.new"));
if (File.Exists(newX86PluginPath) || File.Exists(newX64PluginPath))
{
bool userAcceptsUpdate = false;
if (unityRunningInBatchmode)
{
userAcceptsUpdate = true;
}
else
{
int dialogResult = EditorUtility.DisplayDialogComplex("Update Spatializer Plugins",
"New spatializer plugin found. Do you want to upgrade? If you choose 'Upgrade', the old plugin will be renamed to AudioPluginOculusSpatializer.old",
"Upgrade", "Don't upgrade", "Delete new plugin");
if (dialogResult == 0)
{
userAcceptsUpdate = true;
}
else if (dialogResult == 1)
{
// do nothing
}
else if (dialogResult == 2)
{
try
{
File.Delete(newX86PluginPath);
File.Delete(newX86PluginPath + ".meta");
File.Delete(newX64PluginPath);
File.Delete(newX64PluginPath + ".meta");
}
catch (Exception e)
{
UnityEngine.Debug.LogWarning("Exception happened when deleting new spatializer plugin: " + e.Message);
}
}
}
if (userAcceptsUpdate)
{
bool upgradeDone = false;
string curX86PluginPath = Path.Combine(pluginsPath, "x86/AudioPluginOculusSpatializer.dll");
if (File.Exists(newX86PluginPath))
{
RenameSpatializerPluginToOld(curX86PluginPath);
try
{
File.Move(newX86PluginPath, curX86PluginPath);
File.Move(newX86PluginPath + ".meta", curX86PluginPath + ".meta");
// fix the platform
string curX86PluginPathRel = "Assets/Oculus/Spatializer/Plugins/x86/AudioPluginOculusSpatializer.dll";
UnityEngine.Debug.Log("path = " + curX86PluginPathRel);
AssetDatabase.ImportAsset(curX86PluginPathRel, ImportAssetOptions.ForceUpdate);
PluginImporter pi = PluginImporter.GetAtPath(curX86PluginPathRel) as PluginImporter;
pi.SetCompatibleWithEditor(false);
pi.SetCompatibleWithAnyPlatform(false);
pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false);
#if UNITY_2017_3_OR_NEWER
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);
#else
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false);
#endif
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, true);
pi.SetCompatibleWithEditor(true);
pi.SetEditorData("CPU", "X86");
pi.SetEditorData("OS", "Windows");
pi.SetPlatformData("Editor", "CPU", "X86");
pi.SetPlatformData("Editor", "OS", "Windows");
AssetDatabase.ImportAsset(curX86PluginPathRel, ImportAssetOptions.ForceUpdate);
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
upgradeDone = true;
}
catch (Exception e)
{
UnityEngine.Debug.LogWarning("Unable to rename the new spatializer plugin: " + e.Message);
}
}
string curX64PluginPath = Path.Combine(pluginsPath, "x86_64/AudioPluginOculusSpatializer.dll");
if (File.Exists(newX64PluginPath))
{
RenameSpatializerPluginToOld(curX64PluginPath);
try
{
File.Move(newX64PluginPath, curX64PluginPath);
File.Move(newX64PluginPath + ".meta", curX64PluginPath + ".meta");
// fix the platform
string curX64PluginPathRel = "Assets/Oculus/Spatializer/Plugins/x86_64/AudioPluginOculusSpatializer.dll";
UnityEngine.Debug.Log("path = " + curX64PluginPathRel);
AssetDatabase.ImportAsset(curX64PluginPathRel, ImportAssetOptions.ForceUpdate);
PluginImporter pi = PluginImporter.GetAtPath(curX64PluginPathRel) as PluginImporter;
pi.SetCompatibleWithEditor(false);
pi.SetCompatibleWithAnyPlatform(false);
pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false);
#if UNITY_2017_3_OR_NEWER
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);
#else
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false);
#endif
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, true);
pi.SetCompatibleWithEditor(true);
pi.SetEditorData("CPU", "X86_64");
pi.SetEditorData("OS", "Windows");
pi.SetPlatformData("Editor", "CPU", "X86_64");
pi.SetPlatformData("Editor", "OS", "Windows");
AssetDatabase.ImportAsset(curX64PluginPathRel, ImportAssetOptions.ForceUpdate);
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
upgradeDone = true;
}
catch (Exception e)
{
UnityEngine.Debug.LogWarning("Unable to rename the new spatializer plugin: " + e.Message);
}
}
if (upgradeDone)
{
if (unityRunningInBatchmode
|| EditorUtility.DisplayDialog("Restart Unity",
"Spatializer plugins has been upgraded."
+ "\n\nPlease restart the Unity Editor to complete the update process."
#if !UNITY_2017_1_OR_NEWER
+ " You may need to manually relaunch Unity if you are using Unity 5.6 and higher."
#endif
,
"Restart",
"Not Now"))
{
RestartUnityEditor();
}
}
}
}
else
{
UnityEngine.Debug.Log("No new spatializer plugin(s) found");
}
}
private static void RestartUnityEditor()
{
if (unityRunningInBatchmode)
{
EditorApplication.Exit(0);
}
else
{
restartPending = true;
EditorApplication.OpenProject(GetCurrentProjectPath());
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Reflection;
using RoslynIntellisense;
using Microsoft.CodeAnalysis;
namespace Syntaxer
{
public class Test
{
public static void All()
{
var trigegr_loadig_var = csscript.Cscs_asm;
// Test.SuggestUsings(); return;
// Test.SignatureHelp(); return;
// Test.Resolving();
// Test.AssignmentCompletion(); return;
// Test.Renaming();
Test.CodeMapVSCode();
// Test.Format();
// Test.Project();
// Test.Tooltip();
// Test.CSSCompletion();
// Test.CSSResolving();
// Test.CSSResolving2();
// Test.CSSTooltipResolving();
}
public static void Format()
{
Output.WriteLine("---");
Output.Write("Formatting: ");
// $safeprojectname$
try
{
// var dummyWorkspace = MSBuildWorkspace.Create();
// SyntaxTree tree = CSharpSyntaxTree.ParseText(SyntaxProvider.testCode.Trim());
// SyntaxNode root = Microsoft.CodeAnalysis.Formatting.Formatter.Format(tree.GetRoot(), dummyWorkspace);
RoslynIntellisense.Formatter.FormatHybrid(SyntaxProvider.testFreestyleCode, "code.cs");
Output.WriteLine("OK");
}
catch (Exception e)
{
Output.WriteLine("failed");
Output.WriteLine(e);
}
}
public static void CodeMapVSCode()
{
var script = Path.GetTempFileName();
Output.WriteLine("---");
Output.Write("CodeMap-VSCode: ");
try
{
var code = @"//css_autoclass
using System;
void main()
{
void ttt()
{
}
}
//css_ac_end
static class Extensions
{
static public void Convert(this string text)
{
}
}";
File.WriteAllText(script, code);
var map = SyntaxProvider.CodeMap(script, false, true);
Output.WriteLine("OK");
}
catch (Exception e)
{
Output.WriteLine("failed");
Output.WriteLine(e);
}
finally
{
try { File.Delete(script); } catch { }
}
}
static void TestScript(Action<string> action, bool local = false)
{
var script = Path.GetTempFileName();
if (local)
{
var localFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
.PathJoin(Path.GetFileName(script));
File.Move(script, localFile);
script = localFile;
}
try
{
var currDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var cscs = Path.Combine(currDir, "cscs.exe");
if (File.Exists(cscs))
csscript.cscs_path = cscs;
else
{
cscs = Path.Combine(Path.GetDirectoryName(currDir), "cscs.exe");
if (File.Exists(cscs))
csscript.cscs_path = cscs;
else
csscript.cscs_path = "./cscs.exe";
}
action(script);
}
catch (Exception e)
{
Output.WriteLine("failed");
Output.WriteLine(e);
}
finally
{
try { File.Delete(script); } catch { }
}
}
public static void Project()
{
TestScript(script =>
{
Output.WriteLine("---");
Output.WriteLine("Generating project: ");
Project project = CSScriptHelper.GenerateProjectFor(new SourceInfo(script));
project.Files.ToList().ForEach(x => Output.WriteLine(" file: " + x));
project.Refs.ToList().ForEach(x => Output.WriteLine(" ref: " + x));
project.SearchDirs.ToList().ForEach(x => Output.WriteLine(" searchDir: " + x));
Output.WriteLine("OK - " + project.Files.Concat(project.Refs).Concat(project.SearchDirs).Count() + " project item(s)");
});
}
public static void Completion()
{
TestScript(script =>
{
Output.WriteLine("---");
Console.Write("Autocompletion: ");
string code = SyntaxProvider.testCode7b;
File.WriteAllText(script, code);
var caret = code.IndexOf("info.ver") + "info.ver".Length;
string word = code.WordAt(caret);
var completions = TestServices.GetCompletion(script, caret);
Output.WriteLine("OK - " + completions.Count() + " completion item(s)...");
Output.WriteLine(" '" + completions.GetLines().FirstOrDefault(x => x.StartsWith(word)) + "'");
});
}
public static void AssignmentCompletion()
{
TestScript(script =>
{
Output.WriteLine("---");
Console.Write("AssignmentCompletion: ");
string code = SyntaxProvider.testCode7b;
// System.IO.StreamReader file =
File.WriteAllText(script, code);
var pattern = "System.IO.StreamReader file =";
pattern = "f.DialogResult =";
pattern = "Form form =";
pattern = "Form form = new";
var caret = code.IndexOf(pattern) + pattern.Length;
string word = code.WordAt(caret);
var completions = TestServices.GetCompletion(script, caret);
Output.WriteLine("OK - " + completions.Count() + " completion item(s)...");
Output.WriteLine(" '" + completions.GetLines().FirstOrDefault(x => x.StartsWith(word)) + "'");
});
}
public static void CSSCompletion()
{
TestScript(script =>
{
Console.Write("CS-Script Autocompletion: ");
File.WriteAllText(script, " //css_inc test.cs");
var caret = 5;
var completions = SyntaxProvider.GetCompletion(script, caret);
Output.WriteLine("OK");
caret = 12;
completions = SyntaxProvider.GetCompletion(script, caret);
File.WriteAllText(script, " //css_inc cmd.cs");
caret = 12;
completions = SyntaxProvider.GetCompletion(script, caret);
caret = 15;
completions = SyntaxProvider.GetCompletion(script, caret);
// Console.WriteLine(" '" + completions.Split('\n').FirstOrDefault(x => x.StartsWith(word)) + "'");
}, local: true);
}
// static void TestCSSCompletion2()
// {
// TestScript(script =>
// {
// Console.Write("CS-Script 'Include' Autocompletion: ");
// string code = " //css_inc test.cs";
// File.WriteAllText(script, code);
// var caret = 12;
// var completions = SyntaxProvider.GetCompletion(script, caret);
// Console.WriteLine("OK");
// caret = 12;
// var word = code.WordAt(caret, true);
// var line = code.LineAt(caret);
// completions = SyntaxProvider.GetCompletion(script, caret);
// // Console.WriteLine(" '" + completions.Split('\n').FirstOrDefault(x => x.StartsWith(word)) + "'");
// });
// }
public static void CSSResolving()
{
TestScript(script =>
{
Output.Write("Resolve CS-Script symbol: ");
string code = " //css_ref test.dll;";
File.WriteAllText(script, code);
var caret = 5;
var info = TestServices.Resolve(script, caret);
Output.WriteLine("OK");
});
}
public static void CSSResolving2()
{
TestScript(script =>
{
Output.Write("Resolve CS-Script symbol: ");
string code = "//css_inc cmd.cs;";
// string code = "//css_ref cmd.dll;";
File.WriteAllText(script, code);
var caret = 13;
var info = TestServices.Resolve(script, caret);
Output.WriteLine(info);
Output.WriteLine("OK");
});
}
public static void CSSTooltipResolving()
{
TestScript(script =>
{
Output.Write("Resolve CS-Script symbol to tooltip: ");
// string code = " //css_ref test.dll;";
string code = " //css_inc cmd.cs;";
File.WriteAllText(script, code);
var caret = 13;
// var caret = 5;
string info = TestServices.GetTooltip(script, caret, null, true);
Output.WriteLine(info);
Output.WriteLine("OK");
});
}
public static void Resolving()
{
TestScript(script =>
{
Output.WriteLine("---");
Output.Write("Resolve symbol: ");
string code = SyntaxProvider.testCode7b;
File.WriteAllText(script, code);
var pattern = "Console.Write";
// pattern = "info.ver";
pattern = "System.IO.StreamReader fi";
var caret = code.IndexOf(pattern) + pattern.Length;
string word = code.WordAt(caret);
var region = TestServices.Resolve(script, caret);
Output.WriteLine("OK - " + 1 + " symbol info item(s)...");
Output.WriteLine(" '" + region.GetLines().FirstOrDefault() + "'");
});
}
public static void Renaming()
{
TestScript(script =>
{
Output.WriteLine("---");
Output.Write("Generate renaming info: ");
string code = SyntaxProvider.testCodeClass;
File.WriteAllText(script, code);
var pattern = "class Scr";
var caret = code.IndexOf(pattern) + pattern.Length;
string word = code.WordAt(caret);
var region = TestServices.FindRefreneces(script, caret, "all");
Output.WriteLine("OK - " + 1 + " symbol info item(s)...");
Output.WriteLine(" '" + region.GetLines().FirstOrDefault() + "'");
});
}
public static void SignatureHelp()
{
TestScript(script =>
{
Output.WriteLine("---");
Output.Write("Generate signature help: ");
string code = @"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(22
// Console.WriteLine(5.ToString(), 33,
}
}";
// Console.WriteLine(22,
File.WriteAllText(script, code);
// var pattern = "WriteLine(";
var pattern = "22";
var caret = code.IndexOf(pattern) + pattern.Length;
string word = code.WordAt(caret);
var region = TestServices.GetSignatureHelp(script, caret);
Output.WriteLine("OK - " + 1 + " symbol info item(s)...");
Output.WriteLine(" '" + region.GetLines().FirstOrDefault() + "'");
});
}
public static void SuggestUsings()
{
TestScript(script =>
{
Output.WriteLine("---");
Output.Write("SuggestUsings: ");
string code = @"using System;
class Program
{
static void Main(string[] args)
{
File
}
}";
File.WriteAllText(script, code);
var pattern = "File";
var caret = code.IndexOf(pattern) + pattern.Length;
string word = code.WordAt(caret);
var region = TestServices.FindUsings(script, "File");
Output.WriteLine("OK - " + 1 + " symbol info item(s)...");
Output.WriteLine(" '" + region.GetLines().FirstOrDefault() + "'");
});
}
public static void Tooltip()
{
TestScript(script =>
{
Output.WriteLine("---");
Output.Write("Get tooltip: ");
string code = SyntaxProvider.testCode7b;
File.WriteAllText(script, code);
var pattern = "Console.Write";
// pattern = "info.ver";
var caret = code.IndexOf(pattern) + pattern.Length;
string word = code.WordAt(caret);
var tooltip = TestServices.GetTooltip(script, caret, null, true);
Output.WriteLine("OK");
Output.WriteLine(" '" + tooltip.GetLines().FirstOrDefault() + "'");
});
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.DownloadMultipleFilesJS
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using System.Drawing.Imaging;
// Todo: how can we prevent the user from dragging a control outside the panel?
// Todo: redesign the cursors and make some new ones.
// Todo: figure out how to store all the graphic information to the database.
// Todo: figure out how to print a graphic as part of a report.
// Note: I originally designed this so that you could enter the text for the control you were
// ABOUT TO DRAW, and not be limited to editing the text of the currently selected item.
// This didn't work too well because I didn't have a separate buffer for "default text".
// In the end it's overkill for this app so I scrapped it.
namespace Factotum
{
public partial class GraphicEdit : Form, IEntityEditForm
{
// **************************************************************
// MEMBER VARIABLES AND ENUMERATIONS
// **************************************************************
private EGraphic curGraphic;
private bool isImageNotFound = false;
private bool isImageAtDefaultPath = false;
// Allow the calling form to access the entity
public IEntity Entity
{
get { return curGraphic; }
}
// The two User Interface modes
public enum UiMode {
SelectMode,
DrawMode
};
// Currently just these drawing tools
public enum DrawingTool {
DoubleBlackArrowSm,
HeadlessBlackArrowSm,
SimpleBlackArrow,
SimpleBlackArrowSm,
YellowTextArrow,
Notation,
Region
};
// The current modes
private UiMode currentUiMode;
private DrawingTool currentDrawingTool;
// The current default font for all new drawing controls that have text
private Font defaultFont;
// **************************************************************
// FORM CONSTRUCTOR
// **************************************************************
public GraphicEdit(Guid? ID)
: this(ID, null){}
public GraphicEdit(Guid? ID, Guid? inspectionID)
{
InitializeComponent();
curGraphic = new EGraphic();
curGraphic.Load(ID);
if (inspectionID != null) curGraphic.GraphicIspID = inspectionID;
InitializeControls(ID == null);
}
private void InitializeControls(bool newRecord)
{
this.Text = newRecord ? "New Graphic" : "Edit Graphic";
// Todo: there should be a default image that possibly directs the user to
// load an image via the load image button
// Set default mode and tool
CurrentUiMode = UiMode.DrawMode;
CurrentDrawingTool = DrawingTool.SimpleBlackArrow;
// Set the default DrawingControl font to the Form's default font.
defaultFont = Font;
tsbFont.ToolTipText = "Set default font";
// Initially no drawing objects, so disable any buttons which require a selection
DisEnableSelectedItemButtons(false);
DisEnableZButtons(false);
SetControlValues();
btnSaveGraphic.Enabled = curGraphic.GraphicBgImageFileName != null;
}
private FontFamily GetFontFamilyForName(string name)
{
FontFamily[] families = FontFamily.Families;
foreach (FontFamily family in families)
{
if (family.Name == name) return family;
}
return FontFamily.GenericSerif;
}
private string SubstituteDefaultImagePath(string imagePath)
{
return UserSettings.sets.DefaultImageFolder + "\\" + Path.GetFileName(imagePath);
}
private Bitmap GetImageDeepClone(Bitmap srcImg)
{
Bitmap srcImgCopy;
PixelFormat fmt;
if (srcImg.PixelFormat == PixelFormat.Format4bppIndexed ||
srcImg.PixelFormat == PixelFormat.Format8bppIndexed ||
srcImg.PixelFormat == PixelFormat.Format1bppIndexed)
fmt = PixelFormat.Format16bppRgb565;
else
fmt = srcImg.PixelFormat;
srcImgCopy = new Bitmap(srcImg.Width, srcImg.Height);
// Make sure the resolution is the same as the original image...
srcImgCopy.SetResolution(srcImg.HorizontalResolution, srcImg.VerticalResolution);
Graphics g = Graphics.FromImage(srcImgCopy);
if (srcImg.Height > srcImg.Width)
{
int sx = srcImg.Height * pnlDrawingPanel.Width / pnlDrawingPanel.Height;
Region reg = new Region(new Rectangle(new Point(0, 0), new Size(sx, srcImg.Height)));
g.Clip = new Region(new Rectangle(new Point(0, 0), new Size(sx, srcImg.Height)));
srcImgCopy = new Bitmap((int)g.ClipBounds.Width, (int)g.ClipBounds.Height, g);
g = Graphics.FromImage(srcImgCopy);
g.FillRegion(Brushes.White, reg);
Point pt = new Point((int)(sx - srcImg.Width) / 2, 0);
g.DrawImage(srcImg, pt);
}
else
{
g.DrawImage(srcImg, new Point(0, 0));
}
g.Dispose();
srcImg.Dispose();
return srcImgCopy;
}
// Set the form controls to the inspected component object values.
private void SetControlValues()
{
Bitmap backImage = null;
if (curGraphic.GraphicIspID != null)
{
EInspection inspection =
new EInspection(curGraphic.GraphicIspID);
lblSiteName.Text = "Graphic for Inspection: '" + inspection.InspectionName + "'";
}
else lblSiteName.Text = "Graphic for Unknown Inspection";
DowUtils.Util.CenterControlHorizInForm(lblSiteName, this);
EDrawingControlCollection ctrls = EDrawingControl.ListForGraphicByZindex(curGraphic.ID);
if (curGraphic.GraphicBgImageFileName != null)
{
if (File.Exists(curGraphic.GraphicBgImageFileName))
{
backImage = (Bitmap)Image.FromFile(curGraphic.GraphicBgImageFileName);
}
else
{
string imgDefaultPath = SubstituteDefaultImagePath(curGraphic.GraphicBgImageFileName);
if (File.Exists(imgDefaultPath))
{
isImageAtDefaultPath = true;
backImage = (Bitmap)Image.FromFile(imgDefaultPath);
}
else
{
isImageNotFound = true;
MessageBox.Show("The background image file: '" + curGraphic.GraphicBgImageFileName
+ "' could not be opened.\r\nIf it has been moved, try changing the Default Image Folder in Preferences > General.",
"Factotum");
}
}
if (backImage != null)
{
backImage = GetImageDeepClone(backImage);
pnlDrawingPanel.BackgroundImage = backImage;
}
}
foreach (EDrawingControl eCtrl in ctrls)
{
FontStyle style = FontStyle.Regular
| (eCtrl.DrawingControlFontIsBold ? FontStyle.Bold : 0)
| (eCtrl.DrawingControlFontIsItalic ? FontStyle.Italic : 0)
| (eCtrl.DrawingControlFontIsUnderlined ? FontStyle.Underline : 0);
FontFamily family = GetFontFamilyForName(eCtrl.DrawingControlFontFamily);
Font font = new Font(family,eCtrl.DrawingControlFontPoints,style);
Color fillColor = Color.FromArgb(eCtrl.DrawingControlFillColor);
Color strokeColor = Color.FromArgb(eCtrl.DrawingControlStrokeColor);
Color textColor = Color.FromArgb(eCtrl.DrawingControlTextColor);
switch (eCtrl.DrawingControlType)
{
case (byte)EDrawingControlType.Arrow:
EArrow eArrow = new EArrow();
eArrow.LoadForDrawingControl((Guid)eCtrl.ID);
Arrow arrow = new Arrow(
new PointF((float)eArrow.ArrowStartX, (float)eArrow.ArrowStartY),
new PointF((float)eArrow.ArrowEndX, (float)eArrow.ArrowEndY),
eArrow.ArrowHeadCount,
eArrow.ArrowShaftWidth,
eArrow.ArrowBarb,
eArrow.ArrowTip,
eCtrl.DrawingControlStroke,
eCtrl.DrawingControlText,
eCtrl.DrawingControlHasText,
fillColor,
textColor,
strokeColor,
eCtrl.DrawingControlHasTranspBackground,
font);
pnlDrawingPanel.Controls.Add(arrow);
arrow.StateChange +=
new DrawingControl.SelectStateChangedEventHandler(AnyDwgControlSelectedStateChanged);
arrow.KeyDown += new KeyEventHandler(AnyDwgControlKeyDown);
break;
case (byte)EDrawingControlType.Notation:
ENotation eNotation = new ENotation();
eNotation.LoadForDrawingControl((Guid)eCtrl.ID);
Notation notation = new Notation(
new Point(eNotation.NotationLeft, eNotation.NotationTop),
new Size(eNotation.NotationWidth, eNotation.NotationHeight),
eCtrl.DrawingControlStroke,
eCtrl.DrawingControlText,
fillColor,
textColor,
strokeColor,
eCtrl.DrawingControlHasTranspBackground,
font);
pnlDrawingPanel.Controls.Add(notation);
notation.StateChange +=
new DrawingControl.SelectStateChangedEventHandler(AnyDwgControlSelectedStateChanged);
notation.KeyDown += new KeyEventHandler(AnyDwgControlKeyDown);
break;
case (byte)EDrawingControlType.Boundary:
EBoundary eBoundary = new EBoundary();
eBoundary.LoadForDrawingControl((Guid)eCtrl.ID);
PointF[] boundaryPts = EBoundaryPoint.GetArrayByIndexForBoundary((Guid)eBoundary.ID);
Boundary boundary = new Boundary(
boundaryPts,
eCtrl.DrawingControlStroke,
eCtrl.DrawingControlText,
eCtrl.DrawingControlHasText,
fillColor,
textColor,
strokeColor,
font,
eBoundary.BoundaryAlpha);
pnlDrawingPanel.Controls.Add(boundary);
boundary.StateChange +=
new DrawingControl.SelectStateChangedEventHandler(AnyDwgControlSelectedStateChanged);
boundary.KeyDown += new KeyEventHandler(AnyDwgControlKeyDown);
break;
default:
break;
}
}
}
// **************************************************************
// PROPERTIES (Should they really be public?)
// **************************************************************
// Current User Interface Mode Property
public UiMode CurrentUiMode
{
get { return currentUiMode; }
set
{
if (currentUiMode != value)
{
// the ui mode changed
currentUiMode = value;
switch (value)
{
// the mode changed to Select Mode.
// so toggle the button checked states and update the status bar label.
case UiMode.SelectMode:
tsbDraw.Checked = false;
tsbSelect.Checked = true;
lblCurrentMode.Text = "Select Mode";
// Also set the the textbox text to match that of the selected item
// if there is one or clear it if not.
DrawingControl dc = getSelectedDrawingControl();
txtDrawingControlText.Text = ((dc != null && dc.HasText) ? dc.Text : "");
break;
// the mode changed to Draw Mode.
// so toggle the button checked states and update the status bar label.
case UiMode.DrawMode:
tsbDraw.Checked = true;
tsbSelect.Checked = false;
lblCurrentMode.Text = "Drawing Mode";
// Also make sure no drawing objects are selected
deselectAllDrawingControls();
break;
default:
break;
}
// Enable or disable the textbox based on the mode and current tool or
// selected DrawingObject.
DisEnableTextbox();
}
}
}
// Current Drawing tool property
public DrawingTool CurrentDrawingTool
{
get { return currentDrawingTool; }
set
{
if (currentDrawingTool != value)
{
currentDrawingTool = value;
}
// Any time the user accesses the drawing tools, ensure that no control is selected,
// Set the textbox text to the default text for the chosen tool, and
// disable the textbox. We don't allow edits until after it's drawn.
deselectAllDrawingControls();
SetDefaultText(currentDrawingTool);
DisEnableTextbox();
// We don't do anything with the font here, because fonts are handled differently.
// There are no default fonts assigned to specific tools,
// just a current control font and a current default font.
}
}
// **************************************************************
// GENERAL USER INTERFACE EVENT HANDLERS
// **************************************************************
// Handle the user clicking on the drawing panel
private void pnlDrawingPanel_MouseClick(object sender, MouseEventArgs e)
{
DrawingControl dc;
if (CurrentUiMode == UiMode.SelectMode)
{
// If we're in Select mode, clicking on the form deselects any selected item
// and clears the textbox text.
deselectAllDrawingControls();
txtDrawingControlText.Text = "";
}
else if (CurrentUiMode == UiMode.DrawMode)
{
// If we're in Drawing mode, clicking on the form draws a new DrawingControl
// of the CurrentDrawingTool type.
// Set up the default colors for the control of the CurrentDrawingTool type.
Color fillColor, textColor, strokeColor;
switch (CurrentDrawingTool)
{
case DrawingTool.DoubleBlackArrowSm:
fillColor = Color.Black;
textColor = Color.Black;
strokeColor = Color.Black;
break;
case DrawingTool.HeadlessBlackArrowSm:
fillColor = Color.Black;
textColor = Color.Black;
strokeColor = Color.Black;
break;
case DrawingTool.SimpleBlackArrow:
fillColor = Color.Black;
textColor = Color.Black;
strokeColor = Color.Black;
break;
case DrawingTool.SimpleBlackArrowSm:
fillColor = Color.Black;
textColor = Color.Black;
strokeColor = Color.Black;
break;
case DrawingTool.YellowTextArrow:
fillColor = Color.Yellow;
textColor = Color.Red;
strokeColor = Color.Black;
break;
case DrawingTool.Notation:
fillColor = Color.White;
textColor = Color.Black;
strokeColor = Color.Black;
break;
case DrawingTool.Region:
fillColor = Color.AliceBlue;
textColor = Color.Black;
strokeColor = Color.Black;
break;
default:
throw new Exception("Unknown drawing tool");
}
// Create the new DrawingControl
switch (CurrentDrawingTool)
{
case DrawingTool.SimpleBlackArrow:
dc = new Arrow(new PointF(e.X, e.Y), 1, 6, 4, 14, 1, "", false,
fillColor, textColor, strokeColor, false, defaultFont);
break;
case DrawingTool.DoubleBlackArrowSm:
dc = new Arrow(new PointF(e.X, e.Y),2, 2, 2, 10, 1, "", false,
fillColor, textColor, strokeColor, false, defaultFont);
break;
case DrawingTool.SimpleBlackArrowSm:
dc = new Arrow(new PointF(e.X, e.Y), 1, 2, 2, 10, 1, "", false,
fillColor, textColor, strokeColor, false, defaultFont);
break;
case DrawingTool.HeadlessBlackArrowSm:
dc = new Arrow(new PointF(e.X, e.Y),0, 2, 0 , 0, 1, "", false,
fillColor, textColor, strokeColor, false, defaultFont);
break;
case DrawingTool.YellowTextArrow:
dc = new Arrow(new PointF(e.X, e.Y),1, 20, 6, 15, 1, txtDrawingControlText.Text, true,
fillColor, textColor, strokeColor, false, defaultFont);
break;
case DrawingTool.Notation:
dc = new Notation(new Point(e.X, e.Y), 1, txtDrawingControlText.Text,
fillColor, textColor, strokeColor, tsbTransparent.Checked, defaultFont);
break;
case DrawingTool.Region:
dc = new Boundary(new Point(e.X, e.Y), new Size(50,50),12,1,"",false,fillColor,textColor,strokeColor,defaultFont,150);
break;
default:
throw new Exception("Unknown drawing tool");
}
// Add the new drawing control to the panel.
pnlDrawingPanel.Controls.Add(dc);
dc.BringToFront();
// Set to receive selection state change events raised by the new DrawingControl
dc.StateChange +=
new DrawingControl.SelectStateChangedEventHandler(AnyDwgControlSelectedStateChanged);
dc.KeyDown += new KeyEventHandler(AnyDwgControlKeyDown);
// Set the new drawing control's state to selected and the mode to select mode
// so the user can edit if desired.
dc.IsSelected = true;
CurrentUiMode = UiMode.SelectMode;
}
else throw new Exception("Unknown User Interface Mode");
// Enable the textbox only if we've just created a DrawingControl that has text
DisEnableTextbox();
}
// Handle a selected state change of any drawing control
private void AnyDwgControlSelectedStateChanged(object sender, EventArgs e)
{
DrawingControl dc = (DrawingControl)sender;
if (dc.IsSelected)
{
// Deselect all the other drawing controls. Only allow selecting one at a time.
deselectAllDrawingControlsExcept(dc);
// Change the textbox text to match that of the newly selected control
txtDrawingControlText.Text = (dc.HasText ? dc.Text : "");
// Set the state of the Transparent background button to match
// the setting of the newly selected control.
if (dc is Boundary)
{
tsbTransparent.Checked = false;
tsbTransparent.ToolTipText = "Set Background Opacity";
}
else
{
tsbTransparent.Checked = dc.HasTransparentBackground;
tsbTransparent.ToolTipText = tsbTransparent.Checked ? "Show Background" : "Hide Background";
}
// Let the user know that the font button is now affecting just the selected item.
tsbFont.ToolTipText = "Set font for item";
// Enable the textbox if the selected control has text
DisEnableTextbox();
// Enable the Z-order buttons if we have more than one control
if (pnlDrawingPanel.Controls.Count > 1) DisEnableZButtons(true);
// Enable the buttons that require a selection (e.g. color btns, delete btn)
DisEnableSelectedItemButtons(true, dc.HasText);
// Enable the font button if and only if the selected control has text.
tsbFont.Enabled = dc.HasText;
// Set the current mode to Select mode.
// If we were in drawing mode and clicked on an existing control
// instead of drawing on the form, we should go back to Select mode
CurrentUiMode = UiMode.SelectMode;
}
}
// Pass on textbox text changes to the selected control
private void txtDrawingControlText_TextChanged(object sender, EventArgs e)
{
DrawingControl dc = getSelectedDrawingControl();
if (dc != null)
{
dc.Text = txtDrawingControlText.Text;
dc.Invalidate();
}
}
// Handle the user pressing the 'Delete' key.
void AnyDwgControlKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete) DeleteSelectedControl();
}
// **************************************************************
// TOOLBAR EVENT HANDLERS
// **************************************************************
// Handle the user clicking to select a new background image.
private void tsbGetBackgroundImage_Click(object sender, EventArgs e)
{
Bitmap backImage;
if (curGraphic.GraphicBgImageFileName != null)
{
FileInfo fi = new FileInfo(curGraphic.GraphicBgImageFileName);
openFileDialog1.FileName = fi.Name;
openFileDialog1.InitialDirectory = fi.DirectoryName;
}
else
{
openFileDialog1.FileName = "";
openFileDialog1.InitialDirectory = Globals.ImageFolder;
}
// Todo: what file types should we allow?
openFileDialog1.Filter = "Image Files *.jpg, *.gif, *.png, *.bmp|*.jpg;*.gif;*.png;*.bmp";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// Dispose of the previous background image if there was any, otherwise that file will be
// locked to the user until such time as garbage disposal gets around to its job.
if (pnlDrawingPanel.BackgroundImage != null) pnlDrawingPanel.BackgroundImage.Dispose();
curGraphic.GraphicBgImageFileName = openFileDialog1.FileName;
backImage = (Bitmap)Image.FromFile(openFileDialog1.FileName);
// free up the image file.
backImage = GetImageDeepClone(backImage);
pnlDrawingPanel.BackgroundImage = backImage;
if (pnlDrawingPanel.BackgroundImage.Height > pnlDrawingPanel.BackgroundImage.Width)
MessageBox.Show("The selected background image is in portrait mode. To avoid distortion, it must be cropped or rotated." +
"\r\nPlease close the Graphic Editor before making adjustments to the image file.","Factotum: Background Image In Portrait Mode");
}
curGraphic.GraphicBgImageType = (byte)BackgroundImageFileType.Jpeg;
if (curGraphic.GraphicBgImageFileName != null) btnSaveGraphic.Enabled = true;
// Clear these flag if it was set, since a new image has now been selected
isImageAtDefaultPath = false;
isImageNotFound = false;
}
// Handle user click on the select mode button
private void tsbSelect_Click(object sender, EventArgs e)
{
CurrentUiMode = UiMode.SelectMode;
}
// Handle user click on the draw mode button
private void tsbDraw_Click(object sender, EventArgs e)
{
CurrentUiMode = UiMode.DrawMode;
// Set the textbox text to the default text for the current tool
SetDefaultText(CurrentDrawingTool);
}
// If the user clicks to select any tool, switch to draw mode
private void tsbToolSelector_Click(object sender, EventArgs e)
{
CurrentUiMode = UiMode.DrawMode;
}
// Handle user selecting a drawing tool
private void tsbToolSelector_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
// Change the selector's image to the currently selected image
tsbToolSelector.Image = e.ClickedItem.Image;
// Set the current tool to the selected item
switch (e.ClickedItem.Name)
{
case "miDoubleBlackArrowSm":
CurrentDrawingTool = DrawingTool.DoubleBlackArrowSm;
break;
case "miHeadlessBlackArrowSm":
CurrentDrawingTool = DrawingTool.HeadlessBlackArrowSm;
break;
case "miSimpleBlackArrow":
CurrentDrawingTool = DrawingTool.SimpleBlackArrow;
break;
case "miSimpleBlackArrowSm":
CurrentDrawingTool = DrawingTool.SimpleBlackArrowSm;
break;
case "miYellowTextArrow":
CurrentDrawingTool = DrawingTool.YellowTextArrow;
break;
case "miNotation":
CurrentDrawingTool = DrawingTool.Notation;
break;
case "miRegion":
CurrentDrawingTool = DrawingTool.Region;
break;
default:
throw new Exception("Invalid drop-down menu item name");
}
}
// If the user clicks to toggle the background transparency, do so.
private void tsbTransparent_Click(object sender, EventArgs e)
{
DrawingControl dc = getSelectedDrawingControl();
System.Diagnostics.Debug.Assert(dc != null);
if (dc is Boundary)
{
Boundary b = (Boundary)dc;
TransparencySelector ts = new TransparencySelector();
ts.AlphaLevel = b.AlphaLevel;
ts.ShowDialog();
if (ts.DialogResult == DialogResult.OK)
{
b.AlphaLevel = ts.AlphaLevel;
}
// Force it back to unchecked.
tsbTransparent.Checked = false;
}
else
{
dc.HasTransparentBackground = tsbTransparent.Checked;
// Change the tool tip appropriately
tsbTransparent.ToolTipText = tsbTransparent.Checked ? "Show Background" : "Hide Background";
}
dc.Invalidate();
}
// If the user clicks to select a fill color, show a dialog to get a new color
private void tsbFillColor_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.Assert(CurrentUiMode == UiMode.SelectMode);
DrawingControl dc = getSelectedDrawingControl();
System.Diagnostics.Debug.Assert(dc != null);
// Initialize the dialog color to the user's selected color
colorDialog1.Color = dc.FillColor;
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
dc.FillColor = colorDialog1.Color;
dc.Invalidate();
}
}
// If the user clicks to select a stroke color, show a dialog to get a new color
private void tsbStrokeColor_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.Assert(CurrentUiMode == UiMode.SelectMode);
DrawingControl dc = getSelectedDrawingControl();
System.Diagnostics.Debug.Assert(dc != null);
// Initialize the dialog color to the user's selected color
colorDialog1.Color = dc.StrokeColor;
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
dc.StrokeColor = colorDialog1.Color;
dc.Invalidate();
}
}
// If the user clicks to select a text color, show a dialog to get a new color
private void tsbTextColor_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.Assert(CurrentUiMode == UiMode.SelectMode);
DrawingControl dc = getSelectedDrawingControl();
System.Diagnostics.Debug.Assert(dc != null);
// Initialize the dialog color to the user's selected color
colorDialog1.Color = dc.TextColor;
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
dc.TextColor = colorDialog1.Color;
dc.Invalidate();
}
}
// Handle the user clicking to change font.
private void tsbFont_Click(object sender, EventArgs e)
{
DrawingControl dc = getSelectedDrawingControl();
// If there's a drawing control selected, we're just changing its font
// Otherwise, we're changing the default font for new drawing controls.
// Initialize the font dialog to the current font and disallow script change
// just because it seems unnecessarily complicated.
fontDialog1.Font = (dc == null ? defaultFont : dc.Font);
fontDialog1.AllowScriptChange = false;
if (fontDialog1.ShowDialog() == DialogResult.OK)
{
if (dc != null)
{
// There was a control selected, so set its font
dc.Font = fontDialog1.Font;
dc.Invalidate();
}
else
{
// No control selected, so change the default font
defaultFont = fontDialog1.Font;
if (existDrawingControlsWithText())
{
// If there are existing controls with text check whether or not the user
// wants to update them to the new font.
if (MessageBox.Show("Update existing drawing elements to this new default font?", "Factotum: Setting New Default Font",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (DrawingControl d in pnlDrawingPanel.Controls)
{
d.Font = defaultFont;
d.Invalidate();
}
}
}
}
}
}
// If the user clicks to bring the selected item to the front, do so.
private void tsbBringToFront_Click(object sender, EventArgs e)
{
DrawingControl dc = getSelectedDrawingControl();
System.Diagnostics.Debug.Assert(dc != null);
dc.BringToFront();
}
// If the user clicks to send the selected item to the back, do so.
private void tsbSendToBack_Click(object sender, EventArgs e)
{
DrawingControl dc = getSelectedDrawingControl();
System.Diagnostics.Debug.Assert(dc != null);
dc.SendToBack();
}
// Handle the user clicking the delete button
private void tsbDelete_Click(object sender, EventArgs e)
{
DeleteSelectedControl();
}
// **************************************************************
// UTILITY FUNCTIONS
// **************************************************************
// Set the textbox text to the default text for the current tool
private void SetDefaultText(DrawingTool dt)
{
switch (dt)
{
case DrawingTool.DoubleBlackArrowSm:
case DrawingTool.HeadlessBlackArrowSm:
case DrawingTool.SimpleBlackArrow:
case DrawingTool.SimpleBlackArrowSm:
case DrawingTool.Region:
txtDrawingControlText.Text = "";
break;
case DrawingTool.YellowTextArrow:
txtDrawingControlText.Text = "FLOW";
break;
case DrawingTool.Notation:
txtDrawingControlText.Text = "ENTER TEXT";
break;
default:
throw new Exception("Invalid drop-down menu item name");
}
}
// Check if we have any drawing controls that have text.
private bool existDrawingControlsWithText()
{
foreach (DrawingControl d in pnlDrawingPanel.Controls)
if (d.HasText) return true;
return false;
}
// Delete the selected control, if there is one.
private void DeleteSelectedControl()
{
DrawingControl dc = getSelectedDrawingControl();
if (dc != null)
{
pnlDrawingPanel.Controls.Remove(dc);
dc.Dispose();
// After we delete, there won't be any selected items
DisEnableSelectedItemButtons(false);
DisEnableZButtons(false);
tsbFont.ToolTipText = "Set default font";
// After we delete, there won't be any selected text
txtDrawingControlText.Text = "";
DisEnableTextbox();
}
}
// De-select all the drawing controls except the specified one.
private void deselectAllDrawingControlsExcept(Control ctl)
{
foreach (DrawingControl c in pnlDrawingPanel.Controls)
if (!c.Equals(ctl)) c.IsSelected = false;
}
// De-select all the drawing controls.
private void deselectAllDrawingControls()
{
foreach (DrawingControl c in pnlDrawingPanel.Controls)
c.IsSelected = false;
// Since there is no longer a selected control, disable some buttons
DisEnableSelectedItemButtons(false);
DisEnableZButtons(false);
// Let the user know that the font button now sets the default font
// and make sure it's enabled.
tsbFont.ToolTipText = "Set default font";
tsbFont.Enabled = true;
}
// Handle enabling and disabling of buttons that should only be enabled if there is
// a drawing control selected.
private void DisEnableSelectedItemButtons(bool status)
{
tsbDelete.Enabled = status;
tsbFillColor.Enabled = status;
tsbStrokeColor.Enabled = status;
tsbTransparent.Enabled = status;
tsbTextColor.Enabled = status;
}
// Handle default enabling and disabling of buttons that need a drawing control selected.
// Then handle the special case of the text color button.
private void DisEnableSelectedItemButtons(bool status, bool hasText)
{
DisEnableSelectedItemButtons(status);
tsbTextColor.Enabled = status && hasText;
}
// Handle enabling and disabling of the bringToFront and SendToBack buttons
// These should only be enabled if there is a drawing control selected
// AND there are at least two drawing controls in the container
private void DisEnableZButtons(bool status)
{
tsbBringToFront.Enabled = status;
tsbSendToBack.Enabled = status;
}
// Handle enabling and disabling of the textbox
private void DisEnableTextbox()
{
if (CurrentUiMode == UiMode.SelectMode)
{
// If we're in select mode and a drawing control is selected,
// enable the textbox if the control has text.
DrawingControl dc = getSelectedDrawingControl();
if (dc != null) txtDrawingControlText.Enabled = (dc.HasText);
// If no drawing controls are selected, disable the textbox.
else txtDrawingControlText.Enabled = false;
}
// If we're in drawing mode, disable the textbox.
else txtDrawingControlText.Enabled = false;
}
// Return the selected drawing control or null if none are selected.
private DrawingControl getSelectedDrawingControl()
{
foreach (DrawingControl dc in pnlDrawingPanel.Controls)
if (dc.IsSelected) return dc;
return null;
}
private void tsbPrint_Click(object sender, EventArgs e)
{
//CaptureScreen();
//printDocument1.Print();
}
private Bitmap graphicImage;
#if false
private void CaptureScreen()
{
graphicImage = new Bitmap(pnlDrawingPanel.Width, pnlDrawingPanel.Height);
pnlDrawingPanel.DrawToBitmap(graphicImage,
new Rectangle(0, 0, pnlDrawingPanel.Width, pnlDrawingPanel.Height));
}
#endif
// This function creates a graphics from the background image and then paints each control
// into it in the correct sequence. This way the transparency is always handled correctly
// without the controls needing to be aware of each other.
// If we are called with 'forStoring' true, we double the width and height of the image and
// paint the controls at twice their actual size. This gives us high enough density of
// graphical data for the printed image to look reasonably good.
private Image CaptureScreen(bool forStoring)
{
Graphics g;
if (forStoring)
{
Size sz = new Size(pnlDrawingPanel.DisplayRectangle.Width * 2,
pnlDrawingPanel.DisplayRectangle.Height * 2);
graphicImage = new Bitmap(pnlDrawingPanel.BackgroundImage, sz);
g = Graphics.FromImage(graphicImage);
g.PageUnit = GraphicsUnit.Pixel;
g.PageScale = 2.0F;
}
else
{
Size sz = new Size(pnlDrawingPanel.DisplayRectangle.Width,
pnlDrawingPanel.DisplayRectangle.Height);
graphicImage = new Bitmap(pnlDrawingPanel.BackgroundImage, sz);
g = Graphics.FromImage(graphicImage);
}
int ctrlCount = pnlDrawingPanel.Controls.Count;
for (int i = ctrlCount - 1; i>=0; i-- )
{
DrawingControl d = (DrawingControl)pnlDrawingPanel.Controls[i];
g.TranslateTransform(d.Left, d.Top);
d.PaintGraphics(g,forStoring?2.0F:1.0F);
g.TranslateTransform(-d.Left, -d.Top);
}
g.Dispose();
//graphicImage.Save(@"c:\test1.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
return graphicImage;
}
//private void printDocument1_PrintPage(Object sender, PrintPageEventArgs e)
//{
// int x = e.MarginBounds.Left;
// int y = e.MarginBounds.Top;
// e.Graphics.DrawString("Hello World",
// Font,new SolidBrush(Color.Black),
// new PointF(x,y));
// y += 15;
// e.Graphics.DrawImage(graphicImage, new Point(x, y));
//}
private void previewToolStripButton_Click(object sender, EventArgs e)
{
if (pnlDrawingPanel.BackgroundImage == null)
{
MessageBox.Show("A background image must be set before the graphic can be previewed", "Factotum");
return;
}
deselectAllDrawingControls();
PreviewGraphic pv = new PreviewGraphic();
pv.SetPreviewImage(CaptureScreen(false));
pv.ShowDialog();
}
private void tsbExport_Click(object sender, EventArgs e)
{
if (pnlDrawingPanel.BackgroundImage == null)
{
MessageBox.Show("A background image must be set before the graphic can be exported","Factotum");
return;
}
deselectAllDrawingControls();
Image img = CaptureScreen(true);
saveFileDialog1.Filter = "Jpeg Files|*.jpg";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
img.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
private void btnSaveGraphic_Click(object sender, EventArgs e)
{
int i = 0;
deselectAllDrawingControls();
if (isImageNotFound)
{
if (MessageBox.Show("Are you sure that you want to save the current graphic? If so, the original background image file name will be lost!",
"Factotum", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes) return;
}
if (isImageAtDefaultPath)
{
if (MessageBox.Show("Would you like to update the location of the background image to the current Default Image Folder?",
"Factotum", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
{
curGraphic.GraphicBgImageFileName = SubstituteDefaultImagePath(curGraphic.GraphicBgImageFileName);
}
}
curGraphic.GraphicImage = CaptureScreen(true);
curGraphic.Save();
EDrawingControl.DeleteAllForGraphic((Guid)curGraphic.ID);
foreach (DrawingControl dctl in pnlDrawingPanel.Controls)
{
EDrawingControl eDrawingControl = new EDrawingControl();
eDrawingControl.DrawingControlGphID = curGraphic.ID;
eDrawingControl.DrawingControlFillColor = dctl.FillColor.ToArgb();
eDrawingControl.DrawingControlFontFamily = dctl.Font.FontFamily.Name;
eDrawingControl.DrawingControlFontIsBold = dctl.Font.Bold;
eDrawingControl.DrawingControlFontIsItalic = dctl.Font.Italic;
eDrawingControl.DrawingControlFontIsUnderlined = dctl.Font.Underline;
eDrawingControl.DrawingControlFontPoints = dctl.Font.SizeInPoints;
eDrawingControl.DrawingControlHasFill = dctl.HasFill;
eDrawingControl.DrawingControlHasStroke = dctl.HasStroke;
eDrawingControl.DrawingControlHasText = dctl.HasText;
eDrawingControl.DrawingControlHasTranspBackground = dctl.HasTransparentBackground;
eDrawingControl.DrawingControlStroke = (int)dctl.Stroke;
eDrawingControl.DrawingControlStrokeColor = dctl.StrokeColor.ToArgb();
eDrawingControl.DrawingControlText = dctl.Text;
eDrawingControl.DrawingControlTextColor = dctl.TextColor.ToArgb();
eDrawingControl.DrawingControlZindex = i;
if (dctl is Arrow)
eDrawingControl.DrawingControlType = (byte)EDrawingControlType.Arrow;
else if (dctl is Notation)
eDrawingControl.DrawingControlType = (byte)EDrawingControlType.Notation;
else if (dctl is Boundary)
eDrawingControl.DrawingControlType = (byte)EDrawingControlType.Boundary;
else
throw new Exception("Unexpected drawing control type");
Guid? drawingControlID = eDrawingControl.Save();
if (drawingControlID == null)
{
MessageBox.Show("Unable to save graphic. Contact support.", "Factotum");
}
if (dctl is Arrow)
{
Arrow arrow = (Arrow)dctl;
EArrow eArrow = new EArrow();
eArrow.ArrowBarb = (int)arrow.Barb;
eArrow.ArrowDctID = drawingControlID;
eArrow.ArrowEndX = (int)arrow.GEndPoint.X;
eArrow.ArrowEndY = (int)arrow.GEndPoint.Y;
eArrow.ArrowHeadCount = (byte)arrow.HeadCount;
eArrow.ArrowShaftWidth = (int)arrow.ShaftWidth;
eArrow.ArrowStartX = (int)arrow.GStartPoint.X;
eArrow.ArrowStartY = (int)arrow.GStartPoint.Y;
eArrow.ArrowTip = (int)arrow.Tip;
eArrow.Save();
}
else if (dctl is Notation)
{
Notation notation = (Notation)dctl;
ENotation eNotation = new ENotation();
eNotation.NotationDctID = drawingControlID;
eNotation.NotationHeight = notation.Height;
eNotation.NotationLeft = notation.Left;
eNotation.NotationTop = notation.Top;
eNotation.NotationWidth = notation.Width;
eNotation.Save();
}
else if (dctl is Boundary)
{
Boundary boundary = (Boundary)dctl;
EBoundary eBoundary = new EBoundary();
eBoundary.BoundaryAlpha = (byte)boundary.AlphaLevel;
eBoundary.BoundaryDctID = drawingControlID;
Guid? boundaryID = eBoundary.Save();
if (boundaryID == null)
{
MessageBox.Show("Unable to save graphic. Please contact support.", "Factotum");
}
EBoundaryPoint.SaveForBoundaryFromArray((Guid)boundaryID, boundary.GBoundaryPoints);
}
i++;
}
DialogResult = DialogResult.OK;
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void GraphicEdit_FormClosing(object sender, FormClosingEventArgs e)
{
// Free up the background image file in case the user wants to edit it.
if (pnlDrawingPanel.BackgroundImage != null)
pnlDrawingPanel.BackgroundImage = 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.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
using System.Linq;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public abstract partial class DecryptTests
{
private bool _useExplicitPrivateKey;
public static bool SupportsIndefiniteLengthEncoding { get; } = !PlatformDetection.IsFullFramework;
public DecryptTests(bool useExplicitPrivateKey)
{
_useExplicitPrivateKey = useExplicitPrivateKey;
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_IssuerAndSerial()
{
byte[] content = { 5, 112, 233, 43 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_Ski()
{
byte[] content = { 6, 3, 128, 33, 44 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.SubjectKeyIdentifier);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_Capi()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_256()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha256KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_384()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha384KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_512()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha512KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_FixedValue()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
byte[] message = (
"3082012506092A864886F70D010703A0820116308201120201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77196303C06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B48010B78CDFECFF32A8" +
"E86D448989382A93E7"
).HexToByteArray();
VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content));
}
[Fact]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_NoData_FixedValue()
{
// This is the Decrypt_512_FixedData test re-encoded to remove the
// encryptedContentInfo.encryptedContent optional value.
byte[] content = Array.Empty<byte>();
byte[] message = (
"3082011306092A864886F70D010703A0820104308201000201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77196302A06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B4"
).HexToByteArray();
if (PlatformDetection.IsFullFramework)
{
// On NetFx when Array.Empty should be returned an array of 6 zeros is
// returned instead.
content = new byte[6];
}
VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content));
}
[Fact]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_CekDoesNotDecrypt_FixedValue()
{
// This is the Decrypt_512_NoData_FixedValue test except that the last
// byte of the recipient encrypted key has been changed from 0x96 to 0x95
// (the sequence 7195 identifies the changed byte)
byte[] content = Array.Empty<byte>();
byte[] message = (
"3082011306092A864886F70D010703A0820104308201000201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77195302A06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B4"
).HexToByteArray();
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content)));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_SignedWithinEnveloped()
{
byte[] content =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_EnvelopedWithinEnveloped()
{
byte[] content =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818013"
+ "dc0eb2984a445d04a1f6246b8fe41f1d24507548d449d454d5bb5e0638d75ed101bf78c0155a5d208eb746755fbccbc86923"
+ "8443760a9ae94770d6373e0197be23a6a891f0c522ca96b3e8008bf23547474b7e24e7f32e8134df3862d84f4dea2470548e"
+ "c774dd74f149a56cdd966e141122900d00ad9d10ea1848541294a1302b06092a864886f70d010701301406082a864886f70d"
+ "030704089c8119f6cf6b174c8008bcea3a10d0737eb9").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7SignedEnveloped), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
public void EncryptToNegativeSerialNumber()
{
CertLoader negativeSerial = Certificates.NegativeSerialNumber;
const string expectedSerial = "FD319CB1514B06AF49E00522277E43C8";
byte[] content = { 1, 2, 3 };
ContentInfo contentInfo = new ContentInfo(content);
EnvelopedCms cms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = negativeSerial.GetCertificate())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
cms.Encrypt(recipient);
}
EnvelopedCms cms2 = new EnvelopedCms();
cms2.Decode(cms.Encode());
RecipientInfoCollection recipients = cms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, recipientInfo.RecipientIdentifier.Type);
X509IssuerSerial issuerSerial = (X509IssuerSerial)recipientInfo.RecipientIdentifier.Value;
Assert.Equal(expectedSerial, issuerSerial.SerialNumber);
using (X509Certificate2 cert = negativeSerial.TryGetCertificateWithPrivateKey())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
cms2.Decrypt(new X509Certificate2Collection(cert));
}
Assert.Equal(content, cms2.ContentInfo.Content);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes128_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm is Aes128
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D0101073000048180862175CD3B2932235A67C6A025F75CDA1A43B53E785370895BA9AC8D0DD"
+ "318EB36DFAE275B16ABD497FEBBFCF2D4B3F38C75B91DC40941A2CC1F7F47E701EEA2D5A770C485565F8726"
+ "DC0D59DDE17AA6DB0F9384C919FC8BC6CB561A980A9AE6095486FDF9F52249FB466B3676E4AEFE4035C15DC"
+ "EE769F25E4660D4BE664E7F303C06092A864886F70D010701301D060960864801650304010204100A068EE9"
+ "03E085EA5A03D1D8B4B73DD88010740E5DE9B798AA062B449F104D0F5D35").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes192_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes192
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D010107300004818029B82454B4C301F277D7872A14695A41ED24FD37AC4C9942F9EE96774E0"
+ "C6ACC18E756993A38AB215E5702CD34F244E52402DA432E8B79DF748405135E8A6D8CB78D88D9E4C142565C"
+ "06F9FAFB32F5A9A4074E10FCCB0758A708CA758C12A17A4961969FCB3B2A6E6C9EB49F5E688D107E1B1DF3D"
+ "531BC684B944FCE6BD4550C303C06092A864886F70D010701301D06096086480165030401160410FD7CBBF5"
+ "6101854387E584C1B6EF3B08801034BD11C68228CB683E0A43AB5D27A8A4").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D01010730000481800215BF7505BCD5D083F8EFDA01A4F91D61DE3967779B2F5E4360593D4CB"
+ "96474E36198531A5E20E417B04C5C7E3263C3301DF8FA888FFBECC796500D382858379059C986285AFD605C"
+ "B5DE125487CCA658DF261C836720E2E14440DA60E2F12D6D5E3992A0DB59973929DF6FC23D8E891F97CA956"
+ "2A7AD160B502FA3C10477AA303C06092A864886F70D010701301D060960864801650304012A04101287FE80"
+ "93F3C517AE86AFB95E599D7E80101823D88F47191857BE0743C4C730E39E").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleTripleDes_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is 3DES-CBC
byte[] encryptedMessage =
("3082010C06092A864886F70D010703A081FE3081FB0201003181C83081C5020100302E301A3118301606035"
+ "50403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A86"
+ "4886F70D0101010500048180062F6F16637C8F35B73924AD85BA47D99DBB4800CB8F0C4094F6896050B7C1F"
+ "11CE79BEE55A638EAAE70F2C32C01FC24B8D09D9D574CB7373788C8BC3A4748124154338C74B644A2A11750"
+ "9E97D1B3535FAE70E4E7C8F2F866232CBFC6448E89CF9D72B948EDCF9C9FC9C153BCC7104680282A4BBBC1E"
+ "E367F094F627EE45FCD302B06092A864886F70D010701301406082A864886F70D030704081E3F12D42E4041"
+ "58800877A4A100165DD0F2").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_Ski()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type SubjectKeyIdentifier. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082010306092A864886F70D010703A081F53081F20201023181AE3081AB0201028014F2008AA9FA3742E83"
+ "70CB1674CE1D1582921DCC3300D06092A864886F70D010101050004818055F258073615B95426A7021E1B30"
+ "9CFE8DD135B58D29F174B9FE19AE80CFC84621BCE3DBD63A5422AF30A6FAA3E2DFC05CB1AB5AB4FBA6C84EB"
+ "1C2E17D5BE5C4959DBE8F96BF1A9701F55B697843032EEC7AFEC58A36815168F017DCFD70C74AD05C48B5E4"
+ "D9DDEE409FDC9DC3326B6C5BA9F433A9E031FF9B09473176637F50303C06092A864886F70D010701301D060"
+ "960864801650304012A0410314DA87435ED110DFE4F52FA70CEF7B080104DDA6C617338DEBDD10913A9141B"
+ "EE52").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaTransferCapi()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransferCapi1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012306092A864886F70D010703A0820114308201100201003181CC3081C90201003032301E311C301A0"
+ "60355040313135253414B65795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA"
+ "300D06092A864886F70D01010730000481804F3F4A6707B329AB9A7343C62F20D5C1EAF4E74ECBB2DC66D1C"
+ "642FC4AA3E40FC4C13547C6C9F73D525EE2FE4147B2043B8FEBF8604C0E4091C657B48DFD83A322F0879580"
+ "FA002C9B27AD1FCF9B8AF24EDDA927BB6728D11530B3F96EBFC859ED6B9F7B009F992171FACB587A7D05E8B"
+ "467B3A1DACC08B2F3341413A7E96576303C06092A864886F70D010701301D060960864801650304012A0410"
+ "6F911E14D9D991DAB93C0B7738D1EC208010044264D201501735F73052FFCA4B2A95").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha256()
{
// Message encrypted on framework for a recipient using the certificate returned by
// Certificates.RSASha256KeyTransfer1.GetCertificate() and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613235364B65795472616E7366657231021072C6C7734916468C4D608253DA01"
+ "7676300D06092A864886F70D01010730000481805C32FA32EBDCFFC3595166EEDACFC9E9D60842105B581E1"
+ "8B85DE1409F4C999995637153480438530955EE4481A3B27B866FF4E106A525CDFFC6941BDD01EFECCC6CCC"
+ "82A3D7F743F7543AB20A61A7831FE4DFB24A1652B072B3758FE4B2588D3B94A29575B6422DC5EF52E432565"
+ "36CA25A11BB92817D61FEAFBDDDEC6EE331303C06092A864886F70D010701301D060960864801650304012A"
+ "041021D59FDB89C13A3EC3766EF32FB333D080105AE8DEB71DF50DD85F66FEA63C8113F4").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha256KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha384()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSASha384KeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613338344B65795472616E736665723102103C724FB7A0159A9345CAAC9E3DF5"
+ "F136300D06092A864886F70D010107300004818011C1B85914331C005EA89E30D00364821B29BC0C459A22D"
+ "917494A1092CDBDA2022792E46C5E88BAD0EE3FD4927B856722311F9B17934FB29CAB8FE595C2AB2B20096B"
+ "9E2FC6F9D7B92125F571CBFC945C892EE4764D9B63369350FD2DAEFE455B367F48E100CB461F112808E792A"
+ "8AA49B66C79E511508A877530BBAA896696303C06092A864886F70D010701301D060960864801650304012A"
+ "0410D653E25E06BFF2EEB0BED4A90D00FE2680106B7EF143912ABA5C24F5E2C151E59D7D").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha384KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha512()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSASha512KeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613531324B65795472616E736665723102102F5D9D58A5F41B844650AA233E68"
+ "F105300D06092A864886F70D01010730000481802156D42FF5ED2F0338302E7298EF79BA1D04E20E68B079D"
+ "B3239120E1FC03FEDA8B544F59142AACAFBC5E58205E8A0D124AAD17B5DCAA39BFC6BA634E820DE623BFDB6"
+ "582BC48AF1B3DEF6849A57D2033586AF01079D67C9AB3AA9F6B51754BCC479A19581D4045EBE23145370219"
+ "98ECB6F5E1BCF8D6BED6A75FE957A40077D303C06092A864886F70D010701301D060960864801650304012A"
+ "04100B696608E489E7C35914D0A3DB9EB27F80103D362181B54721FB2CB7CE461CB31030").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha512KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_ExplicitSki()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate()
// and of type SubjectKeyIdentifier. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082018806092A864886F70D010703A082017930820175020102318201303082012C020102801401952851C"
+ "55DB594B0C6167F5863C5B6B67AEFE6300D06092A864886F70D010101050004820100269EAF029262C87125"
+ "314DD3FB02302FA212EB3CC06F73DF1474382BBA2A92845F39FF5A7F5020482849C36B4BC6BC82F7AF0E2E3"
+ "9143548CC32B93B72EF0659C6895F77E6B5839962678532392185C9431658B34D1ABD31F64F4C4A9B348A77"
+ "56783D60244519ADDD33560405E9377A91617127C2EECF2BAE53AB930FC13AFD25723FB60DB763286EDF6F1"
+ "187D8124B6A569AA2BD19294A7D551A0D90F8436274690231520A2254C19EA9BF877FC99566059A29CDF503"
+ "6BEA1D517916BA2F20AC9F1D8F164B6E8ACDD52BA8B2650EBBCC2ED9103561E11AF422D10DF7405404195FA"
+ "EF79A1FDC680F3A3DC395E3E9C0B10394DF35AE134E6CB719E35152F8E5303C06092A864886F70D01070130"
+ "1D060960864801650304012A041085072D8771A2A2BB403E3236A7C60C2A80105C71A04E73C57FE75C1DEDD"
+ "94B57FD01").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer_ExplicitSki;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_Pkcs7Signed_GeneratedOnWindows()
{
byte[] expectedContent =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), expectedContent);
byte[] encodedMessage = Convert.FromBase64String(
"MIIERwYJKoZIhvcNAQcDoIIEODCCBDQCAQAxgcwwgckCAQAwMjAeMRwwGgYDVQQDExNSU0FLZXlU" +
"cmFuc2ZlckNhcGkxAhBdL//4Y7q8m008gKsXikzKMA0GCSqGSIb3DQEBAQUABIGAngdmU69zGsgJ" +
"mx+hXmTjlefr1oazKRK8VGOeqNMm++J3yHxwz68CLoN4FIEyS/HE3NQE6qb3M80HOpk5fmVVMw7Z" +
"3mrsZlPLOEjJIxEFqAC/JFEzvyE/BL+1OvwRoHpxHsAvZNlz5f9g18wQVE7X5TkkbOJV/6F2disK" +
"H0jik68wggNeBgkqhkiG9w0BBwIwHQYJYIZIAWUDBAEqBBDr3I8NYAnetX+2h9D/nVAggIIDMOlW" +
"7mDuuScuXhCXgZaPy0/zEWy/sYDzxhj1G1X2qBwhB7m6Ez6giibAEYwfRNYaOiVIitIJAUU9LSKg" +
"n0FL1o0eCcgvo04w+zoaBH8pFFk78kuR+T73kflz+O3Eno1pIFpy+2cz2B0QvQSC7lYikbZ4J+/C" +
"7F/uqRoK7sdafNdyUnKhDL+vvP6ToGf9C4g0TjoFEC2ycyJxIBh1F57pqjht6HMQcYm+/fQoBtkt" +
"NrvZxJPlBhbQad/9pSCd0G6NDoPnDuFAicaxGVa7yI2BbvGTCc6NSnbdCzv2EgvsI10Yko+XO4/i" +
"oPnk9pquZBzC3p61XRKbBDrd5RsbkvPDXUHJKD5NQ3W3z9Bnc3bjNyilgDSIB01dE4AcWzdg+RGb" +
"TA7iAbAQKp2zjxb/prmxw1mhO9g6OkDovSTqmQQt7MlHFYFcX9wH8yEe+huIechmiy7famofluJX" +
"vBIz4m3JozlodyNX0nu9QwW58WWcFu6OyoPjFhlB+tLIHUElq9/AAEgwwgfsAj6jEQaHiFG+CYSJ" +
"RjX9+DHFJXMDyzW+eJw8Z/mvbZzzKF553xlAGpfUHHq4CywTyVTHn4nu9HPOeFzoirj1lzFvqmQd" +
"Dgp3T8NOPrns9ZIUBmdNNs/vUxNZqEeN4d0nD5lBG4aZnjsxr4i25rR3Jpe3kKrFtJQ74efkRM37" +
"1ntz9HGiA95G41fuaMw7lgOOfTL+AENNvwRGRCAhinajvQLDkFEuX5ErTtmBxJWU3ZET46u/vRiK" +
"NiRteFiN0hLv1jy+RJK+d+B/QEH3FeVMm3Tz5ll2LfO2nn/QR51hth7qFsvtFpwQqkkhMac6dMf/" +
"bb62pZY15U3y2x5jSn+MZVrNbL4ZK/JO5JFomqKVRjLH1/IZ+kuFNaaTrKFWB4U2gxrMdcjMCZvx" +
"ylbuf01Ajxo74KhPY9sIRztG4BU8ZaE69Ke50wJTE3ulm+g6hzNECdQS/yjuA8AUReGRj2NH/U4M" +
"lEUiR/rMHB/Mq/Vj6lsRFEVxHJSzek6jvrQ4UzVgWGrH4KnP3Rca8CfBTQX79RcZPu+0kI3KI+4H" +
"0Q+UBbb72FHnWsw3uqPEyA==");
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_Pkcs7Signed_GeneratedOnLinux()
{
byte[] expectedContent =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), expectedContent);
byte[] encodedMessage = Convert.FromBase64String(
"MIIERwYJKoZIhvcNAQcDoIIEODCCBDQCAQAxgcwwgckCAQAwMjAeMRwwGgYDVQQDExNSU0FLZXlU" +
"cmFuc2ZlckNhcGkxAhBdL//4Y7q8m008gKsXikzKMA0GCSqGSIb3DQEBAQUABIGAfsH5F4ZlwIcH" +
"nzqn8sOn+ZwK884en7HZrQbgEfedy5ti0ituKn70yTDz4iuNJtpguukCfCAsOT/n3eQn+T6etIa9" +
"byRGQst3F6QtgjAzdb5P1N6c5Mpz1o6k0mbNP/f0FqAaNtuAOnYwlEMwWOz9x4eEYpOhhlc6agRG" +
"qWItNVgwggNeBgkqhkiG9w0BBwIwHQYJYIZIAWUDBAEqBBCA8qaTiT+6IkrO8Ks9WOBggIIDMIkr" +
"7OGlPd3CfzO2CfJA3Sis/1ulDm1ioMCS9V5kLHVx4GWDETORG/YTPA54luxJkvIdU5VwO86+QuXf" +
"rgaly38XHTLZv+RBxUwCaWI0pgvaykEki5CnDu4j9uRQxqz6iU5bY6SKxG3bwcnUzGhWFdQVcNJn" +
"xzuMEcbrix5zfqmoeqemaYyqVqgMPNOnc5kmMOqHrha76qMdbYOSpwx81zYwstBlg+S9+AgOMR+W" +
"qrV9aXJTovjiJEVHPEPJFx0v/wCthhXso51mSU091Cs8qVfvokzlzXcK2dPF5d8EdmZCcmHsoq35" +
"/DfAL4DkfKucwiP9W7rT1a2BmVMquFTMI+KXyDvNhMVasjhKq5eM2G+oUDc3kGa3akaPZ+hNEHA+" +
"BNAS7iIpRft2GMNfTqpkBqnS6pB0+SSf02/JVkcFuHXZ9oZJsvZRm8M1i4WdVauBJ34rInQBdhaO" +
"yaFDx69tBvolclYnMzvdHLiP2TZbiR6kM0vqD1DGjEHNDE+m/jxL7HXcNotW84J9CWlDnm9zaNhL" +
"sB4PJNiNjKhkAsO+2HaNWlEPrmgmWKvNi/Qyrz1qUryqz2/2HGrFDqmjTeEf1+yy35N3Pqv5uvAj" +
"f/ySihknnAh77nI0yOPy0Uto+hbO+xraeujrEifaII8izcz6UG6LHNPxOyscne7HNcqPSAFLsNFJ" +
"1oOlKO0SwhPkGQsk4W5tjVfvLvJiPNcL7SY/eof4vVsRRwX6Op5WUjhJIagY1Vij+4hOcn5TqdmU" +
"OZDh/FC3x4DI556BeMfbWxHNlGvptROQwQ6BasfdiVWCWzMHwLpz27Y47vKbMQ+8TL9668ilT83f" +
"6eo6mHZ590pzuDB+gFrjEK44ov0rvHBK5jHwnSObQvChN0ElizWBdMSUbx9SkcnReH6Fd29SSXdu" +
"RaVspnhmFNXWg7qGYHpEChnIGSr/WIKETZ84f7FRCxCNSYoQtrHs0SskiEGJYEbB6KDMFimEZ4YN" +
"b4cV8VLC9Pxa1Qe1Oa05FBzG2DAP2PfObeKR34afF5wo6vIZfQE0WWoPo9YS326vz1iA5rE0F6qw" +
"zCNmZl8+rW6x73MTEcWhvg==");
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha256()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha256 --aes256 -keyopt rsa_oaep_md:sha256
byte[] encodedMessage = Convert.FromBase64String(
"MIIBUAYJKoZIhvcNAQcDoIIBQTCCAT0CAQAxgfkwgfYCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwOAYJKoZI" +
"hvcNAQEHMCugDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUD" +
"BAIBBIGAuobMSz1Q4OHRX2aX9AutOPdZX2phA6WATQTOKOWCD//LQwrHYtuNIPAG" +
"Tld+JTZ1EMQD9PoEMyxdkllyie2dn/PSvnE0q/WU+IrHzGzoWofuNs9M6g9Gvpg5" +
"qCGAXK9cL3WkZ9S+M1r6BqlCLwU03bJr6292PiLyjIH80CdMuRUwPAYJKoZIhvcN" +
"AQcBMB0GCWCGSAFlAwQBKgQQezbMDGrefOaUPpfIXBpw7oAQazcOoj9GkvzZMR9Z" +
"NU22nQ==");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha384()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha384 --aes256 -keyopt rsa_oaep_md:sha384
byte[] encodedMessage = Convert.FromBase64String(
"MIIB0AYJKoZIhvcNAQcDoIIBwTCCAb0CAQAxggF4MIIBdAIBADAxMCQxIjAgBgNV" +
"BAMMGVJTQTIwNDhTaGEyNTZLZXlUcmFuc2ZlcjECCQDc5NcqfzyljjA4BgkqhkiG" +
"9w0BAQcwK6ANMAsGCWCGSAFlAwQCAqEaMBgGCSqGSIb3DQEBCDALBglghkgBZQME" +
"AgIEggEAIqqdx5zCFnGSNzV+/N0Mu8S8CVABuPv+RcpV8fiFj5TLcHe84lYI/ptr" +
"F7FwyQRfHVDWgJrJqDS/wYfzD6Ar8qLRdfBswCotn/QYm/VLzBXNRLM402t3lWq+" +
"2pgucyGghpnf2I1aZo8U9hJGUOUPISQqkiol9I1O/JYfo9B7sBTW8Vp22W/c8nTI" +
"huQx+tOhzqGAMElrsd+cEaTiVqAMmNU20B2du0wWs0nckzg4KLbz2g/g8L699luU" +
"t8OluQclxfVgruLY28RY8R5w7OH2LZSEhyKxq3PG3KqXqR+E1MCkpdg8PhTJkeYO" +
"Msz1J70aVA8L8nrhtS9xXq0dd8jyfzA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEq" +
"BBA/xHlg1Der3mxzmvPvUcqogBDEEZmz+ECEWMeNGBv/Cw82");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSA2048Sha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha512()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha512 --aes256 -keyopt rsa_oaep_md:sha512
byte[] encodedMessage = Convert.FromBase64String(
"MIIB0AYJKoZIhvcNAQcDoIIBwTCCAb0CAQAxggF4MIIBdAIBADAxMCQxIjAgBgNV" +
"BAMMGVJTQTIwNDhTaGEyNTZLZXlUcmFuc2ZlcjECCQDc5NcqfzyljjA4BgkqhkiG" +
"9w0BAQcwK6ANMAsGCWCGSAFlAwQCA6EaMBgGCSqGSIb3DQEBCDALBglghkgBZQME" +
"AgMEggEAc6QULhpkV7C63HhSbdYM7QFDTtRj8Wch3QHrFB0jIYlLGxcMuOB3Kw6f" +
"P1Q4W8qmVJgH+dyeKcpu2J6OrjlZVDtK166DrmKCflTMCGhCsPsmCMbKlpBihuXo" +
"7xQ13Fzs9QhudY/B/jUNjOTb3nONBqOdDJVLFsoMxm9cJqnDcdFPJVgIFl3IQW7X" +
"I1ZFdnS6FVKybR94jU4ASx8awQ+zDOgnCsyZ7t5cOwca2NgyQxZCf92WEJjdXqbl" +
"3ax/ULfSWD104Fp4N7lf8Z9BAkjIVJh3EeROzWgDkP5FQ9bDqkn3x+IlVKHfu+3r" +
"fmaUWI/sZCMXnUnLFEEILwCBcZlvBzA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEq" +
"BBDJhteA5Rpug15ksuJ9o/9vgBDQzvGRyFU8AKtfSpF6jBkB");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSA2048Sha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha1_Default()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha1
byte[] encodedMessage = Convert.FromBase64String(
"MIIBJQYJKoZIhvcNAQcDoIIBFjCCARICAQAxgc4wgcsCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwDQYJKoZI" +
"hvcNAQEHMAAEgYCLNNE4H03P0aP1lBDwKrm549DajTVSeyseWxv7TDDdVVWOTNgh" +
"c5OEVT2lmzxWD6lq28aZqmV8PPxJhvOZl4mnY9ycA5hgwmFRdKyI2hBTWQL8GQcF" +
"nYKc54BMKNaJsfIUIwN89knw7AEYEchGF+USKgQY1qsvdag6ZNBuhs5uwTA8Bgkq" +
"hkiG9w0BBwEwHQYJYIZIAWUDBAEqBBB/OyPGgn42q2XoDE4o8+2ggBDRXtH4O1xQ" +
"BHevgmD2Ev8V");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaep_MaskGenFunc_HashFunc_Mismatch()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha256
byte[] encodedMessage = Convert.FromBase64String(
"MIIBNAYJKoZIhvcNAQcDoIIBJTCCASECAQAxgd0wgdoCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwHAYJKoZI" +
"hvcNAQEHMA+gDTALBglghkgBZQMEAgEEgYCw85yDulRtibSZm0xy1mOTIGjDu4yy" +
"pMT++3dV5Cy2GF4vp3mxp89Ylq2boYZ8b4B86IcJqUfyU/fG19O+vXyjn/0VUP3f" +
"OjMM71oqvQc/Qou/LvgDYQZY1koDldoeH89waZ1hgFaVpFEwGZUPSHmzgfsxMOpj" +
"RoToifiTsP3PkjA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBCCufI08zVL4KVc" +
"WgKwZxCNgBA9M9KpJHmKwm5dMtvdcs/Q");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaep_PSpecified_NonDefault()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep \
// -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha1 -keyopt rsa_oaep_label:0102030405
byte[] encodedMessage = Convert.FromBase64String(
"MIIBOwYJKoZIhvcNAQcDoIIBLDCCASgCAQAxgeQwgeECAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwIwYJKoZI" +
"hvcNAQEHMBaiFDASBgkqhkiG9w0BAQkEBQECAwQFBIGAoJ7P69rwtexRcLbK+K8z" +
"UrKROLk2tVU8xGA056j8o2GfqQPxGsHl1w8Q3lsnSPsjGHY30+KYmQMQrZJd5zIW" +
"2OpgriYeqnHUwNCd9CrRFVvEqqACZlzTw/L+DgeDXwSNPRzNghjIqWo79FFT9kRI" +
"DHUB10A+sIZevVYtFrWxbVQwPAYJKoZIhvcNAQcBMB0GCWCGSAFlAwQBKgQQfxMe" +
"56xuPm9lTJYYozmQ6oAQd1RIE2hhgx1kdJmIW1Z4/w==");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo));
}
[Fact]
public void DecryptEnvelopedOctetStringWithDefiniteLength()
{
// enveloped content consists of 5 bytes: <id: 1 byte><length: 1 byte><content: 3 bytes>
// <id>:
// 04 - Octet string
// 30 - Sequence
// <length>: 03 => length is 3 (encoded with definite length)
// <content>: 010203
// Note: we expect invalid ASN.1 sequence
byte[] content = "0403010203".HexToByteArray();
byte[] expectedContent = "3003010203".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithInefficientlyEncodedLength()
{
// enveloped content consists of 5 or 6 bytes: <id: 1 byte><length: 1 or 2 bytes><content: 3 bytes>
// <id>:
// 04 - Octet string
// 30 - Sequence
// <length>: 03 => length is 3 (encoded with definite length)
// 81 03 => length is 3 (encoded with inefficiently encoded length)
// <content>: 010203
// Note: we expect invalid ASN.1 sequence
byte[] content = "048103010203".HexToByteArray();
byte[] expectedContent = "3003010203".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx does not allow it")]
public void DecryptEnvelopedEmptyArray()
{
byte[] content = Array.Empty<byte>();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedEmptyOctetString()
{
byte[] content = "0400".HexToByteArray();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithExtraData()
{
byte[] content = "04010203".HexToByteArray();
byte[] expectedContent = "300102".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedDataWithNonPkcs7Oid()
{
byte[] content = "3003010203".HexToByteArray();
string nonPkcs7Oid = "0.0";
ContentInfo contentInfo = new ContentInfo(new Oid(nonPkcs7Oid), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsIndefiniteLengthEncoding))]
public void DecryptEnvelopedEmptyOctetStringWithIndefiniteLength()
{
byte[] content = "30800000".HexToByteArray();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[ConditionalFact(nameof(SupportsIndefiniteLengthEncoding))]
public void DecryptEnvelopedOctetStringWithIndefiniteLength()
{
byte[] content = "308004000000".HexToByteArray();
byte[] expectedContent = "30020400".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
private void TestSimpleDecrypt_RoundTrip(CertLoader certLoader, ContentInfo contentInfo, string algorithmOidValue, SubjectIdentifierType type, ContentInfo expectedContentInfo = null)
{
// Deep-copy the contentInfo since the real ContentInfo doesn't do this. This defends against a bad implementation changing
// our "expectedContentInfo" to match what it produces.
expectedContentInfo = expectedContentInfo ?? new ContentInfo(new Oid(contentInfo.ContentType), (byte[])(contentInfo.Content.Clone()));
string certSubjectName;
byte[] encodedMessage;
byte[] originalCopy = (byte[])(contentInfo.Content.Clone());
using (X509Certificate2 certificate = certLoader.GetCertificate())
{
certSubjectName = certificate.Subject;
AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(algorithmOidValue));
EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg);
CmsRecipient cmsRecipient = new CmsRecipient(type, certificate);
ecms.Encrypt(cmsRecipient);
Assert.Equal(originalCopy.ByteArrayToHex(), ecms.ContentInfo.Content.ByteArrayToHex());
encodedMessage = ecms.Encode();
}
// We don't pass "certificate" down because it's expected that the certificate used for encrypting doesn't have a private key (part of the purpose of this test is
// to ensure that you don't need the recipient's private key to encrypt.) The decrypt phase will have to locate the matching cert with the private key.
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
internal void VerifySimpleDecrypt(byte[] encodedMessage, CertLoader certLoader, ContentInfo expectedContent)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = certLoader.TryGetCertificateWithPrivateKey())
{
if (cert == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
#if NETCOREAPP // API not present on netfx
if (_useExplicitPrivateKey)
{
using (X509Certificate2 pubCert = certLoader.GetCertificate())
{
RecipientInfo recipient = ecms.RecipientInfos.Cast<RecipientInfo>().Where((r) => r.RecipientIdentifier.MatchesCertificate(cert)).Single();
ecms.Decrypt(recipient, cert.PrivateKey);
}
}
else
#endif
{
X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
ecms.Decrypt(extraStore);
}
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal(expectedContent.ContentType.Value, contentInfo.ContentType.Value);
Assert.Equal(expectedContent.Content.ByteArrayToHex(), contentInfo.Content.ByteArrayToHex());
}
}
}
}
| |
namespace ZetaResourceEditor.UI.FileGroups
{
partial class CreateNewFileForm
{
/// <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.panelControl1 = new ExtendedControlsLibrary.Skinning.CustomPanel.MyPanelControl();
this.labelCsProjectToAdd = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.AddFileAsDependantUponCheckBox = new ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit();
this.IncludeFileInCsprojChecBox = new ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit();
this.buttonSettings = new ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton();
this.labelControl3 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.buttonDefault = new ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton();
this.prefixTextBox = new ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit();
this.prefixCheckBox = new ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit();
this.buttonCancel = new ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton();
this.copyTextsCheckBox = new ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit();
this.buttonOK = new ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton();
this.automaticallyTranslateCheckBox = new ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit();
this.label1 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.newLanguageComboBox = new ExtendedControlsLibrary.Skinning.CustomComboBoxEdit.MyComboBoxEdit();
this.label2 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.referenceLanguageComboBox = new ExtendedControlsLibrary.Skinning.CustomComboBoxEdit.MyComboBoxEdit();
this.fileGroupTextBox = new ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit();
this.labelControl2 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.newFileNameTextBox = new ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit();
this.labelControl1 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
((System.ComponentModel.ISupportInitialize)(this.panelControl1)).BeginInit();
this.panelControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.AddFileAsDependantUponCheckBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.IncludeFileInCsprojChecBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.prefixTextBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.prefixCheckBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.copyTextsCheckBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.automaticallyTranslateCheckBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.newLanguageComboBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.referenceLanguageComboBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.fileGroupTextBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.newFileNameTextBox.Properties)).BeginInit();
this.SuspendLayout();
//
// panelControl1
//
this.panelControl1.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.panelControl1.Controls.Add(this.labelCsProjectToAdd);
this.panelControl1.Controls.Add(this.AddFileAsDependantUponCheckBox);
this.panelControl1.Controls.Add(this.IncludeFileInCsprojChecBox);
this.panelControl1.Controls.Add(this.buttonSettings);
this.panelControl1.Controls.Add(this.labelControl3);
this.panelControl1.Controls.Add(this.buttonDefault);
this.panelControl1.Controls.Add(this.prefixTextBox);
this.panelControl1.Controls.Add(this.prefixCheckBox);
this.panelControl1.Controls.Add(this.buttonCancel);
this.panelControl1.Controls.Add(this.copyTextsCheckBox);
this.panelControl1.Controls.Add(this.buttonOK);
this.panelControl1.Controls.Add(this.automaticallyTranslateCheckBox);
this.panelControl1.Controls.Add(this.label1);
this.panelControl1.Controls.Add(this.newLanguageComboBox);
this.panelControl1.Controls.Add(this.label2);
this.panelControl1.Controls.Add(this.referenceLanguageComboBox);
this.panelControl1.Controls.Add(this.fileGroupTextBox);
this.panelControl1.Controls.Add(this.labelControl2);
this.panelControl1.Controls.Add(this.newFileNameTextBox);
this.panelControl1.Controls.Add(this.labelControl1);
this.panelControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelControl1.Location = new System.Drawing.Point(0, 0);
this.panelControl1.Margin = new System.Windows.Forms.Padding(0);
this.panelControl1.Name = "panelControl1";
this.panelControl1.Padding = new System.Windows.Forms.Padding(9);
this.panelControl1.Size = new System.Drawing.Size(484, 341);
this.panelControl1.TabIndex = 0;
//
// labelCsProjectToAdd
//
this.labelCsProjectToAdd.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelCsProjectToAdd.Appearance.Options.UseFont = true;
this.labelCsProjectToAdd.Location = new System.Drawing.Point(158, 235);
this.labelCsProjectToAdd.Name = "labelCsProjectToAdd";
this.labelCsProjectToAdd.Size = new System.Drawing.Size(18, 17);
this.labelCsProjectToAdd.TabIndex = 14;
this.labelCsProjectToAdd.Text = "<>";
//
// AddFileAsDependantUponCheckBox
//
this.AddFileAsDependantUponCheckBox.Location = new System.Drawing.Point(14, 260);
this.AddFileAsDependantUponCheckBox.Name = "AddFileAsDependantUponCheckBox";
this.AddFileAsDependantUponCheckBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.AddFileAsDependantUponCheckBox.Properties.Appearance.Options.UseFont = true;
this.AddFileAsDependantUponCheckBox.Properties.AutoWidth = true;
this.AddFileAsDependantUponCheckBox.Properties.Caption = "&Add file as dependantUpon (to main resource file)";
this.AddFileAsDependantUponCheckBox.Size = new System.Drawing.Size(316, 21);
this.AddFileAsDependantUponCheckBox.TabIndex = 15;
//
// IncludeFileInCsprojChecBox
//
this.IncludeFileInCsprojChecBox.Location = new System.Drawing.Point(14, 233);
this.IncludeFileInCsprojChecBox.Name = "IncludeFileInCsprojChecBox";
this.IncludeFileInCsprojChecBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.IncludeFileInCsprojChecBox.Properties.Appearance.Options.UseFont = true;
this.IncludeFileInCsprojChecBox.Properties.AutoWidth = true;
this.IncludeFileInCsprojChecBox.Properties.Caption = "&Include file in csproj";
this.IncludeFileInCsprojChecBox.Size = new System.Drawing.Size(139, 21);
this.IncludeFileInCsprojChecBox.TabIndex = 13;
this.IncludeFileInCsprojChecBox.CheckedChanged += new System.EventHandler(this.IncludeFileInCsprojChecBox_CheckedChanged);
//
// buttonSettings
//
this.buttonSettings.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonSettings.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.buttonSettings.Appearance.Options.UseFont = true;
this.buttonSettings.Location = new System.Drawing.Point(14, 299);
this.buttonSettings.Name = "buttonSettings";
this.buttonSettings.Size = new System.Drawing.Size(75, 28);
this.buttonSettings.TabIndex = 16;
this.buttonSettings.Text = "Settings";
this.buttonSettings.WantDrawFocusRectangle = true;
this.buttonSettings.Click += new System.EventHandler(this.buttonSettings_Click);
//
// labelControl3
//
this.labelControl3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.labelControl3.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelControl3.Appearance.ForeColor = System.Drawing.SystemColors.GrayText;
this.labelControl3.Appearance.Options.UseFont = true;
this.labelControl3.Appearance.Options.UseForeColor = true;
this.labelControl3.Location = new System.Drawing.Point(95, 305);
this.labelControl3.Name = "labelControl3";
this.labelControl3.Size = new System.Drawing.Size(18, 17);
this.labelControl3.TabIndex = 17;
this.labelControl3.Text = "<>";
//
// buttonDefault
//
this.buttonDefault.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.buttonDefault.Appearance.Options.UseFont = true;
this.buttonDefault.Location = new System.Drawing.Point(301, 202);
this.buttonDefault.Name = "buttonDefault";
this.buttonDefault.Size = new System.Drawing.Size(60, 26);
this.buttonDefault.TabIndex = 12;
this.buttonDefault.Text = "Default";
this.buttonDefault.WantDrawFocusRectangle = true;
this.buttonDefault.Click += new System.EventHandler(this.buttonDefault_Click);
//
// prefixTextBox
//
this.prefixTextBox.Bold = false;
this.prefixTextBox.CueText = null;
this.prefixTextBox.Location = new System.Drawing.Point(195, 203);
this.prefixTextBox.MaximumSize = new System.Drawing.Size(0, 24);
this.prefixTextBox.MinimumSize = new System.Drawing.Size(0, 24);
this.prefixTextBox.Name = "prefixTextBox";
this.prefixTextBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.prefixTextBox.Properties.Appearance.Options.UseFont = true;
this.prefixTextBox.Properties.Mask.EditMask = null;
this.prefixTextBox.Properties.NullValuePrompt = null;
this.prefixTextBox.Properties.ShowNullValuePrompt = ((DevExpress.XtraEditors.ShowNullValuePromptOptions)((DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorFocused | DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorReadOnly)));
this.prefixTextBox.Size = new System.Drawing.Size(100, 24);
this.prefixTextBox.TabIndex = 11;
this.prefixTextBox.EditValueChanged += new System.EventHandler(this.prefixTextBox_EditValueChanged);
//
// prefixCheckBox
//
this.prefixCheckBox.Location = new System.Drawing.Point(14, 204);
this.prefixCheckBox.Name = "prefixCheckBox";
this.prefixCheckBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.prefixCheckBox.Properties.Appearance.Options.UseFont = true;
this.prefixCheckBox.Properties.AutoWidth = true;
this.prefixCheckBox.Properties.Caption = "Prefix translated texts with:";
this.prefixCheckBox.Size = new System.Drawing.Size(178, 21);
this.prefixCheckBox.TabIndex = 10;
this.prefixCheckBox.CheckedChanged += new System.EventHandler(this.prefixCheckBox_CheckedChanged);
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.buttonCancel.Appearance.Options.UseFont = true;
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(395, 299);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 28);
this.buttonCancel.TabIndex = 19;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.WantDrawFocusRectangle = true;
//
// copyTextsCheckBox
//
this.copyTextsCheckBox.Location = new System.Drawing.Point(14, 147);
this.copyTextsCheckBox.Name = "copyTextsCheckBox";
this.copyTextsCheckBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.copyTextsCheckBox.Properties.Appearance.Options.UseFont = true;
this.copyTextsCheckBox.Properties.AutoWidth = true;
this.copyTextsCheckBox.Properties.Caption = "&Copy texts from reference language";
this.copyTextsCheckBox.Size = new System.Drawing.Size(233, 21);
this.copyTextsCheckBox.TabIndex = 8;
this.copyTextsCheckBox.CheckedChanged += new System.EventHandler(this.copyTextsCheckBox_CheckedChanged);
//
// buttonOK
//
this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOK.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.buttonOK.Appearance.Options.UseFont = true;
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOK.Location = new System.Drawing.Point(314, 299);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 28);
this.buttonOK.TabIndex = 18;
this.buttonOK.Text = "OK";
this.buttonOK.WantDrawFocusRectangle = true;
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// automaticallyTranslateCheckBox
//
this.automaticallyTranslateCheckBox.Location = new System.Drawing.Point(14, 174);
this.automaticallyTranslateCheckBox.Name = "automaticallyTranslateCheckBox";
this.automaticallyTranslateCheckBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.automaticallyTranslateCheckBox.Properties.Appearance.Options.UseFont = true;
this.automaticallyTranslateCheckBox.Properties.AutoWidth = true;
this.automaticallyTranslateCheckBox.Properties.Caption = "&Automatically translate from reference language";
this.automaticallyTranslateCheckBox.Size = new System.Drawing.Size(303, 21);
this.automaticallyTranslateCheckBox.TabIndex = 9;
this.automaticallyTranslateCheckBox.CheckedChanged += new System.EventHandler(this.automaticallyTranslateCheckBox_CheckedChanged);
//
// label1
//
this.label1.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.label1.Appearance.Options.UseFont = true;
this.label1.Location = new System.Drawing.Point(16, 17);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(62, 17);
this.label1.TabIndex = 0;
this.label1.Text = "File group:";
//
// newLanguageComboBox
//
this.newLanguageComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.newLanguageComboBox.CueText = null;
this.newLanguageComboBox.Location = new System.Drawing.Point(141, 82);
this.newLanguageComboBox.Name = "newLanguageComboBox";
this.newLanguageComboBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.newLanguageComboBox.Properties.Appearance.Options.UseFont = true;
this.newLanguageComboBox.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.newLanguageComboBox.Properties.DropDownRows = 20;
this.newLanguageComboBox.Properties.NullValuePrompt = null;
this.newLanguageComboBox.Properties.ShowNullValuePrompt = ((DevExpress.XtraEditors.ShowNullValuePromptOptions)((DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorFocused | DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorReadOnly)));
this.newLanguageComboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
this.newLanguageComboBox.Properties.SelectedIndexChanged += new System.EventHandler(this.referenceLanguageGroupBox_SelectedIndexChanged);
this.newLanguageComboBox.Size = new System.Drawing.Size(329, 24);
this.newLanguageComboBox.TabIndex = 5;
this.newLanguageComboBox.SelectedIndexChanged += new System.EventHandler(this.newLanguageComboBox_SelectedIndexChanged);
this.newLanguageComboBox.TextChanged += new System.EventHandler(this.newLanguageComboBox_TextChanged);
//
// label2
//
this.label2.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.label2.Appearance.Options.UseFont = true;
this.label2.Location = new System.Drawing.Point(16, 47);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(119, 17);
this.label2.TabIndex = 2;
this.label2.Text = "&Reference language:";
//
// referenceLanguageComboBox
//
this.referenceLanguageComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.referenceLanguageComboBox.CueText = null;
this.referenceLanguageComboBox.Location = new System.Drawing.Point(141, 44);
this.referenceLanguageComboBox.Name = "referenceLanguageComboBox";
this.referenceLanguageComboBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.referenceLanguageComboBox.Properties.Appearance.Options.UseFont = true;
this.referenceLanguageComboBox.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.referenceLanguageComboBox.Properties.DropDownRows = 20;
this.referenceLanguageComboBox.Properties.NullValuePrompt = null;
this.referenceLanguageComboBox.Properties.ShowNullValuePrompt = ((DevExpress.XtraEditors.ShowNullValuePromptOptions)((DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorFocused | DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorReadOnly)));
this.referenceLanguageComboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
this.referenceLanguageComboBox.Properties.SelectedIndexChanged += new System.EventHandler(this.referenceLanguageGroupBox_SelectedIndexChanged);
this.referenceLanguageComboBox.Size = new System.Drawing.Size(329, 24);
this.referenceLanguageComboBox.TabIndex = 3;
this.referenceLanguageComboBox.SelectedIndexChanged += new System.EventHandler(this.referenceLanguageComboBox_SelectedIndexChanged);
//
// fileGroupTextBox
//
this.fileGroupTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fileGroupTextBox.Bold = false;
this.fileGroupTextBox.CueText = null;
this.fileGroupTextBox.Location = new System.Drawing.Point(141, 14);
this.fileGroupTextBox.MaximumSize = new System.Drawing.Size(0, 24);
this.fileGroupTextBox.MinimumSize = new System.Drawing.Size(0, 24);
this.fileGroupTextBox.Name = "fileGroupTextBox";
this.fileGroupTextBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.fileGroupTextBox.Properties.Appearance.Options.UseFont = true;
this.fileGroupTextBox.Properties.Mask.EditMask = null;
this.fileGroupTextBox.Properties.NullValuePrompt = null;
this.fileGroupTextBox.Properties.ReadOnly = true;
this.fileGroupTextBox.Properties.ShowNullValuePrompt = ((DevExpress.XtraEditors.ShowNullValuePromptOptions)((DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorFocused | DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorReadOnly)));
this.fileGroupTextBox.Size = new System.Drawing.Size(329, 24);
this.fileGroupTextBox.TabIndex = 1;
//
// labelControl2
//
this.labelControl2.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelControl2.Appearance.Options.UseFont = true;
this.labelControl2.Location = new System.Drawing.Point(16, 115);
this.labelControl2.Name = "labelControl2";
this.labelControl2.Size = new System.Drawing.Size(86, 17);
this.labelControl2.TabIndex = 6;
this.labelControl2.Text = "New file name:";
//
// newFileNameTextBox
//
this.newFileNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.newFileNameTextBox.Bold = false;
this.newFileNameTextBox.CueText = null;
this.newFileNameTextBox.Location = new System.Drawing.Point(141, 112);
this.newFileNameTextBox.MaximumSize = new System.Drawing.Size(0, 24);
this.newFileNameTextBox.MinimumSize = new System.Drawing.Size(0, 24);
this.newFileNameTextBox.Name = "newFileNameTextBox";
this.newFileNameTextBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.newFileNameTextBox.Properties.Appearance.Options.UseFont = true;
this.newFileNameTextBox.Properties.Mask.EditMask = null;
this.newFileNameTextBox.Properties.NullValuePrompt = null;
this.newFileNameTextBox.Properties.ReadOnly = true;
this.newFileNameTextBox.Properties.ShowNullValuePrompt = ((DevExpress.XtraEditors.ShowNullValuePromptOptions)((DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorFocused | DevExpress.XtraEditors.ShowNullValuePromptOptions.EditorReadOnly)));
this.newFileNameTextBox.Size = new System.Drawing.Size(329, 24);
this.newFileNameTextBox.TabIndex = 7;
this.newFileNameTextBox.TextChanged += new System.EventHandler(this.newFileNameTextBox_TextChanged);
//
// labelControl1
//
this.labelControl1.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelControl1.Appearance.Options.UseFont = true;
this.labelControl1.Location = new System.Drawing.Point(16, 85);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(87, 17);
this.labelControl1.TabIndex = 4;
this.labelControl1.Text = "&New language:";
//
// CreateNewFileForm
//
this.AcceptButton = this.buttonOK;
this.Appearance.Options.UseFont = true;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(484, 341);
this.Controls.Add(this.panelControl1);
this.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.IconOptions.ShowIcon = false;
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(1024, 380);
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(486, 373);
this.Name = "CreateNewFileForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Create new files for language";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.CreateNewFileForm_FormClosing);
this.Load += new System.EventHandler(this.CreateNewFileForm_Load);
((System.ComponentModel.ISupportInitialize)(this.panelControl1)).EndInit();
this.panelControl1.ResumeLayout(false);
this.panelControl1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.AddFileAsDependantUponCheckBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.IncludeFileInCsprojChecBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.prefixTextBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.prefixCheckBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.copyTextsCheckBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.automaticallyTranslateCheckBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.newLanguageComboBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.referenceLanguageComboBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.fileGroupTextBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.newFileNameTextBox.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private ExtendedControlsLibrary.Skinning.CustomPanel.MyPanelControl panelControl1;
private ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton buttonCancel;
private ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton buttonOK;
private ExtendedControlsLibrary.Skinning.CustomComboBoxEdit.MyComboBoxEdit referenceLanguageComboBox;
private ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit fileGroupTextBox;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl label2;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl label1;
private ExtendedControlsLibrary.Skinning.CustomComboBoxEdit.MyComboBoxEdit newLanguageComboBox;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelControl2;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelControl1;
private ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit newFileNameTextBox;
private ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit automaticallyTranslateCheckBox;
private ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit copyTextsCheckBox;
private ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton buttonDefault;
private ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit prefixTextBox;
private ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit prefixCheckBox;
private ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton buttonSettings;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelControl3;
private ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit AddFileAsDependantUponCheckBox;
private ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit IncludeFileInCsprojChecBox;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelCsProjectToAdd;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: comments/comments_service.proto
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace KillrVideo.Comments {
/// <summary>
/// Manages comments
/// </summary>
public static class CommentsService
{
static readonly string __ServiceName = "killrvideo.comments.CommentsService";
static readonly Marshaller<global::KillrVideo.Comments.CommentOnVideoRequest> __Marshaller_CommentOnVideoRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Comments.CommentOnVideoRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Comments.CommentOnVideoResponse> __Marshaller_CommentOnVideoResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Comments.CommentOnVideoResponse.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Comments.GetUserCommentsRequest> __Marshaller_GetUserCommentsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Comments.GetUserCommentsRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Comments.GetUserCommentsResponse> __Marshaller_GetUserCommentsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Comments.GetUserCommentsResponse.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Comments.GetVideoCommentsRequest> __Marshaller_GetVideoCommentsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Comments.GetVideoCommentsRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Comments.GetVideoCommentsResponse> __Marshaller_GetVideoCommentsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Comments.GetVideoCommentsResponse.Parser.ParseFrom);
static readonly Method<global::KillrVideo.Comments.CommentOnVideoRequest, global::KillrVideo.Comments.CommentOnVideoResponse> __Method_CommentOnVideo = new Method<global::KillrVideo.Comments.CommentOnVideoRequest, global::KillrVideo.Comments.CommentOnVideoResponse>(
MethodType.Unary,
__ServiceName,
"CommentOnVideo",
__Marshaller_CommentOnVideoRequest,
__Marshaller_CommentOnVideoResponse);
static readonly Method<global::KillrVideo.Comments.GetUserCommentsRequest, global::KillrVideo.Comments.GetUserCommentsResponse> __Method_GetUserComments = new Method<global::KillrVideo.Comments.GetUserCommentsRequest, global::KillrVideo.Comments.GetUserCommentsResponse>(
MethodType.Unary,
__ServiceName,
"GetUserComments",
__Marshaller_GetUserCommentsRequest,
__Marshaller_GetUserCommentsResponse);
static readonly Method<global::KillrVideo.Comments.GetVideoCommentsRequest, global::KillrVideo.Comments.GetVideoCommentsResponse> __Method_GetVideoComments = new Method<global::KillrVideo.Comments.GetVideoCommentsRequest, global::KillrVideo.Comments.GetVideoCommentsResponse>(
MethodType.Unary,
__ServiceName,
"GetVideoComments",
__Marshaller_GetVideoCommentsRequest,
__Marshaller_GetVideoCommentsResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::KillrVideo.Comments.CommentsServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of CommentsService</summary>
public abstract class CommentsServiceBase
{
/// <summary>
/// Add a new comment to a video
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.Comments.CommentOnVideoResponse> CommentOnVideo(global::KillrVideo.Comments.CommentOnVideoRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Get comments made by a user
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.Comments.GetUserCommentsResponse> GetUserComments(global::KillrVideo.Comments.GetUserCommentsRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Get comments made on a video
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.Comments.GetVideoCommentsResponse> GetVideoComments(global::KillrVideo.Comments.GetVideoCommentsRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for CommentsService</summary>
public class CommentsServiceClient : ClientBase<CommentsServiceClient>
{
/// <summary>Creates a new client for CommentsService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public CommentsServiceClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for CommentsService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public CommentsServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected CommentsServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected CommentsServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Add a new comment to a video
/// </summary>
public virtual global::KillrVideo.Comments.CommentOnVideoResponse CommentOnVideo(global::KillrVideo.Comments.CommentOnVideoRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CommentOnVideo(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Add a new comment to a video
/// </summary>
public virtual global::KillrVideo.Comments.CommentOnVideoResponse CommentOnVideo(global::KillrVideo.Comments.CommentOnVideoRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CommentOnVideo, null, options, request);
}
/// <summary>
/// Add a new comment to a video
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Comments.CommentOnVideoResponse> CommentOnVideoAsync(global::KillrVideo.Comments.CommentOnVideoRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CommentOnVideoAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Add a new comment to a video
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Comments.CommentOnVideoResponse> CommentOnVideoAsync(global::KillrVideo.Comments.CommentOnVideoRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CommentOnVideo, null, options, request);
}
/// <summary>
/// Get comments made by a user
/// </summary>
public virtual global::KillrVideo.Comments.GetUserCommentsResponse GetUserComments(global::KillrVideo.Comments.GetUserCommentsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetUserComments(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get comments made by a user
/// </summary>
public virtual global::KillrVideo.Comments.GetUserCommentsResponse GetUserComments(global::KillrVideo.Comments.GetUserCommentsRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetUserComments, null, options, request);
}
/// <summary>
/// Get comments made by a user
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Comments.GetUserCommentsResponse> GetUserCommentsAsync(global::KillrVideo.Comments.GetUserCommentsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetUserCommentsAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get comments made by a user
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Comments.GetUserCommentsResponse> GetUserCommentsAsync(global::KillrVideo.Comments.GetUserCommentsRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetUserComments, null, options, request);
}
/// <summary>
/// Get comments made on a video
/// </summary>
public virtual global::KillrVideo.Comments.GetVideoCommentsResponse GetVideoComments(global::KillrVideo.Comments.GetVideoCommentsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetVideoComments(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get comments made on a video
/// </summary>
public virtual global::KillrVideo.Comments.GetVideoCommentsResponse GetVideoComments(global::KillrVideo.Comments.GetVideoCommentsRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetVideoComments, null, options, request);
}
/// <summary>
/// Get comments made on a video
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Comments.GetVideoCommentsResponse> GetVideoCommentsAsync(global::KillrVideo.Comments.GetVideoCommentsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetVideoCommentsAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get comments made on a video
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Comments.GetVideoCommentsResponse> GetVideoCommentsAsync(global::KillrVideo.Comments.GetVideoCommentsRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetVideoComments, null, options, request);
}
protected override CommentsServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new CommentsServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(CommentsServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_CommentOnVideo, serviceImpl.CommentOnVideo)
.AddMethod(__Method_GetUserComments, serviceImpl.GetUserComments)
.AddMethod(__Method_GetVideoComments, serviceImpl.GetVideoComments).Build();
}
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime.ReminderService
{
internal class LocalReminderService : GrainService, IReminderService
{
private const int InitialReadRetryCountBeforeFastFailForUpdates = 2;
private static readonly TimeSpan InitialReadMaxWaitTimeForUpdates = TimeSpan.FromSeconds(20);
private static readonly TimeSpan InitialReadRetryPeriod = TimeSpan.FromSeconds(30);
private readonly Dictionary<ReminderIdentity, LocalReminderData> localReminders;
private readonly IReminderTable reminderTable;
private long localTableSequence;
private IGrainTimer listRefreshTimer; // timer that refreshes our list of reminders to reflect global reminder table
private readonly TaskCompletionSource<bool> startedTask;
private uint initialReadCallCount = 0;
private readonly AverageTimeSpanStatistic tardinessStat;
private readonly CounterStatistic ticksDeliveredStat;
private readonly GlobalConfiguration config;
private readonly TimeSpan initTimeout;
internal LocalReminderService(
Silo silo,
GrainId id,
IReminderTable reminderTable,
GlobalConfiguration config,
TimeSpan initTimeout)
: base(id, silo, null)
{
localReminders = new Dictionary<ReminderIdentity, LocalReminderData>();
this.reminderTable = reminderTable;
this.config = config;
this.initTimeout = initTimeout;
localTableSequence = 0;
tardinessStat = AverageTimeSpanStatistic.FindOrCreate(StatisticNames.REMINDERS_AVERAGE_TARDINESS_SECONDS);
IntValueStatistic.FindOrCreate(StatisticNames.REMINDERS_NUMBER_ACTIVE_REMINDERS, () => localReminders.Count);
ticksDeliveredStat = CounterStatistic.FindOrCreate(StatisticNames.REMINDERS_COUNTERS_TICKS_DELIVERED);
startedTask = new TaskCompletionSource<bool>();
}
#region Public methods
/// <summary>
/// Attempt to retrieve reminders, that are my responsibility, from the global reminder table when starting this silo (reminder service instance)
/// </summary>
/// <returns></returns>
public override async Task Start()
{
// confirm that it can access the underlying store, as after this the ReminderService will load in the background, without the opportunity to prevent the Silo from starting
await reminderTable.Init(config, Logger).WithTimeout(initTimeout);
await base.Start();
}
public async override Task Stop()
{
await base.Stop();
if (listRefreshTimer != null)
{
listRefreshTimer.Dispose();
listRefreshTimer = null;
}
foreach (LocalReminderData r in localReminders.Values)
r.StopReminder(Logger);
// for a graceful shutdown, also handover reminder responsibilities to new owner, and update the ReminderTable
// currently, this is taken care of by periodically reading the reminder table
}
public async Task<IGrainReminder> RegisterOrUpdateReminder(GrainReference grainRef, string reminderName, TimeSpan dueTime, TimeSpan period)
{
var entry = new ReminderEntry
{
GrainRef = grainRef,
ReminderName = reminderName,
StartAt = DateTime.UtcNow.Add(dueTime),
Period = period,
};
if(Logger.IsVerbose) Logger.Verbose(ErrorCode.RS_RegisterOrUpdate, "RegisterOrUpdateReminder: {0}", entry.ToString());
await DoResponsibilitySanityCheck(grainRef, "RegisterReminder");
var newEtag = await reminderTable.UpsertRow(entry);
if (newEtag != null)
{
if (Logger.IsVerbose) Logger.Verbose("Registered reminder {0} in table, assigned localSequence {1}", entry, localTableSequence);
entry.ETag = newEtag;
StartAndAddTimer(entry);
if (Logger.IsVerbose3) PrintReminders();
return new ReminderData(grainRef, reminderName, newEtag) as IGrainReminder;
}
var msg = string.Format("Could not register reminder {0} to reminder table due to a race. Please try again later.", entry);
Logger.Error(ErrorCode.RS_Register_TableError, msg);
throw new ReminderException(msg);
}
/// <summary>
/// Stop the reminder locally, and remove it from the external storage system
/// </summary>
/// <param name="reminder"></param>
/// <returns></returns>
public async Task UnregisterReminder(IGrainReminder reminder)
{
var remData = (ReminderData)reminder;
if(Logger.IsVerbose) Logger.Verbose(ErrorCode.RS_Unregister, "UnregisterReminder: {0}, LocalTableSequence: {1}", remData, localTableSequence);
GrainReference grainRef = remData.GrainRef;
string reminderName = remData.ReminderName;
string eTag = remData.ETag;
await DoResponsibilitySanityCheck(grainRef, "RemoveReminder");
// it may happen that we dont have this reminder locally ... even then, we attempt to remove the reminder from the reminder
// table ... the periodic mechanism will stop this reminder at any silo's LocalReminderService that might have this reminder locally
// remove from persistent/memory store
var success = await reminderTable.RemoveRow(grainRef, reminderName, eTag);
if (success)
{
bool removed = TryStopPreviousTimer(grainRef, reminderName);
if (removed)
{
if(Logger.IsVerbose) Logger.Verbose(ErrorCode.RS_Stop, "Stopped reminder {0}", reminder);
if (Logger.IsVerbose3) PrintReminders(string.Format("After removing {0}.", reminder));
}
else
{
// no-op
if(Logger.IsVerbose) Logger.Verbose(ErrorCode.RS_RemoveFromTable, "Removed reminder from table which I didn't have locally: {0}.", reminder);
}
}
else
{
var msg = string.Format("Could not unregister reminder {0} from the reminder table, due to tag mismatch. You can retry.", reminder);
Logger.Error(ErrorCode.RS_Unregister_TableError, msg);
throw new ReminderException(msg);
}
}
public async Task<IGrainReminder> GetReminder(GrainReference grainRef, string reminderName)
{
if(Logger.IsVerbose) Logger.Verbose(ErrorCode.RS_GetReminder,"GetReminder: GrainReference={0} ReminderName={1}", grainRef.ToDetailedString(), reminderName);
var entry = await reminderTable.ReadRow(grainRef, reminderName);
return entry == null ? null : entry.ToIGrainReminder();
}
public async Task<List<IGrainReminder>> GetReminders(GrainReference grainRef)
{
if (Logger.IsVerbose) Logger.Verbose(ErrorCode.RS_GetReminders, "GetReminders: GrainReference={0}", grainRef.ToDetailedString());
var tableData = await reminderTable.ReadRows(grainRef);
return tableData.Reminders.Select(entry => entry.ToIGrainReminder()).ToList();
}
#endregion
/// <summary>
/// Attempt to retrieve reminders from the global reminder table
/// </summary>
private async Task ReadAndUpdateReminders()
{
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
RemoveOutOfRangeReminders();
// try to retrieve reminders from all my subranges
var rangeSerialNumberCopy = RangeSerialNumber;
if (Logger.IsVerbose2) Logger.Verbose2($"My range= {RingRange}, RangeSerialNumber {RangeSerialNumber}. Local reminders count {localReminders.Count}");
var acks = new List<Task>();
foreach (var range in RangeFactory.GetSubRanges(RingRange))
{
acks.Add(ReadTableAndStartTimers(range, rangeSerialNumberCopy));
}
await Task.WhenAll(acks);
if (Logger.IsVerbose3) PrintReminders();
}
private void RemoveOutOfRangeReminders()
{
var remindersOutOfRange = localReminders.Where(r => !RingRange.InRange(r.Key.GrainRef)).Select(r => r.Value).ToArray();
foreach (var reminder in remindersOutOfRange)
{
if (Logger.IsVerbose2)
Logger.Verbose2("Not in my range anymore, so removing. {0}", reminder);
// remove locally
reminder.StopReminder(Logger);
localReminders.Remove(reminder.Identity);
}
if (Logger.IsInfo && remindersOutOfRange.Length > 0) Logger.Info($"Removed {remindersOutOfRange.Length} local reminders that are now out of my range.");
}
#region Change in membership, e.g., failure of predecessor
public override async Task OnRangeChange(IRingRange oldRange, IRingRange newRange, bool increased)
{
await base.OnRangeChange(oldRange, newRange, increased);
if (Status == GrainServiceStatus.Started)
await ReadAndUpdateReminders();
else
if (Logger.IsVerbose) Logger.Verbose("Ignoring range change until ReminderService is Started -- Current status = {0}", Status);
}
#endregion
#region Internal implementation methods
protected override async Task StartInBackground()
{
await DoInitialReadAndUpdateReminders();
if (Status == GrainServiceStatus.Booting)
{
var random = new SafeRandom();
listRefreshTimer = GrainTimer.FromTaskCallback(
this.RuntimeClient.Scheduler,
_ => DoInitialReadAndUpdateReminders(),
null,
random.NextTimeSpan(InitialReadRetryPeriod),
InitialReadRetryPeriod,
name: "ReminderService.ReminderListInitialRead");
listRefreshTimer.Start();
}
}
private void PromoteToStarted()
{
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
// Logger.Info(ErrorCode.RS_ServiceStarted, "Reminder system target started OK on: {0} x{1,8:X8}, with range {2}", this.Silo, this.Silo.GetConsistentHashCode(), this.myRange);
var random = new SafeRandom();
var dueTime = random.NextTimeSpan(Constants.RefreshReminderList);
if (listRefreshTimer != null) listRefreshTimer.Dispose();
listRefreshTimer = GrainTimer.FromTaskCallback(
this.RuntimeClient.Scheduler,
_ => ReadAndUpdateReminders(),
null,
dueTime,
Constants.RefreshReminderList,
name: "ReminderService.ReminderListRefresher");
listRefreshTimer.Start();
Status = GrainServiceStatus.Started;
startedTask.TrySetResult(true);
}
private async Task DoInitialReadAndUpdateReminders()
{
try
{
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
initialReadCallCount++;
await this.ReadAndUpdateReminders();
PromoteToStarted();
}
catch (Exception ex)
{
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
if (initialReadCallCount <= InitialReadRetryCountBeforeFastFailForUpdates)
{
Logger.Warn(
ErrorCode.RS_ServiceInitialLoadFailing,
string.Format("ReminderService failed initial load of reminders and will retry. Attempt #{0}", this.initialReadCallCount),
ex);
}
else
{
const string baseErrorMsg = "ReminderService failed initial load of reminders and cannot guarantee that the service will be eventually start without manual intervention or restarting the silo.";
var logErrorMessage = string.Format(baseErrorMsg + " Attempt #{0}", this.initialReadCallCount);
Logger.Error(ErrorCode.RS_ServiceInitialLoadFailed, logErrorMessage, ex);
startedTask.TrySetException(new OrleansException(baseErrorMsg, ex));
}
}
}
private async Task ReadTableAndStartTimers(IRingRange range, int rangeSerialNumberCopy)
{
if (Logger.IsVerbose) Logger.Verbose("Reading rows from {0}", range.ToString());
localTableSequence++;
long cachedSequence = localTableSequence;
try
{
var srange = range as ISingleRange;
if (srange == null)
throw new InvalidOperationException("LocalReminderService must be dealing with SingleRange");
ReminderTableData table = await reminderTable.ReadRows(srange.Begin, srange.End); // get all reminders, even the ones we already have
if (rangeSerialNumberCopy < RangeSerialNumber)
{
if (Logger.IsVerbose) Logger.Verbose($"My range changed while reading from the table, ignoring the results. Another read has been started. RangeSerialNumber {RangeSerialNumber}, RangeSerialNumberCopy {rangeSerialNumberCopy}.");
return;
}
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
// if null is a valid value, it means that there's nothing to do.
if (null == table && reminderTable is MockReminderTable) return;
var remindersNotInTable = localReminders.Where(r => range.InRange(r.Key.GrainRef)).ToDictionary(r => r.Key, r => r.Value); // shallow copy
if (Logger.IsVerbose) Logger.Verbose("For range {0}, I read in {1} reminders from table. LocalTableSequence {2}, CachedSequence {3}", range.ToString(), table.Reminders.Count, localTableSequence, cachedSequence);
foreach (ReminderEntry entry in table.Reminders)
{
var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
LocalReminderData localRem;
if (localReminders.TryGetValue(key, out localRem))
{
if (cachedSequence > localRem.LocalSequenceNumber) // info read from table is same or newer than local info
{
if (localRem.Timer != null) // if ticking
{
if (Logger.IsVerbose2) Logger.Verbose2("In table, In local, Old, & Ticking {0}", localRem);
// it might happen that our local reminder is different than the one in the table, i.e., eTag is different
// if so, stop the local timer for the old reminder, and start again with new info
if (!localRem.ETag.Equals(entry.ETag))
// this reminder needs a restart
{
if (Logger.IsVerbose2) Logger.Verbose2("{0} Needs a restart", localRem);
localRem.StopReminder(Logger);
localReminders.Remove(localRem.Identity);
StartAndAddTimer(entry);
}
}
else // if not ticking
{
// no-op
if (Logger.IsVerbose2) Logger.Verbose2("In table, In local, Old, & Not Ticking {0}", localRem);
}
}
else // cachedSequence < localRem.LocalSequenceNumber ... // info read from table is older than local info
{
if (localRem.Timer != null) // if ticking
{
// no-op
if (Logger.IsVerbose2) Logger.Verbose2("In table, In local, Newer, & Ticking {0}", localRem);
}
else // if not ticking
{
// no-op
if (Logger.IsVerbose2) Logger.Verbose2("In table, In local, Newer, & Not Ticking {0}", localRem);
}
}
}
else // exists in table, but not locally
{
if (Logger.IsVerbose2) Logger.Verbose2("In table, Not in local, {0}", entry);
// create and start the reminder
StartAndAddTimer(entry);
}
// keep a track of extra reminders ... this 'reminder' is useful, so remove it from extra list
remindersNotInTable.Remove(key);
} // foreach reminder read from table
int remindersCountBeforeRemove = localReminders.Count;
// foreach reminder that is not in global table, but exists locally
foreach (var reminder in remindersNotInTable.Values)
{
if (cachedSequence < reminder.LocalSequenceNumber)
{
// no-op
if (Logger.IsVerbose2) Logger.Verbose2("Not in table, In local, Newer, {0}", reminder);
}
else // cachedSequence > reminder.LocalSequenceNumber
{
if (Logger.IsVerbose2) Logger.Verbose2("Not in table, In local, Old, so removing. {0}", reminder);
// remove locally
reminder.StopReminder(Logger);
localReminders.Remove(reminder.Identity);
}
}
if (Logger.IsVerbose) Logger.Verbose($"Removed {localReminders.Count - remindersCountBeforeRemove} reminders from local table");
}
catch (Exception exc)
{
Logger.Error(ErrorCode.RS_FailedToReadTableAndStartTimer, "Failed to read rows from table.", exc);
throw;
}
}
private void StartAndAddTimer(ReminderEntry entry)
{
// it might happen that we already have a local reminder with a different eTag
// if so, stop the local timer for the old reminder, and start again with new info
// Note: it can happen here that we restart a reminder that has the same eTag as what we just registered ... its a rare case, and restarting it doesn't hurt, so we don't check for it
var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
LocalReminderData prevReminder;
if (localReminders.TryGetValue(key, out prevReminder)) // if found locally
{
if (Logger.IsVerbose) Logger.Verbose(ErrorCode.RS_LocalStop, "Localy stopping reminder {0} as it is different than newly registered reminder {1}", prevReminder, entry);
prevReminder.StopReminder(Logger);
localReminders.Remove(prevReminder.Identity);
}
var newReminder = new LocalReminderData(entry);
localTableSequence++;
newReminder.LocalSequenceNumber = localTableSequence;
localReminders.Add(newReminder.Identity, newReminder);
newReminder.StartTimer(this.RuntimeClient.Scheduler, AsyncTimerCallback, Logger);
if (Logger.IsVerbose) Logger.Verbose(ErrorCode.RS_Started, "Started reminder {0}.", entry.ToString());
}
// stop without removing it. will remove later.
private bool TryStopPreviousTimer(GrainReference grainRef, string reminderName)
{
// we stop the locally running timer for this reminder
var key = new ReminderIdentity(grainRef, reminderName);
LocalReminderData localRem;
if (!localReminders.TryGetValue(key, out localRem)) return false;
// if we have it locally
localTableSequence++; // move to next sequence
localRem.LocalSequenceNumber = localTableSequence;
localRem.StopReminder(Logger);
return true;
}
#endregion
/// <summary>
/// Local timer expired ... notify it as a 'tick' to the grain who registered this reminder
/// </summary>
/// <param name="rem">Reminder that this timeout represents</param>
private async Task AsyncTimerCallback(object rem)
{
var reminder = (LocalReminderData)rem;
if (!localReminders.ContainsKey(reminder.Identity) // we have already stopped this timer
|| reminder.Timer == null) // this timer was unregistered, and is waiting to be gc-ied
return;
ticksDeliveredStat.Increment();
await reminder.OnTimerTick(tardinessStat, Logger);
}
#region Utility (less useful) methods
private async Task DoResponsibilitySanityCheck(GrainReference grainRef, string debugInfo)
{
switch (Status)
{
case GrainServiceStatus.Booting:
// if service didn't finish the initial load, it could still be loading normally or it might have already
// failed a few attempts and callers should not be hold waiting for it to complete
var task = this.startedTask.Task;
if (task.IsCompleted)
{
// task at this point is already Faulted
await task;
}
else
{
try
{
// wait for the initial load task to complete (with a timeout)
await task.WithTimeout(InitialReadMaxWaitTimeForUpdates);
}
catch (TimeoutException ex)
{
throw new OrleansException("Reminder Service is still initializing and it is taking a long time. Please retry again later.", ex);
}
}
break;
case GrainServiceStatus.Started:
break;
case GrainServiceStatus.Stopped:
throw new OperationCanceledException("ReminderService has been stopped.");
default:
throw new InvalidOperationException("status");
}
if (!RingRange.InRange(grainRef))
{
Logger.Warn(ErrorCode.RS_NotResponsible, "I shouldn't have received request '{0}' for {1}. It is not in my responsibility range: {2}",
debugInfo, grainRef.ToDetailedString(), RingRange);
// For now, we still let the caller proceed without throwing an exception... the periodical mechanism will take care of reminders being registered at the wrong silo
// otherwise, we can either reject the request, or re-route the request
}
}
// Note: The list of reminders can be huge in production!
private void PrintReminders(string msg = null)
{
if (!Logger.IsVerbose3) return;
var str = String.Format("{0}{1}{2}", (msg ?? "Current list of reminders:"), Environment.NewLine,
Utils.EnumerableToString(localReminders, null, Environment.NewLine));
Logger.Verbose3(str);
}
#endregion
private class LocalReminderData
{
private readonly IRemindable remindable;
private Stopwatch stopwatch;
private readonly DateTime firstTickTime; // time for the first tick of this reminder
private readonly TimeSpan period;
private GrainReference GrainRef { get { return Identity.GrainRef; } }
private string ReminderName { get { return Identity.ReminderName; } }
internal ReminderIdentity Identity { get; private set; }
internal string ETag;
internal IGrainTimer Timer;
internal long LocalSequenceNumber; // locally, we use this for resolving races between the periodic table reader, and any concurrent local register/unregister requests
internal LocalReminderData(ReminderEntry entry)
{
Identity = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
firstTickTime = entry.StartAt;
period = entry.Period;
remindable = entry.GrainRef.Cast<IRemindable>();
ETag = entry.ETag;
LocalSequenceNumber = -1;
}
public void StartTimer(OrleansTaskScheduler scheduler, Func<object, Task> asyncCallback, Logger Logger)
{
StopReminder(Logger); // just to make sure.
var dueTimeSpan = CalculateDueTime();
Timer = GrainTimer.FromTaskCallback(scheduler, asyncCallback, this, dueTimeSpan, period, name: ReminderName);
if (Logger.IsVerbose) Logger.Verbose("Reminder {0}, Due time{1}", this, dueTimeSpan);
Timer.Start();
}
public void StopReminder(Logger Logger)
{
if (Timer != null)
Timer.Dispose();
Timer = null;
}
private TimeSpan CalculateDueTime()
{
TimeSpan dueTimeSpan;
var now = DateTime.UtcNow;
if (now < firstTickTime) // if the time for first tick hasn't passed yet
{
dueTimeSpan = firstTickTime.Subtract(now); // then duetime is duration between now and the first tick time
}
else // the first tick happened in the past ... compute duetime based on the first tick time, and period
{
// formula used:
// due = period - 'time passed since last tick (==sinceLast)'
// due = period - ((Now - FirstTickTime) % period)
// explanation of formula:
// (Now - FirstTickTime) => gives amount of time since first tick happened
// (Now - FirstTickTime) % period => gives amount of time passed since the last tick should have triggered
var sinceFirstTick = now.Subtract(firstTickTime);
var sinceLastTick = TimeSpan.FromTicks(sinceFirstTick.Ticks % period.Ticks);
dueTimeSpan = period.Subtract(sinceLastTick);
// in corner cases, dueTime can be equal to period ... so, take another mod
dueTimeSpan = TimeSpan.FromTicks(dueTimeSpan.Ticks % period.Ticks);
}
return dueTimeSpan;
}
public async Task OnTimerTick(AverageTimeSpanStatistic tardinessStat, Logger Logger)
{
var before = DateTime.UtcNow;
var status = TickStatus.NewStruct(firstTickTime, period, before);
if (Logger.IsVerbose2) Logger.Verbose2("Triggering tick for {0}, status {1}, now {2}", this.ToString(), status, before);
try
{
if (null != stopwatch)
{
stopwatch.Stop();
var tardiness = stopwatch.Elapsed - period;
tardinessStat.AddSample(Math.Max(0, tardiness.Ticks));
}
await remindable.ReceiveReminder(ReminderName, status);
if (null == stopwatch)
stopwatch = new Stopwatch();
stopwatch.Restart();
var after = DateTime.UtcNow;
if (Logger.IsVerbose2)
Logger.Verbose2("Tick triggered for {0}, dt {1} sec, next@~ {2}", this.ToString(), (after - before).TotalSeconds,
// the next tick isn't actually scheduled until we return control to
// AsyncSafeTimer but we can approximate it by adding the period of the reminder
// to the after time.
after + period);
}
catch (Exception exc)
{
var after = DateTime.UtcNow;
Logger.Error(
ErrorCode.RS_Tick_Delivery_Error,
String.Format("Could not deliver reminder tick for {0}, next {1}.", this.ToString(), after + period),
exc);
// What to do with repeated failures to deliver a reminder's ticks?
}
}
public override string ToString()
{
return string.Format("[{0}, {1}, {2}, {3}, {4}, {5}, {6}]",
ReminderName,
GrainRef.ToDetailedString(),
period,
LogFormatter.PrintDate(firstTickTime),
ETag,
LocalSequenceNumber,
Timer == null ? "Not_ticking" : "Ticking");
}
}
private struct ReminderIdentity : IEquatable<ReminderIdentity>
{
private readonly GrainReference grainRef;
private readonly string reminderName;
public GrainReference GrainRef { get { return grainRef; } }
public string ReminderName { get { return reminderName; } }
public ReminderIdentity(GrainReference grainRef, string reminderName)
{
if (grainRef == null)
throw new ArgumentNullException("grainRef");
if (string.IsNullOrWhiteSpace(reminderName))
throw new ArgumentException("The reminder name is either null or whitespace.", "reminderName");
this.grainRef = grainRef;
this.reminderName = reminderName;
}
public bool Equals(ReminderIdentity other)
{
return grainRef.Equals(other.grainRef) && reminderName.Equals(other.reminderName);
}
public override bool Equals(object other)
{
return (other is ReminderIdentity) && Equals((ReminderIdentity)other);
}
public override int GetHashCode()
{
return unchecked((int)((uint)grainRef.GetHashCode() + (uint)reminderName.GetHashCode()));
}
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Encog.App.Analyst.Util;
using Encog.App.Generate;
using Encog.Util;
using Encog.Util.CSV;
namespace Encog.App.Analyst.Script.Prop
{
/// <summary>
/// Holds all of the properties for a script. Constants are provided to define
/// "well known" properties.
/// </summary>
public class ScriptProperties
{
/// <summary>
/// Property for: "HEADER:DATASOURCE_sourceFile".
/// </summary>
public const String HeaderDatasourceSourceFile = "HEADER:DATASOURCE_sourceFile";
/// <summary>
/// Property for: "HEADER:DATASOURCE_rawFile".
/// </summary>
public const String HeaderDatasourceRawFile = "HEADER:DATASOURCE_rawFile";
/// <summary>
/// Property for: "HEADER:DATASOURCE_sourceHeaders".
/// </summary>
public const String HeaderDatasourceSourceHeaders = "HEADER:DATASOURCE_sourceHeaders";
/// <summary>
/// Property for: "SETUP:CONFIG_maxClassCount".
/// </summary>
public const String SetupConfigMaxClassCount = "SETUP:CONFIG_maxClassCount";
/// <summary>
/// Property for: = "SETUP:CONFIG_allowedClasses".
/// </summary>
public const String SetupConfigAllowedClasses = "SETUP:CONFIG_allowedClasses";
/// <summary>
/// Property for: "SETUP:CONFIG_inputHeaders".
/// </summary>
public const String SetupConfigInputHeaders = "SETUP:CONFIG_inputHeaders";
/// <summary>
/// Property for: "SETUP:CONFIG_csvFormat".
/// </summary>
public const String SetupConfigCSVFormat = "SETUP:CONFIG_csvFormat";
/// <summary>
/// Property for: "DATA:CONFIG_goal".
/// </summary>
public const String DataConfigGoal = "DATA:CONFIG_goal";
/// <summary>
/// Property for: "NORMALIZE:CONFIG_sourceFile".
/// </summary>
public const String NormalizeConfigSourceFile = "NORMALIZE:CONFIG_sourceFile";
/// <summary>
/// Property for: "NORMALIZE:CONFIG_targetFile".
/// </summary>
public const String NormalizeConfigTargetFile = "NORMALIZE:CONFIG_targetFile";
/// <summary>
/// Property for: "BALANCE:CONFIG_sourceFile".
/// </summary>
public const String BalanceConfigSourceFile = "BALANCE:CONFIG_sourceFile";
/// <summary>
/// Property for: "BALANCE:CONFIG_targetFile".
/// </summary>
public const String BalanceConfigTargetFile = "BALANCE:CONFIG_targetFile";
/// <summary>
/// Property for: "NORMALIZE:CONFIG_missingValues."
/// </summary>
public const String NormalizeMissingValues = "NORMALIZE:CONFIG_missingValues";
/// <summary>
/// Property for: "BALANCE:CONFIG_balanceField".
/// </summary>
public const String BalanceConfigBalanceField = "BALANCE:CONFIG_balanceField";
/// <summary>
/// Property for: "BALANCE:CONFIG_countPer".
/// </summary>
public const String BalanceConfigCountPer = "BALANCE:CONFIG_countPer";
/// <summary>
/// Property for: "RANDOMIZE:CONFIG_sourceFile".
/// </summary>
public const String RandomizeConfigSourceFile = "RANDOMIZE:CONFIG_sourceFile";
/// <summary>
/// Property for: "RANDOMIZE:CONFIG_targetFile".
/// </summary>
public const String RandomizeConfigTargetFile = "RANDOMIZE:CONFIG_targetFile";
/// <summary>
/// Property for: "SEGREGATE:CONFIG_sourceFile".
/// </summary>
public const String SegregateConfigSourceFile = "SEGREGATE:CONFIG_sourceFile";
/// <summary>
/// Property for: "GENERATE:CONFIG_sourceFile".
/// </summary>
public const String GenerateConfigSourceFile = "GENERATE:CONFIG_sourceFile";
/// <summary>
/// Property for: "GENERATE:CONFIG_targetFile".
/// </summary>
public const String GenerateConfigTargetFile = "GENERATE:CONFIG_targetFile";
/// <summary>
/// Property for: "ML:CONFIG_trainingFile".
/// </summary>
public const String MlConfigTrainingFile = "ML:CONFIG_trainingFile";
/// <summary>
/// Property for: "ML:CONFIG_evalFile".
/// </summary>
public const String MlConfigEvalFile = "ML:CONFIG_evalFile";
/// <summary>
/// Property for: "ML:CONFIG_machineLearningFile".
/// </summary>
public const String MlConfigMachineLearningFile = "ML:CONFIG_machineLearningFile";
/// <summary>
/// Property for: "ML:CONFIG_outputFile".
/// </summary>
public const String MlConfigOutputFile = "ML:CONFIG_outputFile";
/// <summary>
/// Property for: = ML:CONFIG_type".
/// </summary>
public const String MlConfigType = "ML:CONFIG_type";
/// <summary>
/// Property for: "ML:CONFIG_architecture".
/// </summary>
public const String MlConfigArchitecture = "ML:CONFIG_architecture";
/// <summary>
/// Property for "ML:CONFIG_query"
/// </summary>
public const String MLConfigQuery = "ML:CONFIG_query";
/// <summary>
/// Property for: "ML:TRAIN_type".
/// </summary>
public const String MlTrainType = "ML:TRAIN_type";
/// <summary>
/// Property for: "ML:TRAIN_arguments".
/// </summary>
public const String MlTrainArguments = "ML:TRAIN_arguments";
/// <summary>
/// Property for: "ML:TRAIN_targetError".
/// </summary>
public const String MlTrainTargetError = "ML:TRAIN_targetError";
/// <summary>
/// Property for: "ML:TRAIN_cross".
/// </summary>
public const String MlTrainCross = "ML:TRAIN_cross";
/// <summary>
/// Property for: "CLUSTER:CONFIG_sourceFile".
/// </summary>
public const String ClusterConfigSourceFile = "CLUSTER:CONFIG_sourceFile";
/// <summary>
/// Property for: "CLUSTER:CONFIG_targetFile".
/// </summary>
public const String ClusterConfigTargetFile = "CLUSTER:CONFIG_targetFile";
/// <summary>
/// Property for: "CLUSTER:CONFIG_type".
/// </summary>
public const String ClusterConfigType = "CLUSTER:CONFIG_type";
/// <summary>
/// Property for: "CLUSTER:CONFIG_clusters".
/// </summary>
public const String ClusterConfigClusters = "CLUSTER:CONFIG_clusters";
/// <summary>
/// Property for: "GENERATE:CONFIG_targetLanguage".
/// </summary>
public const String CODE_CONFIG_TARGET_LANGUAGE
= "CODE:CONFIG_targetLanguage";
/// <summary>
/// Property for: "GENERATE:CONFIG_targetFile".
/// </summary>
public const String CODE_CONFIG_TARGET_FILE
= "CODE:CONFIG_targetFile";
/// <summary>
/// Property for: "GENERATE:CONFIG_embedData".
/// </summary>
public const String CODE_CONFIG_EMBED_DATA
= "CODE:CONFIG_embedData";
/// <summary>
/// Property for: "PROCESS:CONFIG,sourceFile".
/// </summary>
public const String PROCESS_CONFIG_SOURCE_FILE =
"PROCESS:CONFIG_sourceFile";
/// <summary>
/// Property for: "PROCESS:CONFIG,targetFile".
/// </summary>
public const String PROCESS_CONFIG_TARGET_FILE =
"PROCESS:CONFIG_targetFile";
/// <summary>
/// Property for: "PROCESS:CONFIG,backwardSize".
/// </summary>
public const String PROCESS_CONFIG_BACKWARD_SIZE =
"PROCESS:CONFIG_backwardSize";
/// <summary>
/// Property for: "PROCESS:CONFIG,forwardSize".
/// </summary>
public const String PROCESS_CONFIG_FORWARD_SIZE =
"PROCESS:CONFIG_forwardSize";
/// <summary>
/// Properties are stored in this map.
/// </summary>
private readonly IDictionary<String, String> _data;
/// <summary>
/// Construct the object.
/// </summary>
public ScriptProperties()
{
_data = new Dictionary<String, String>();
}
/// <summary>
/// Get all filenames.
/// </summary>
public IList<String> Filenames
{
get
{
return (from key in _data.Keys
where key.StartsWith("SETUP:FILENAMES")
let index = key.IndexOf('_')
where index != -1
select key.Substring(index + 1)).ToList();
}
}
/// <summary>
/// Convert a key to the dot form.
/// </summary>
/// <param name="str">The key form.</param>
/// <returns>The dot form.</returns>
public static String ToDots(String str)
{
int index1 = str.IndexOf(':');
if (index1 == -1)
{
return null;
}
int index2 = str.IndexOf('_');
if (index2 == -1)
{
return null;
}
String section = str.Substring(0, (index1) - (0));
String subSection = str.Substring(index1 + 1, (index2) - (index1 + 1));
String name = str.Substring(index2 + 1);
return section + "." + subSection + "." + name;
}
/// <summary>
/// Clear out all filenames.
/// </summary>
public void ClearFilenames()
{
var array = new string[_data.Keys.Count];
int idx = 0;
foreach (string item in _data.Keys)
{
array[idx++] = item;
}
foreach (string element in array)
{
string key = element;
if (key.StartsWith("SETUP:FILENAMES"))
{
_data.Remove(key);
}
}
}
/// <summary>
/// Get a filename.
/// </summary>
/// <param name="file">The file.</param>
/// <returns>The filename.</returns>
public String GetFilename(String file)
{
String key2 = "SETUP:FILENAMES_" + file;
if (!_data.ContainsKey(key2))
{
throw new AnalystError("Undefined file: " + file);
}
return _data[key2];
}
/// <summary>
/// Get a property as an object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <returns>The property value.</returns>
public Object GetProperty(String name)
{
return _data[name];
}
/// <summary>
/// Get a property as a boolean.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A boolean value.</returns>
public bool GetPropertyBoolean(String name)
{
if (!_data.ContainsKey(name))
{
return false;
}
return _data[name].ToLower().StartsWith("t");
}
/// <summary>
/// Get a property as a format.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A format value.</returns>
public CSVFormat GetPropertyCSVFormat(String name)
{
String v = _data[name];
AnalystFileFormat code = ConvertStringConst
.String2AnalystFileFormat(v);
return ConvertStringConst.ConvertToCSVFormat(code);
}
/// <summary>
/// Get a property as a double.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A double value.</returns>
public double GetPropertyDouble(String name)
{
String v = _data[name];
return CSVFormat.EgFormat.Parse(v);
}
/// <summary>
/// Get a property as a file.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A file value.</returns>
public String GetPropertyFile(String name)
{
return _data[name];
}
/// <summary>
/// Get a property as a format.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A format value.</returns>
public AnalystFileFormat GetPropertyFormat(String name)
{
String v = _data[name];
return ConvertStringConst.String2AnalystFileFormat(v);
}
/// <summary>
/// Get a property as a int.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A int value.</returns>
public int GetPropertyInt(String name)
{
try
{
String v = _data[name];
if (v == null)
{
return 0;
}
return Int32.Parse(v);
}
catch (FormatException ex)
{
throw new AnalystError(ex);
}
}
/// <summary>
/// Get a property as a string.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <returns>The property value.</returns>
public String GetPropertyString(String name)
{
if (!_data.ContainsKey(name))
{
return null;
}
return _data[name];
}
/// <summary>
/// Get a property as a url.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A url value.</returns>
public Uri GetPropertyURL(String name)
{
try
{
return new Uri(_data[name]);
}
catch (UriFormatException e)
{
throw new AnalystError(e);
}
}
/// <summary>
/// Perform a revert.
/// </summary>
/// <param name="revertedData">The source data to revert from.</param>
public void PerformRevert(IDictionary<String, String> revertedData)
{
_data.Clear();
EngineArray.PutAll(revertedData, _data);
}
/// <summary>
/// Prepare a revert.
/// </summary>
/// <returns>Data that can be used to revert properties.</returns>
public IDictionary<String, String> PrepareRevert()
{
IDictionary<String, String> result = new Dictionary<String, String>();
EngineArray.PutAll(_data, result);
return result;
}
/// <summary>
/// Set a filename.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="v">The value.</param>
public void SetFilename(String key, String v)
{
String key2 = "SETUP:FILENAMES_" + key;
_data[key2] = v;
}
/// <summary>
/// Set a property as a target language.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="targetLanguage">The target language.</param>
public void SetProperty(String name, TargetLanguage targetLanguage)
{
_data[name] = targetLanguage.ToString().ToUpper();
}
/// <summary>
/// Set the property to a format.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="format">The value of the property.</param>
public void SetProperty(String name,
AnalystFileFormat format)
{
_data[name] = ConvertStringConst.AnalystFileFormat2String(format);
}
/// <summary>
/// Set a property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="v">The value.</param>
public void SetProperty(String name, AnalystGoal v)
{
switch (v)
{
case AnalystGoal.Classification:
_data[name] = "classification";
break;
case AnalystGoal.Regression:
_data[name] = "regression";
break;
default:
_data[name] = "";
break;
}
}
/// <summary>
/// Set a property as a boolean.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="b">The value to set.</param>
public void SetProperty(String name, bool b)
{
if (b)
{
_data[name] = "t";
}
else
{
_data[name] = "f";
}
}
/// <summary>
/// Set a property as a double.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="d">The value.</param>
public void SetProperty(String name, double d)
{
_data[name] = CSVFormat.EgFormat.Format(d, EncogFramework.DefaultPrecision);
}
/// <summary>
/// Get a property as an object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="f">The filename value.</param>
public void SetProperty(String name, FileInfo f)
{
_data[name] = f.ToString();
}
/// <summary>
/// Set a property to an int.
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="i">The value.</param>
public void SetProperty(String name, int i)
{
_data[name] = ("" + i);
}
/// <summary>
/// Set the property to the specified value.
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="v">The property value.</param>
public void SetProperty(String name, String v)
{
_data[name] = v;
}
/// <summary>
/// Get a property as an object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="url">The url of the property.</param>
public void SetProperty(String name, Uri url)
{
_data[name] = url.ToString();
}
/// <summary>
/// </summary>
public override sealed String ToString()
{
var result = new StringBuilder("[");
result.Append(GetType().Name);
result.Append(" :");
result.Append(_data);
result.Append("]");
return result.ToString();
}
}
}
| |
// 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;
using System.Globalization;
using System.Diagnostics;
namespace System.Reflection.Emit
{
internal sealed class TypeBuilderInstantiation : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo? typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Static Members
internal static Type MakeGenericType(Type type, Type[] typeArguments)
{
Debug.Assert(type != null, "this is only called from RuntimeType.MakeGenericType and TypeBuilder.MakeGenericType so 'type' cannot be null");
if (!type.IsGenericTypeDefinition)
throw new InvalidOperationException();
if (typeArguments == null)
throw new ArgumentNullException(nameof(typeArguments));
foreach (Type t in typeArguments)
{
if (t == null)
throw new ArgumentNullException(nameof(typeArguments));
}
return new TypeBuilderInstantiation(type, typeArguments);
}
#endregion
#region Private Data Members
private Type m_type;
private Type[] m_inst;
private string? m_strFullQualName;
internal Hashtable m_hashtable;
#endregion
#region Constructor
private TypeBuilderInstantiation(Type type, Type[] inst)
{
m_type = type;
m_inst = inst;
m_hashtable = new Hashtable();
}
#endregion
#region Object Overrides
public override string ToString()
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString)!;
}
#endregion
#region MemberInfo Overrides
public override Type? DeclaringType => m_type.DeclaringType;
public override Type? ReflectedType => m_type.ReflectedType;
public override string Name => m_type.Name;
public override Module Module => m_type.Module;
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*", this, 0)!;
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0)!;
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0)!;
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
string s = rank == 1 ?
"[]" :
"[" + new string(',', rank - 1) + "]";
return SymbolType.FormCompoundType(s, this, 0)!;
}
public override Guid GUID => throw new NotSupportedException();
public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly => m_type.Assembly;
public override RuntimeTypeHandle TypeHandle => throw new NotSupportedException();
public override string? FullName => m_strFullQualName ??= TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
public override string? Namespace => m_type.Namespace;
public override string? AssemblyQualifiedName => TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName);
private Type Substitute(Type[] substitutes)
{
Type[] inst = GetGenericArguments();
Type[] instSubstituted = new Type[inst.Length];
for (int i = 0; i < instSubstituted.Length; i++)
{
Type t = inst[i];
if (t is TypeBuilderInstantiation tbi)
{
instSubstituted[i] = tbi.Substitute(substitutes);
}
else if (t is GenericTypeParameterBuilder)
{
// Substitute
instSubstituted[i] = substitutes[t.GenericParameterPosition];
}
else
{
instSubstituted[i] = t;
}
}
return GetGenericTypeDefinition().MakeGenericType(instSubstituted);
}
public override Type? BaseType
{
// B<A,B,C>
// D<T,S> : B<S,List<T>,char>
// D<string,int> : B<int,List<string>,char>
// D<S,T> : B<T,List<S>,char>
// D<S,string> : B<string,List<S>,char>
get
{
Type? typeBldrBase = m_type.BaseType;
if (typeBldrBase == null)
return null;
TypeBuilderInstantiation? typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation;
if (typeBldrBaseAs == null)
return typeBldrBase;
return typeBldrBaseAs.Substitute(GetGenericArguments());
}
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(string name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; }
public override bool IsTypeDefinition => false;
public override bool IsSZArray => false;
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType => this;
public override Type[] GetGenericArguments() { return m_inst; }
public override bool IsGenericTypeDefinition => false;
public override bool IsGenericType => true;
public override bool IsConstructedGenericType => true;
public override bool IsGenericParameter => false;
public override int GenericParameterPosition => throw new InvalidOperationException();
protected override bool IsValueTypeImpl() { return m_type.IsValueType; }
public override bool ContainsGenericParameters
{
get
{
for (int i = 0; i < m_inst.Length; i++)
{
if (m_inst[i].ContainsGenericParameters)
return true;
}
return false;
}
}
public override MethodBase? DeclaringMethod => null;
public override Type GetGenericTypeDefinition() { return m_type; }
public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); }
public override bool IsAssignableFrom(Type? c) { throw new NotSupportedException(); }
public override bool IsSubclassOf(Type c)
{
throw new NotSupportedException();
}
#endregion
#region ICustomAttributeProvider Implementation
public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using PrimerProObjects;
using GenLib;
using PrimerProLocalization;
namespace PrimerProForms
{
/// <summary>
/// Summary description for FormBuildableWordsWL.
/// </summary>
public class FormBuildableWordsWL : System.Windows.Forms.Form
{
private System.Windows.Forms.Label labTitle;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label labGrapheme;
private System.Windows.Forms.TextBox tbGraphemes;
private System.Windows.Forms.Button btnSO;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private Label labHighlight;
private TextBox tbHighlights;
private CheckBox chkBrowseView;
private Button btnGraphemes;
private Button btnHighlight;
private GraphemeInventory m_GraphemeInventory;
private PSTable m_PSTable;
private Font m_Font;
private LocalizationTable m_Table; //Localization table
private string m_Lang; //UI language
private ArrayList m_Graphemes;
private ArrayList m_Highlights;
private bool m_BrowseView;
private SearchOptions m_SearchOptions;
public FormBuildableWordsWL(GraphemeInventory gi, GraphemeTaughtOrder gto, PSTable pst, Font fnt)
{
InitializeComponent();
m_GraphemeInventory = gi;
m_PSTable = pst;
m_Font = fnt;
this.tbGraphemes.Text = this.GetGraphemesTaught(gto);
this.tbHighlights.Text = "";
this.chkBrowseView.Checked = false;
this.tbGraphemes.Font = m_Font;
this.tbHighlights.Font = m_Font;
m_Table = null;
m_Lang = "";
}
public FormBuildableWordsWL(GraphemeInventory gi, GraphemeTaughtOrder gto, PSTable pst, Font fnt,
LocalizationTable table, string lang)
{
InitializeComponent();
m_GraphemeInventory = gi;
m_PSTable = pst;
m_Font = fnt;
m_Table = table;
m_Lang = lang;
this.tbGraphemes.Text = this.GetGraphemesTaught(gto);
this.tbHighlights.Text = "";
this.chkBrowseView.Checked = false;
this.tbGraphemes.Font = m_Font;
this.tbHighlights.Font = m_Font;
this.UpdateFormForLocalization(m_Table);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(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(FormBuildableWordsWL));
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.labTitle = new System.Windows.Forms.Label();
this.labGrapheme = new System.Windows.Forms.Label();
this.tbGraphemes = new System.Windows.Forms.TextBox();
this.btnSO = new System.Windows.Forms.Button();
this.labHighlight = new System.Windows.Forms.Label();
this.tbHighlights = new System.Windows.Forms.TextBox();
this.chkBrowseView = new System.Windows.Forms.CheckBox();
this.btnGraphemes = new System.Windows.Forms.Button();
this.btnHighlight = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnOK.Location = new System.Drawing.Point(484, 206);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(83, 28);
this.btnOK.TabIndex = 9;
this.btnOK.Text = "OK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCancel.Location = new System.Drawing.Point(583, 206);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(84, 28);
this.btnCancel.TabIndex = 10;
this.btnCancel.Text = "Cancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// labTitle
//
this.labTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labTitle.Location = new System.Drawing.Point(100, 14);
this.labTitle.Name = "labTitle";
this.labTitle.Size = new System.Drawing.Size(567, 48);
this.labTitle.TabIndex = 0;
this.labTitle.Text = "List only graphemes (consonants and vowels) which have been taught. The grapheme" +
"s should be separated by a space. (e.g. p b m mp mb mpw mbw a e i o u aa)";
//
// labGrapheme
//
this.labGrapheme.AutoEllipsis = true;
this.labGrapheme.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labGrapheme.Location = new System.Drawing.Point(20, 73);
this.labGrapheme.Name = "labGrapheme";
this.labGrapheme.Size = new System.Drawing.Size(75, 21);
this.labGrapheme.TabIndex = 1;
this.labGrapheme.Text = "Graphemes";
//
// tbGraphemes
//
this.tbGraphemes.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbGraphemes.Location = new System.Drawing.Point(100, 73);
this.tbGraphemes.Name = "tbGraphemes";
this.tbGraphemes.Size = new System.Drawing.Size(467, 21);
this.tbGraphemes.TabIndex = 2;
//
// btnSO
//
this.btnSO.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSO.Location = new System.Drawing.Point(103, 202);
this.btnSO.Name = "btnSO";
this.btnSO.Size = new System.Drawing.Size(200, 32);
this.btnSO.TabIndex = 8;
this.btnSO.Text = "&Search Options";
this.btnSO.Click += new System.EventHandler(this.btnSO_Click);
//
// labHighlight
//
this.labHighlight.AutoEllipsis = true;
this.labHighlight.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labHighlight.Location = new System.Drawing.Point(20, 113);
this.labHighlight.Name = "labHighlight";
this.labHighlight.Size = new System.Drawing.Size(315, 21);
this.labHighlight.TabIndex = 4;
this.labHighlight.Text = "Highlight words with these graphemes";
this.labHighlight.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// tbHighlights
//
this.tbHighlights.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbHighlights.Location = new System.Drawing.Point(358, 113);
this.tbHighlights.Name = "tbHighlights";
this.tbHighlights.Size = new System.Drawing.Size(209, 21);
this.tbHighlights.TabIndex = 5;
//
// chkBrowseView
//
this.chkBrowseView.AutoSize = true;
this.chkBrowseView.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chkBrowseView.Location = new System.Drawing.Point(103, 162);
this.chkBrowseView.Name = "chkBrowseView";
this.chkBrowseView.Size = new System.Drawing.Size(149, 19);
this.chkBrowseView.TabIndex = 7;
this.chkBrowseView.Text = "Display in &browse view";
this.chkBrowseView.UseVisualStyleBackColor = true;
this.chkBrowseView.CheckedChanged += new System.EventHandler(this.chkBrowseView_CheckedChanged);
//
// btnGraphemes
//
this.btnGraphemes.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnGraphemes.Location = new System.Drawing.Point(583, 73);
this.btnGraphemes.Name = "btnGraphemes";
this.btnGraphemes.Size = new System.Drawing.Size(150, 32);
this.btnGraphemes.TabIndex = 3;
this.btnGraphemes.Text = "Item Selection";
this.btnGraphemes.UseVisualStyleBackColor = true;
this.btnGraphemes.Click += new System.EventHandler(this.btnGraphemes_Click);
//
// btnHighlight
//
this.btnHighlight.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnHighlight.Location = new System.Drawing.Point(583, 113);
this.btnHighlight.Name = "btnHighlight";
this.btnHighlight.Size = new System.Drawing.Size(150, 32);
this.btnHighlight.TabIndex = 6;
this.btnHighlight.Text = "Item Selection";
this.btnHighlight.UseVisualStyleBackColor = true;
this.btnHighlight.Click += new System.EventHandler(this.btnHighlight_Click);
//
// FormBuildableWordsWL
//
this.AcceptButton = this.btnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(784, 269);
this.Controls.Add(this.btnHighlight);
this.Controls.Add(this.btnGraphemes);
this.Controls.Add(this.chkBrowseView);
this.Controls.Add(this.tbHighlights);
this.Controls.Add(this.labHighlight);
this.Controls.Add(this.btnSO);
this.Controls.Add(this.tbGraphemes);
this.Controls.Add(this.labGrapheme);
this.Controls.Add(this.labTitle);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FormBuildableWordsWL";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Buildable Words Search";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public ArrayList Graphemes
{
get { return m_Graphemes; }
}
public ArrayList Highlights
{
get { return m_Highlights; }
}
public bool BrowseView
{
get { return m_BrowseView; }
}
public SearchOptions SearchOptions
{
get { return m_SearchOptions; }
}
private void btnOK_Click(object sender, System.EventArgs e)
{
string strGrfs = tbGraphemes.Text.Trim();
string strHlts = tbHighlights.Text.Trim();
if (strGrfs != "")
{
m_Graphemes = Funct.ConvertStringToArrayList(strGrfs, Constants.Space.ToString());
m_Highlights = Funct.ConvertStringToArrayList(strHlts, Constants.Space.ToString());
m_BrowseView = chkBrowseView.Checked;
}
else
{
m_Graphemes = null;
m_Highlights = null;
m_BrowseView = false;
}
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
m_Graphemes = null;
m_Highlights = null;
m_BrowseView = false;
this.Close();
}
private void btnSO_Click(object sender, System.EventArgs e)
{
SearchOptions so = new SearchOptions(m_PSTable);
CodeTable ct = (CodeTable)m_PSTable;
//FormSearchOptions form = new FormSearchOptions(ct, true, false);
FormSearchOptions form = new FormSearchOptions(ct, true, false, m_Table);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
so.PS = form.PSTE;
so.IsRootOnly = form.IsRootOnly;
so.IsIdenticalVowelsInRoot = form.IsIdenticalVowelsInRoot;
so.IsIdenticalVowelsInWord = form.IsIdenticalVowelsInWord;
so.IsBrowseView = form.IsBrowseView;
so.WordCVShape = form.WordCVShape;
so.RootCVShape = form.RootCVShape;
so.MinSyllables = form.MaxSyllables;
so.MaxSyllables = form.MaxSyllables;
so.WordPosition = form.WordPosition;
so.RootPosition = form.RootPosition;
m_SearchOptions = so;
}
}
private void chkBrowseView_CheckedChanged(object sender, EventArgs e)
{
if (chkBrowseView.Checked)
tbHighlights.Enabled = false;
else tbHighlights.Enabled = true;
}
private void btnGraphemes_Click(object sender, EventArgs e)
{
GraphemeInventory gi = m_GraphemeInventory;
ArrayList alGI = new ArrayList();
ArrayList alSelection = new ArrayList();
for (int i = 0; i < gi.ConsonantCount(); i++)
alGI.Add(gi.GetConsonant(i).Symbol);
for (int i = 0; i < gi.VowelCount(); i++)
alGI.Add(gi.GetVowel(i).Symbol);
for (int i = 0; i < gi.ToneCount(); i++)
alGI.Add(gi.GetTone(i).Symbol);
for (int i = 0; i < gi.SyllographCount(); i++)
alGI.Add(gi.GetSyllograph(i).Symbol);
alSelection = Funct.ConvertStringToArrayList(this.tbGraphemes.Text, Constants.Space.ToString());
if ((m_Lang != "") && (m_Lang == OptionList.kFrench))
{
FormItemSelectionFrench form = new FormItemSelectionFrench(alGI, alSelection,labGrapheme.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
string strGraphemes = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
this.tbGraphemes.Text = strGraphemes;
}
}
else if ((m_Lang != "") && (m_Lang == OptionList.kSpanish))
{
FormItemSelectionSpanish form = new FormItemSelectionSpanish(alGI, alSelection, labGrapheme.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
string strGraphemes = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
this.tbGraphemes.Text = strGraphemes;
}
}
else
{
FormItemSelection form = new FormItemSelection(alGI, alSelection, labGrapheme.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
string strGraphemes = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
this.tbGraphemes.Text = strGraphemes;
}
}
}
private void btnHighlight_Click(object sender, EventArgs e)
{
ArrayList alAvailable = Funct.ConvertStringToArrayList(tbGraphemes.Text, Constants.Space.ToString());
ArrayList alHighlight = Funct.ConvertStringToArrayList(tbHighlights.Text, Constants.Space.ToString());
string strSymbol = "";
// remove underscores
for (int i = 0; i < alAvailable.Count; i++)
{
strSymbol = alAvailable[i].ToString();
strSymbol = strSymbol.Replace(Syllable.Underscore, "");
alAvailable[i] = strSymbol;
}
if ((m_Lang != "") && (m_Lang == OptionList.kFrench))
{
FormItemSelectionFrench form = new FormItemSelectionFrench(alAvailable, alHighlight, labHighlight.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
this.tbHighlights.Text = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
}
}
else if ((m_Lang != "") && (m_Lang == OptionList.kSpanish))
{
FormItemSelectionSpanish form = new FormItemSelectionSpanish(alAvailable, alHighlight, labHighlight.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
this.tbHighlights.Text = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
}
}
else
{
FormItemSelection form = new FormItemSelection(alAvailable, alHighlight, labHighlight.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
this.tbHighlights.Text = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
}
}
}
private string GetGraphemesTaught(GraphemeTaughtOrder gto)
{
string strText = "";
for (int i = 0; i < gto.Count(); i++)
{
strText += gto.GetGrapheme(i).Trim() + Constants.Space;
}
strText = strText.Trim();
return strText;
}
private void UpdateFormForLocalization(LocalizationTable table)
{
string strText = "";
strText = table.GetForm("FormBuildableWordsWLT");
if (strText != "")
this.Text = strText;
strText = table.GetForm("FormBuildableWordsWL0");
if (strText != "")
this.labTitle.Text = strText;
strText = table.GetForm("FormBuildableWordsWL1");
if (strText != "")
this.labGrapheme.Text = strText;
strText = table.GetForm("FormBuildableWordsWL3");
if (strText != "")
this.btnGraphemes.Text = strText;
strText = table.GetForm("FormBuildableWordsWL4");
if (strText != "")
this.labHighlight.Text = strText;
strText = table.GetForm("FormBuildableWordsWL6");
if (strText != "")
this.btnHighlight.Text = strText;
strText = table.GetForm("FormBuildableWordsWL7");
if (strText != "")
this.chkBrowseView.Text = strText;
strText = table.GetForm("FormBuildableWordsWL8");
if (strText != "")
this.btnSO.Text = strText;
strText = table.GetForm("FormBuildableWordsWL9");
if (strText != "")
this.btnOK.Text = strText;
strText = table.GetForm("FormBuildableWordsWL10");
if (strText != "")
this.btnCancel.Text = strText;
return;
}
}
}
| |
using System;
using System.Collections.Generic;
using Orleans.Runtime;
using Orleans.Streams;
namespace Orleans.Providers.Streams.Common
{
internal class CacheBucket
{
// For backpressure detection we maintain a histogram of 10 buckets.
// Every buckets recors how many items are in the cache in that bucket
// and how many cursors are poinmting to an item in that bucket.
// We update the NumCurrentItems when we add and remove cache item (potentially opening or removing a bucket)
// We update NumCurrentCursors every time we move a cursor
// If the first (most outdated bucket) has at least one cursor pointing to it, we say we are under back pressure (in a full cache).
internal int NumCurrentItems { get; private set; }
internal int NumCurrentCursors { get; private set; }
internal void UpdateNumItems(int val)
{
NumCurrentItems = NumCurrentItems + val;
}
internal void UpdateNumCursors(int val)
{
NumCurrentCursors = NumCurrentCursors + val;
}
}
internal class SimpleQueueCacheItem
{
internal IBatchContainer Batch;
internal bool DeliveryFailure;
internal StreamSequenceToken SequenceToken;
internal CacheBucket CacheBucket;
}
public class SimpleQueueCache : IQueueCache
{
private readonly LinkedList<SimpleQueueCacheItem> cachedMessages;
private StreamSequenceToken lastSequenceTokenAddedToCache;
private readonly int maxCacheSize;
private readonly Logger logger;
private readonly List<CacheBucket> cacheCursorHistogram; // for backpressure detection
private const int NUM_CACHE_HISTOGRAM_BUCKETS = 10;
private readonly int CACHE_HISTOGRAM_MAX_BUCKET_SIZE;
public int Size
{
get { return cachedMessages.Count; }
}
public int GetMaxAddCount()
{
return CACHE_HISTOGRAM_MAX_BUCKET_SIZE;
}
public SimpleQueueCache(int cacheSize, Logger logger)
{
cachedMessages = new LinkedList<SimpleQueueCacheItem>();
maxCacheSize = cacheSize;
this.logger = logger;
cacheCursorHistogram = new List<CacheBucket>();
CACHE_HISTOGRAM_MAX_BUCKET_SIZE = Math.Max(cacheSize / NUM_CACHE_HISTOGRAM_BUCKETS, 1); // we have 10 buckets
}
public virtual bool IsUnderPressure()
{
if (cachedMessages.Count == 0) return false; // empty cache
if (Size < maxCacheSize) return false; // there is still space in cache
if (cacheCursorHistogram.Count == 0) return false; // no cursors yet - zero consumers basically yet.
// cache is full. Check how many cursors we have in the oldest bucket.
int numCursorsInLastBucket = cacheCursorHistogram[0].NumCurrentCursors;
return numCursorsInLastBucket > 0;
}
public virtual bool TryPurgeFromCache(out IList<IBatchContainer> purgedItems)
{
purgedItems = null;
if (cachedMessages.Count == 0) return false; // empty cache
if (cacheCursorHistogram.Count == 0) return false; // no cursors yet - zero consumers basically yet.
if (cacheCursorHistogram[0].NumCurrentCursors > 0) return false; // consumers are still active in the oldest bucket - fast path
var allItems = new List<IBatchContainer>();
while (cacheCursorHistogram.Count > 0 && cacheCursorHistogram[0].NumCurrentCursors == 0)
{
List<IBatchContainer> items = DrainBucket(cacheCursorHistogram[0]);
allItems.AddRange(items);
cacheCursorHistogram.RemoveAt(0); // remove the last bucket
}
purgedItems = allItems;
return true;
}
private List<IBatchContainer> DrainBucket(CacheBucket bucket)
{
var itemsToRelease = new List<IBatchContainer>(bucket.NumCurrentItems);
// walk all items in the cache starting from last
// and remove from the cache the oness that reside in the given bucket until we jump to a next bucket
while (bucket.NumCurrentItems > 0)
{
SimpleQueueCacheItem item = cachedMessages.Last.Value;
if (item.CacheBucket.Equals(bucket))
{
if (!item.DeliveryFailure)
{
itemsToRelease.Add(item.Batch);
}
bucket.UpdateNumItems(-1);
cachedMessages.RemoveLast();
}
else
{
// this item already points into the next bucket, so stop.
break;
}
}
return itemsToRelease;
}
public virtual void AddToCache(IList<IBatchContainer> msgs)
{
if (msgs == null) throw new ArgumentNullException("msgs");
Log(logger, "AddToCache: added {0} items to cache.", msgs.Count);
foreach (var message in msgs)
{
Add(message, message.SequenceToken);
lastSequenceTokenAddedToCache = message.SequenceToken;
}
}
public virtual IQueueCacheCursor GetCacheCursor(IStreamIdentity streamIdentity, StreamSequenceToken token)
{
if (token != null && !(token is EventSequenceToken))
{
// Null token can come from a stream subscriber that is just interested to start consuming from latest (the most recent event added to the cache).
throw new ArgumentOutOfRangeException("token", "token must be of type EventSequenceToken");
}
var cursor = new SimpleQueueCacheCursor(this, streamIdentity, logger);
InitializeCursor(cursor, token, true);
return cursor;
}
internal void InitializeCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken sequenceToken, bool enforceSequenceToken)
{
Log(logger, "InitializeCursor: {0} to sequenceToken {1}", cursor, sequenceToken);
if (cachedMessages.Count == 0) // nothing in cache
{
StreamSequenceToken tokenToReset = sequenceToken ?? (lastSequenceTokenAddedToCache != null ? ((EventSequenceToken)lastSequenceTokenAddedToCache).NextSequenceNumber() : null);
ResetCursor(cursor, tokenToReset);
return;
}
// if offset is not set, iterate from newest (first) message in cache, but not including the irst message itself
if (sequenceToken == null)
{
StreamSequenceToken tokenToReset = lastSequenceTokenAddedToCache != null ? ((EventSequenceToken)lastSequenceTokenAddedToCache).NextSequenceNumber() : null;
ResetCursor(cursor, tokenToReset);
return;
}
if (sequenceToken.Newer(cachedMessages.First.Value.SequenceToken)) // sequenceId is too new to be in cache
{
ResetCursor(cursor, sequenceToken);
return;
}
LinkedListNode<SimpleQueueCacheItem> lastMessage = cachedMessages.Last;
// Check to see if offset is too old to be in cache
if (sequenceToken.Older(lastMessage.Value.SequenceToken))
{
if (enforceSequenceToken)
{
// throw cache miss exception
throw new QueueCacheMissException(sequenceToken, cachedMessages.Last.Value.SequenceToken, cachedMessages.First.Value.SequenceToken);
}
sequenceToken = lastMessage.Value.SequenceToken;
}
// Now the requested sequenceToken is set and is also within the limits of the cache.
// Find first message at or below offset
// Events are ordered from newest to oldest, so iterate from start of list until we hit a node at a previous offset, or the end.
LinkedListNode<SimpleQueueCacheItem> node = cachedMessages.First;
while (node != null && node.Value.SequenceToken.Newer(sequenceToken))
{
// did we get to the end?
if (node.Next == null) // node is the last message
break;
// if sequenceId is between the two, take the higher
if (node.Next.Value.SequenceToken.Older(sequenceToken))
break;
node = node.Next;
}
// return cursor from start.
SetCursor(cursor, node);
}
/// <summary>
/// Aquires the next message in the cache at the provided cursor
/// </summary>
/// <param name="cursor"></param>
/// <param name="batch"></param>
/// <returns></returns>
internal bool TryGetNextMessage(SimpleQueueCacheCursor cursor, out IBatchContainer batch)
{
Log(logger, "TryGetNextMessage: {0}", cursor);
batch = null;
if (cursor == null) throw new ArgumentNullException("cursor");
//if not set, try to set and then get next
if (!cursor.IsSet)
{
InitializeCursor(cursor, cursor.SequenceToken, false);
return cursor.IsSet && TryGetNextMessage(cursor, out batch);
}
// has this message been purged
if (cursor.SequenceToken.Older(cachedMessages.Last.Value.SequenceToken))
{
throw new QueueCacheMissException(cursor.SequenceToken, cachedMessages.Last.Value.SequenceToken, cachedMessages.First.Value.SequenceToken);
}
// Cursor now points to a valid message in the cache. Get it!
// Capture the current element and advance to the next one.
batch = cursor.Element.Value.Batch;
// Advance to next:
if (cursor.Element == cachedMessages.First)
{
// If we are at the end of the cache unset cursor and move offset one forward
ResetCursor(cursor, ((EventSequenceToken)cursor.SequenceToken).NextSequenceNumber());
}
else // move to next
{
UpdateCursor(cursor, cursor.Element.Previous);
}
return true;
}
private void UpdateCursor(SimpleQueueCacheCursor cursor, LinkedListNode<SimpleQueueCacheItem> item)
{
Log(logger, "UpdateCursor: {0} to item {1}", cursor, item.Value.Batch);
cursor.Element.Value.CacheBucket.UpdateNumCursors(-1); // remove from prev bucket
cursor.Set(item);
cursor.Element.Value.CacheBucket.UpdateNumCursors(1); // add to next bucket
}
internal void SetCursor(SimpleQueueCacheCursor cursor, LinkedListNode<SimpleQueueCacheItem> item)
{
Log(logger, "SetCursor: {0} to item {1}", cursor, item.Value.Batch);
cursor.Set(item);
cursor.Element.Value.CacheBucket.UpdateNumCursors(1); // add to next bucket
}
internal void ResetCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken token)
{
Log(logger, "ResetCursor: {0} to token {1}", cursor, token);
if (cursor.IsSet)
{
cursor.Element.Value.CacheBucket.UpdateNumCursors(-1);
}
cursor.Reset(token);
}
private void Add(IBatchContainer batch, StreamSequenceToken sequenceToken)
{
if (batch == null) throw new ArgumentNullException("batch");
CacheBucket cacheBucket = null;
if (cacheCursorHistogram.Count == 0)
{
cacheBucket = new CacheBucket();
cacheCursorHistogram.Add(cacheBucket);
}
else
{
cacheBucket = cacheCursorHistogram[cacheCursorHistogram.Count - 1]; // last one
}
if (cacheBucket.NumCurrentItems == CACHE_HISTOGRAM_MAX_BUCKET_SIZE) // last bucket is full, open a new one
{
cacheBucket = new CacheBucket();
cacheCursorHistogram.Add(cacheBucket);
}
// Add message to linked list
var item = new SimpleQueueCacheItem
{
Batch = batch,
SequenceToken = sequenceToken,
CacheBucket = cacheBucket
};
cachedMessages.AddFirst(new LinkedListNode<SimpleQueueCacheItem>(item));
cacheBucket.UpdateNumItems(1);
if (Size > maxCacheSize)
{
//var last = cachedMessages.Last;
cachedMessages.RemoveLast();
var bucket = cacheCursorHistogram[0]; // same as: var bucket = last.Value.CacheBucket;
bucket.UpdateNumItems(-1);
if (bucket.NumCurrentItems == 0)
{
cacheCursorHistogram.RemoveAt(0);
}
}
}
internal static void Log(Logger logger, string format, params object[] args)
{
if (logger.IsVerbose) logger.Verbose(format, args);
//if(logger.IsInfo) logger.Info(format, args);
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
// #define SHOW_DK2_VARIABLES
// Use the Unity new GUI with Unity 4.6 or above.
#if UNITY_4_6 || UNITY_5_0
#define USE_NEW_GUI
#endif
using System;
using System.Collections;
using UnityEngine;
#if USE_NEW_GUI
using UnityEngine.UI;
# endif
//-------------------------------------------------------------------------------------
// ***** OVRMainMenu
//
/// <summary>
/// OVRMainMenu is used to control the loading of different scenes. It also renders out
/// a menu that allows a user to modify various Rift settings, and allow for storing
/// these settings for recall later.
///
/// A user of this component can add as many scenes that they would like to be able to
/// have access to.
///
/// OVRMainMenu is currently attached to the OVRPlayerController prefab for convenience,
/// but can safely removed from it and added to another GameObject that is used for general
/// Unity logic.
///
/// </summary>
public class OVRMainMenu : MonoBehaviour
{
public float FadeInTime = 2.0f;
public UnityEngine.Texture FadeInTexture = null;
public Font FontReplace = null;
public KeyCode MenuKey = KeyCode.Space;
public KeyCode QuitKey = KeyCode.Escape;
// Scenes to show onscreen
public string [] SceneNames;
public string [] Scenes;
private bool ScenesVisible = false;
// Spacing for scenes menu
private int StartX = 490;
private int StartY = 250;
private int WidthX = 300;
private int WidthY = 23;
// Spacing for variables that users can change
private int VRVarsSX = 553;
private int VRVarsSY = 250;
private int VRVarsWidthX = 175;
private int VRVarsWidthY = 23;
private int StepY = 25;
// Handle to OVRCameraRig
private OVRCameraRig CameraController = null;
// Handle to OVRPlayerController
private OVRPlayerController PlayerController = null;
// Controller buttons
private bool PrevStartDown;
private bool PrevHatDown;
private bool PrevHatUp;
private bool ShowVRVars;
private bool OldSpaceHit;
// FPS
private float UpdateInterval = 0.5f;
private float Accum = 0;
private int Frames = 0;
private float TimeLeft = 0;
private string strFPS = "FPS: 0";
// IPD shift from physical IPD
public float IPDIncrement = 0.0025f;
private string strIPD = "IPD: 0.000";
// Prediction (in ms)
public float PredictionIncrement = 0.001f; // 1 ms
private string strPrediction = "Pred: OFF";
// FOV Variables
public float FOVIncrement = 0.2f;
private string strFOV = "FOV: 0.0f";
// Height adjustment
public float HeightIncrement = 0.01f;
private string strHeight = "Height: 0.0f";
// Speed and rotation adjustment
public float SpeedRotationIncrement = 0.05f;
private string strSpeedRotationMultipler = "Spd. X: 0.0f Rot. X: 0.0f";
private bool LoadingLevel = false;
private float AlphaFadeValue = 1.0f;
private int CurrentLevel = 0;
// Rift detection
private bool HMDPresent = false;
private float RiftPresentTimeout = 0.0f;
private string strRiftPresent = "";
// Replace the GUI with our own texture and 3D plane that
// is attached to the rendder camera for true 3D placement
private OVRGUI GuiHelper = new OVRGUI();
private GameObject GUIRenderObject = null;
private RenderTexture GUIRenderTexture = null;
// We want to use new Unity GUI built in 4.6 for OVRMainMenu GUI
// Enable the UsingNewGUI option in the editor,
// if you want to use new GUI and Unity version is higher than 4.6
#if USE_NEW_GUI
private GameObject NewGUIObject = null;
private GameObject RiftPresentGUIObject = null;
#endif
// We can set the layer to be anything we want to, this allows
// a specific camera to render it
public string LayerName = "Default";
// Crosshair system, rendered onto 3D plane
public UnityEngine.Texture CrosshairImage = null;
private OVRCrosshair Crosshair = new OVRCrosshair();
// Resolution Eye Texture
private string strResolutionEyeTexture = "Resolution: 0 x 0";
// Latency values
private string strLatencies = "Ren: 0.0f TWrp: 0.0f PostPresent: 0.0f";
// Vision mode on/off
private bool VisionMode = true;
#if SHOW_DK2_VARIABLES
private string strVisionMode = "Vision Enabled: ON";
#endif
// We want to hold onto GridCube, for potential sharing
// of the menu RenderTarget
OVRGridCube GridCube = null;
// We want to hold onto the VisionGuide so we can share
// the menu RenderTarget
OVRVisionGuide VisionGuide = null;
#region MonoBehaviour Message Handlers
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
// Find camera controller
OVRCameraRig[] CameraControllers;
CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>();
if(CameraControllers.Length == 0)
Debug.LogWarning("OVRMainMenu: No OVRCameraRig attached.");
else if (CameraControllers.Length > 1)
Debug.LogWarning("OVRMainMenu: More then 1 OVRCameraRig attached.");
else{
CameraController = CameraControllers[0];
#if USE_NEW_GUI
OVRUGUI.CameraController = CameraController;
#endif
}
// Find player controller
OVRPlayerController[] PlayerControllers;
PlayerControllers = gameObject.GetComponentsInChildren<OVRPlayerController>();
if(PlayerControllers.Length == 0)
Debug.LogWarning("OVRMainMenu: No OVRPlayerController attached.");
else if (PlayerControllers.Length > 1)
Debug.LogWarning("OVRMainMenu: More then 1 OVRPlayerController attached.");
else{
PlayerController = PlayerControllers[0];
#if USE_NEW_GUI
OVRUGUI.PlayerController = PlayerController;
#endif
}
#if USE_NEW_GUI
// Create canvas for using new GUI
NewGUIObject = new GameObject();
NewGUIObject.name = "OVRGUIMain";
NewGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform;
RectTransform r = NewGUIObject.AddComponent<RectTransform>();
r.sizeDelta = new Vector2(100f, 100f);
r.localScale = new Vector3(0.001f, 0.001f, 0.001f);
r.localPosition = new Vector3(0.01f, 0.17f, 0.53f);
r.localEulerAngles = Vector3.zero;
Canvas c = NewGUIObject.AddComponent<Canvas>();
#if (UNITY_5_0)
// TODO: Unity 5.0b11 has an older version of the new GUI being developed in Unity 4.6.
// Remove this once Unity 5 has a more recent merge of Unity 4.6.
c.renderMode = RenderMode.World;
#else
c.renderMode = RenderMode.WorldSpace;
#endif
c.pixelPerfect = false;
#endif
}
/// <summary>
/// Start this instance.
/// </summary>
void Start()
{
AlphaFadeValue = 1.0f;
CurrentLevel = 0;
PrevStartDown = false;
PrevHatDown = false;
PrevHatUp = false;
ShowVRVars = false;
OldSpaceHit = false;
strFPS = "FPS: 0";
LoadingLevel = false;
ScenesVisible = false;
// Set the GUI target
GUIRenderObject = GameObject.Instantiate(Resources.Load("OVRGUIObjectMain")) as GameObject;
if(GUIRenderObject != null)
{
// Chnge the layer
GUIRenderObject.layer = LayerMask.NameToLayer(LayerName);
if(GUIRenderTexture == null)
{
int w = Screen.width;
int h = Screen.height;
// We don't need a depth buffer on this texture
GUIRenderTexture = new RenderTexture(w, h, 0);
GuiHelper.SetPixelResolution(w, h);
// NOTE: All GUI elements are being written with pixel values based
// from DK1 (1280x800). These should change to normalized locations so
// that we can scale more cleanly with varying resolutions
GuiHelper.SetDisplayResolution(1280.0f, 800.0f);
}
}
// Attach GUI texture to GUI object and GUI object to Camera
if(GUIRenderTexture != null && GUIRenderObject != null)
{
GUIRenderObject.GetComponent<Renderer>().material.mainTexture = GUIRenderTexture;
if(CameraController != null)
{
// Grab transform of GUI object
Vector3 ls = GUIRenderObject.transform.localScale;
Vector3 lp = GUIRenderObject.transform.localPosition;
Quaternion lr = GUIRenderObject.transform.localRotation;
// Attach the GUI object to the camera
GUIRenderObject.transform.parent = CameraController.centerEyeAnchor;
// Reset the transform values (we will be maintaining state of the GUI object
// in local state)
GUIRenderObject.transform.localScale = ls;
GUIRenderObject.transform.localPosition = lp;
GUIRenderObject.transform.localRotation = lr;
// Deactivate object until we have completed the fade-in
// Also, we may want to deactive the render object if there is nothing being rendered
// into the UI
GUIRenderObject.SetActive(false);
}
}
// Make sure to hide cursor
if(Application.isEditor == false)
{
#if UNITY_5_0
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
#else
Screen.showCursor = false;
Screen.lockCursor = true;
#endif
}
// CameraController updates
if(CameraController != null)
{
// Add a GridCube component to this object
GridCube = gameObject.AddComponent<OVRGridCube>();
GridCube.SetOVRCameraController(ref CameraController);
// Add a VisionGuide component to this object
VisionGuide = gameObject.AddComponent<OVRVisionGuide>();
VisionGuide.SetOVRCameraController(ref CameraController);
VisionGuide.SetFadeTexture(ref FadeInTexture);
VisionGuide.SetVisionGuideLayer(ref LayerName);
}
// Crosshair functionality
Crosshair.Init();
Crosshair.SetCrosshairTexture(ref CrosshairImage);
Crosshair.SetOVRCameraController (ref CameraController);
Crosshair.SetOVRPlayerController(ref PlayerController);
// Check for HMD and sensor
CheckIfRiftPresent();
#if USE_NEW_GUI
if (!string.IsNullOrEmpty(strRiftPresent)){
ShowRiftPresentGUI();
}
#endif
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
if(LoadingLevel == true)
return;
// Main update
UpdateFPS();
// CameraController updates
if(CameraController != null)
{
UpdateIPD();
UpdateRecenterPose();
UpdateVisionMode();
UpdateFOV();
UpdateEyeHeightOffset();
UpdateResolutionEyeTexture();
UpdateLatencyValues();
}
// PlayerController updates
if(PlayerController != null)
{
UpdateSpeedAndRotationScaleMultiplier();
UpdatePlayerControllerMovement();
}
// MainMenu updates
UpdateSelectCurrentLevel();
// Device updates
UpdateDeviceDetection();
// Crosshair functionality
Crosshair.UpdateCrosshair();
#if USE_NEW_GUI
if (ShowVRVars && RiftPresentTimeout <= 0.0f)
{
NewGUIObject.SetActive(true);
UpdateNewGUIVars();
OVRUGUI.UpdateGUI();
}
else
{
NewGUIObject.SetActive(false);
}
#endif
// Toggle Fullscreen
if(Input.GetKeyDown(KeyCode.F11))
Screen.fullScreen = !Screen.fullScreen;
if (Input.GetKeyDown(KeyCode.M))
OVRManager.display.mirrorMode = !OVRManager.display.mirrorMode;
// Escape Application
if (Input.GetKeyDown(QuitKey))
Application.Quit();
}
/// <summary>
/// Updates Variables for new GUI.
/// </summary>
#if USE_NEW_GUI
void UpdateNewGUIVars()
{
#if SHOW_DK2_VARIABLES
// Print out Vision Mode
OVRUGUI.strVisionMode = strVisionMode;
#endif
// Print out FPS
OVRUGUI.strFPS = strFPS;
// Don't draw these vars if CameraController is not present
if (CameraController != null)
{
OVRUGUI.strPrediction = strPrediction;
OVRUGUI.strIPD = strIPD;
OVRUGUI.strFOV = strFOV;
OVRUGUI.strResolutionEyeTexture = strResolutionEyeTexture;
OVRUGUI.strLatencies = strLatencies;
}
// Don't draw these vars if PlayerController is not present
if (PlayerController != null)
{
OVRUGUI.strHeight = strHeight;
OVRUGUI.strSpeedRotationMultipler = strSpeedRotationMultipler;
}
OVRUGUI.strRiftPresent = strRiftPresent;
}
#endif
void OnGUI()
{
// Important to keep from skipping render events
if (Event.current.type != EventType.Repaint)
return;
#if !USE_NEW_GUI
// Fade in screen
if(AlphaFadeValue > 0.0f)
{
AlphaFadeValue -= Mathf.Clamp01(Time.deltaTime / FadeInTime);
if(AlphaFadeValue < 0.0f)
{
AlphaFadeValue = 0.0f;
}
else
{
GUI.color = new Color(0, 0, 0, AlphaFadeValue);
GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture );
return;
}
}
#endif
// We can turn on the render object so we can render the on-screen menu
if(GUIRenderObject != null)
{
if (ScenesVisible ||
ShowVRVars ||
Crosshair.IsCrosshairVisible() ||
RiftPresentTimeout > 0.0f ||
VisionGuide.GetFadeAlphaValue() > 0.0f)
{
GUIRenderObject.SetActive(true);
}
else
{
GUIRenderObject.SetActive(false);
}
}
//***
// Set the GUI matrix to deal with portrait mode
Vector3 scale = Vector3.one;
Matrix4x4 svMat = GUI.matrix; // save current matrix
// substitute matrix - only scale is altered from standard
GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale);
// Cache current active render texture
RenderTexture previousActive = RenderTexture.active;
// if set, we will render to this texture
if(GUIRenderTexture != null && GUIRenderObject.activeSelf)
{
RenderTexture.active = GUIRenderTexture;
GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f));
}
// Update OVRGUI functions (will be deprecated eventually when 2D renderingc
// is removed from GUI)
GuiHelper.SetFontReplace(FontReplace);
// If true, we are displaying information about the Rift not being detected
// So do not show anything else
if(GUIShowRiftDetected() != true)
{
GUIShowLevels();
GUIShowVRVariables();
}
// The cross-hair may need to go away at some point, unless someone finds it
// useful
Crosshair.OnGUICrosshair();
// Since we want to draw into the main GUI that is shared within the MainMenu,
// we call the OVRVisionGuide GUI function here
VisionGuide.OnGUIVisionGuide();
// Restore active render texture
if (GUIRenderObject.activeSelf)
{
RenderTexture.active = previousActive;
}
// ***
// Restore previous GUI matrix
GUI.matrix = svMat;
}
#endregion
#region Internal State Management Functions
/// <summary>
/// Updates the FPS.
/// </summary>
void UpdateFPS()
{
TimeLeft -= Time.deltaTime;
Accum += Time.timeScale/Time.deltaTime;
++Frames;
// Interval ended - update GUI text and start new interval
if( TimeLeft <= 0.0 )
{
// display two fractional digits (f2 format)
float fps = Accum / Frames;
if(ShowVRVars == true)// limit gc
strFPS = System.String.Format("FPS: {0:F2}",fps);
TimeLeft += UpdateInterval;
Accum = 0.0f;
Frames = 0;
}
}
/// <summary>
/// Updates the IPD.
/// </summary>
void UpdateIPD()
{
if(ShowVRVars == true) // limit gc
{
strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f);
}
}
void UpdateRecenterPose()
{
if(Input.GetKeyDown(KeyCode.R))
{
OVRManager.display.RecenterPose();
}
}
/// <summary>
/// Updates the vision mode.
/// </summary>
void UpdateVisionMode()
{
if (Input.GetKeyDown(KeyCode.F2))
{
VisionMode = !VisionMode;
OVRManager.tracker.isEnabled = VisionMode;
#if SHOW_DK2_VARIABLES
strVisionMode = VisionMode ? "Vision Enabled: ON" : "Vision Enabled: OFF";
#endif
}
}
/// <summary>
/// Updates the FOV.
/// </summary>
void UpdateFOV()
{
if(ShowVRVars == true)// limit gc
{
OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left);
strFOV = System.String.Format ("FOV (deg): {0:F3}", eyeDesc.fov.y);
}
}
/// <summary>
/// Updates resolution of eye texture
/// </summary>
void UpdateResolutionEyeTexture()
{
if (ShowVRVars == true) // limit gc
{
OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left);
OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Right);
float scale = OVRManager.instance.nativeTextureScale * OVRManager.instance.virtualTextureScale;
float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x));
float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y));
strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h);
}
}
/// <summary>
/// Updates latency values
/// </summary>
void UpdateLatencyValues()
{
#if !UNITY_ANDROID || UNITY_EDITOR
if (ShowVRVars == true) // limit gc
{
OVRDisplay.LatencyData latency = OVRManager.display.latency;
if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f)
strLatencies = System.String.Format("Ren : N/A TWrp: N/A PostPresent: N/A");
else
strLatencies = System.String.Format("Ren : {0:F3} TWrp: {1:F3} PostPresent: {2:F3}",
latency.render,
latency.timeWarp,
latency.postPresent);
}
#endif
}
/// <summary>
/// Updates the eye height offset.
/// </summary>
void UpdateEyeHeightOffset()
{
if(ShowVRVars == true)// limit gc
{
float eyeHeight = OVRManager.profile.eyeHeight;
strHeight = System.String.Format ("Eye Height (m): {0:F3}", eyeHeight);
}
}
/// <summary>
/// Updates the speed and rotation scale multiplier.
/// </summary>
void UpdateSpeedAndRotationScaleMultiplier()
{
float moveScaleMultiplier = 0.0f;
PlayerController.GetMoveScaleMultiplier(ref moveScaleMultiplier);
if(Input.GetKeyDown(KeyCode.Alpha7))
moveScaleMultiplier -= SpeedRotationIncrement;
else if (Input.GetKeyDown(KeyCode.Alpha8))
moveScaleMultiplier += SpeedRotationIncrement;
PlayerController.SetMoveScaleMultiplier(moveScaleMultiplier);
float rotationScaleMultiplier = 0.0f;
PlayerController.GetRotationScaleMultiplier(ref rotationScaleMultiplier);
if(Input.GetKeyDown(KeyCode.Alpha9))
rotationScaleMultiplier -= SpeedRotationIncrement;
else if (Input.GetKeyDown(KeyCode.Alpha0))
rotationScaleMultiplier += SpeedRotationIncrement;
PlayerController.SetRotationScaleMultiplier(rotationScaleMultiplier);
if(ShowVRVars == true)// limit gc
strSpeedRotationMultipler = System.String.Format ("Spd.X: {0:F2} Rot.X: {1:F2}",
moveScaleMultiplier,
rotationScaleMultiplier);
}
/// <summary>
/// Updates the player controller movement.
/// </summary>
void UpdatePlayerControllerMovement()
{
if(PlayerController != null)
PlayerController.SetHaltUpdateMovement(ScenesVisible);
}
/// <summary>
/// Updates the select current level.
/// </summary>
void UpdateSelectCurrentLevel()
{
ShowLevels();
if (!ScenesVisible)
return;
CurrentLevel = GetCurrentLevel();
if (Scenes.Length != 0
&& (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.A)
|| Input.GetKeyDown(KeyCode.Return)))
{
LoadingLevel = true;
Application.LoadLevelAsync(Scenes[CurrentLevel]);
}
}
/// <summary>
/// Shows the levels.
/// </summary>
/// <returns><c>true</c>, if levels was shown, <c>false</c> otherwise.</returns>
bool ShowLevels()
{
if (Scenes.Length == 0)
{
ScenesVisible = false;
return ScenesVisible;
}
bool curStartDown = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Start);
bool startPressed = (curStartDown && !PrevStartDown) || Input.GetKeyDown(KeyCode.RightShift);
PrevStartDown = curStartDown;
if (startPressed)
{
ScenesVisible = !ScenesVisible;
}
return ScenesVisible;
}
/// <summary>
/// Gets the current level.
/// </summary>
/// <returns>The current level.</returns>
int GetCurrentLevel()
{
bool curHatDown = false;
if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true)
curHatDown = true;
bool curHatUp = false;
if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true)
curHatUp = true;
if((PrevHatDown == false) && (curHatDown == true) ||
Input.GetKeyDown(KeyCode.DownArrow))
{
CurrentLevel = (CurrentLevel + 1) % SceneNames.Length;
}
else if((PrevHatUp == false) && (curHatUp == true) ||
Input.GetKeyDown(KeyCode.UpArrow))
{
CurrentLevel--;
if(CurrentLevel < 0)
CurrentLevel = SceneNames.Length - 1;
}
PrevHatDown = curHatDown;
PrevHatUp = curHatUp;
return CurrentLevel;
}
#endregion
#region Internal GUI Functions
/// <summary>
/// Show the GUI levels.
/// </summary>
void GUIShowLevels()
{
if(ScenesVisible == true)
{
// Darken the background by rendering fade texture
GUI.color = new Color(0, 0, 0, 0.5f);
GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture );
GUI.color = Color.white;
if(LoadingLevel == true)
{
string loading = "LOADING...";
GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref loading, Color.yellow);
return;
}
for (int i = 0; i < SceneNames.Length; i++)
{
Color c;
if(i == CurrentLevel)
c = Color.yellow;
else
c = Color.black;
int y = StartY + (i * StepY);
GuiHelper.StereoBox (StartX, y, WidthX, WidthY, ref SceneNames[i], c);
}
}
}
/// <summary>
/// Show the VR variables.
/// </summary>
void GUIShowVRVariables()
{
bool SpaceHit = Input.GetKey(MenuKey);
if ((OldSpaceHit == false) && (SpaceHit == true))
{
if (ShowVRVars == true)
{
ShowVRVars = false;
}
else
{
ShowVRVars = true;
#if USE_NEW_GUI
OVRUGUI.InitUIComponent = ShowVRVars;
#endif
}
}
OldSpaceHit = SpaceHit;
// Do not render if we are not showing
if (ShowVRVars == false)
return;
#if !USE_NEW_GUI
int y = VRVarsSY;
#if SHOW_DK2_VARIABLES
// Print out Vision Mode
GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strVisionMode, Color.green);
#endif
// Draw FPS
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strFPS, Color.green);
// Don't draw these vars if CameraController is not present
if (CameraController != null)
{
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strPrediction, Color.white);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strIPD, Color.yellow);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strFOV, Color.white);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strResolutionEyeTexture, Color.white);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strLatencies, Color.white);
}
// Don't draw these vars if PlayerController is not present
if (PlayerController != null)
{
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strHeight, Color.yellow);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strSpeedRotationMultipler, Color.white);
}
#endif
}
// RIFT DETECTION
/// <summary>
/// Checks to see if HMD and / or sensor is available, and displays a
/// message if it is not.
/// </summary>
void CheckIfRiftPresent()
{
HMDPresent = OVRManager.display.isPresent;
if (!HMDPresent)
{
RiftPresentTimeout = 15.0f;
if (!HMDPresent)
strRiftPresent = "NO HMD DETECTED";
#if USE_NEW_GUI
OVRUGUI.strRiftPresent = strRiftPresent;
#endif
}
}
/// <summary>
/// Show if Rift is detected.
/// </summary>
/// <returns><c>true</c>, if show rift detected was GUIed, <c>false</c> otherwise.</returns>
bool GUIShowRiftDetected()
{
#if !USE_NEW_GUI
if(RiftPresentTimeout > 0.0f)
{
GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY,
ref strRiftPresent, Color.white);
return true;
}
#else
if(RiftPresentTimeout < 0.0f)
DestroyImmediate(RiftPresentGUIObject);
#endif
return false;
}
/// <summary>
/// Updates the device detection.
/// </summary>
void UpdateDeviceDetection()
{
if(RiftPresentTimeout > 0.0f)
RiftPresentTimeout -= Time.deltaTime;
}
/// <summary>
/// Show rift present GUI with new GUI
/// </summary>
void ShowRiftPresentGUI()
{
#if USE_NEW_GUI
RiftPresentGUIObject = new GameObject();
RiftPresentGUIObject.name = "RiftPresentGUIMain";
RiftPresentGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform;
RectTransform r = RiftPresentGUIObject.AddComponent<RectTransform>();
r.sizeDelta = new Vector2(100f, 100f);
r.localPosition = new Vector3(0.01f, 0.17f, 0.53f);
r.localEulerAngles = Vector3.zero;
r.localScale = new Vector3(0.001f, 0.001f, 0.001f);
Canvas c = RiftPresentGUIObject.AddComponent<Canvas>();
#if UNITY_5_0
// TODO: Unity 5.0b11 has an older version of the new GUI being developed in Unity 4.6.
// Remove this once Unity 5 has a more recent merge of Unity 4.6.
c.renderMode = RenderMode.World;
#else
c.renderMode = RenderMode.WorldSpace;
#endif
c.pixelPerfect = false;
OVRUGUI.RiftPresentGUI(RiftPresentGUIObject);
#endif
}
#endregion
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Project.ImportWizard;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Python;
namespace PythonToolsTests {
[TestClass]
public class ImportWizardTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
private static string CreateRequestedProject(dynamic settings) {
return Task.Run(async () => {
return await await WpfProxy.FromObject((object)settings).InvokeAsync(
async () => await (Task<string>)settings.CreateRequestedProjectAsync()
);
})
.GetAwaiter()
.GetResult();
}
[TestMethod, Priority(1)]
public void ImportWizardSimple() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py;*.pyproj";
settings.SearchPaths = TestData.GetPath("TestData\\SearchPath1\\") + Environment.NewLine + TestData.GetPath("TestData\\SearchPath2\\");
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("4.0", proj.Descendant("Project").Attribute("ToolsVersion").Value);
Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value);
Assert.AreEqual("..\\SearchPath1\\;..\\SearchPath2\\", proj.Descendant("SearchPath").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"Program.py");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Content")).Select(x => x.Attribute("Include").Value),
"HelloWorld.pyproj");
}
}
[TestMethod, Priority(1)]
public void ImportWizardFiltered() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py";
settings.SearchPaths = TestData.GetPath("TestData\\SearchPath1\\") + Environment.NewLine + TestData.GetPath("TestData\\SearchPath2\\");
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value);
Assert.AreEqual("..\\SearchPath1\\;..\\SearchPath2\\", proj.Descendant("SearchPath").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"Program.py");
Assert.AreEqual(0, proj.Descendants(proj.GetName("Content")).Count());
}
}
[TestMethod, Priority(1)]
public void ImportWizardFolders() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld2\\");
settings.Filters = "*";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorld2\\", proj.Descendant("ProjectHome").Value);
Assert.AreEqual("", proj.Descendant("SearchPath").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"Program.py",
"TestFolder\\SubItem.py",
"TestFolder2\\SubItem.py",
"TestFolder3\\SubItem.py");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"TestFolder",
"TestFolder2",
"TestFolder3");
}
}
[TestMethod, Priority(1)]
public void ImportWizardInterpreter() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py;*.pyproj";
var interpreter = new PythonInterpreterView("Test", "Test|Blah", null);
settings.Dispatcher.Invoke((Action)(() => settings.AvailableInterpreters.Add(interpreter)));
//settings.AddAvailableInterpreter(interpreter);
settings.SelectedInterpreter = interpreter;
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual(interpreter.Id, proj.Descendant("InterpreterId").Value);
var interp = proj.Descendant("InterpreterReference");
Assert.AreEqual(string.Format("{0}", interpreter.Id),
interp.Attribute("Include").Value);
}
}
[TestMethod, Priority(1)]
public void ImportWizardStartupFile() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py;*.pyproj";
settings.StartupFile = "Program.py";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("Program.py", proj.Descendant("StartupFile").Value);
}
}
[TestMethod, Priority(1)]
public void ImportWizardSemicolons() {
// https://pytools.codeplex.com/workitem/2022
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
var sourcePath = TestData.GetTempPath(randomSubPath: true);
// Create a fake set of files to import
Directory.CreateDirectory(Path.Combine(sourcePath, "ABC"));
File.WriteAllText(Path.Combine(sourcePath, "ABC", "a;b;c.py"), "");
Directory.CreateDirectory(Path.Combine(sourcePath, "A;B;C"));
File.WriteAllText(Path.Combine(sourcePath, "A;B;C", "abc.py"), "");
settings.SourcePath = sourcePath;
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"ABC\\a%3bb%3bc.py",
"A%3bB%3bC\\abc.py"
);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"ABC",
"A%3bB%3bC"
);
}
}
private void ImportWizardVirtualEnvWorker(
PythonVersion python,
string venvModuleName,
string expectedFile,
bool brokenBaseInterpreter
) {
var mockService = new MockInterpreterOptionsService();
mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider",
new MockPythonInterpreterFactory(python.Configuration)
));
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, mockService));
var sourcePath = TestData.GetTempPath(randomSubPath: true);
// Create a fake set of files to import
File.WriteAllText(Path.Combine(sourcePath, "main.py"), "");
Directory.CreateDirectory(Path.Combine(sourcePath, "A"));
File.WriteAllText(Path.Combine(sourcePath, "A", "__init__.py"), "");
// Create a real virtualenv environment to import
using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", venvModuleName, Path.Combine(sourcePath, "env"))) {
Console.WriteLine(p.Arguments);
p.Wait();
Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines)));
Assert.AreEqual(0, p.ExitCode);
}
if (brokenBaseInterpreter) {
var cfgPath = Path.Combine(sourcePath, "env", "Lib", "orig-prefix.txt");
if (File.Exists(cfgPath)) {
File.WriteAllText(cfgPath, string.Format("C:\\{0:N}", Guid.NewGuid()));
} else if (File.Exists((cfgPath = Path.Combine(sourcePath, "env", "pyvenv.cfg")))) {
File.WriteAllLines(cfgPath, File.ReadAllLines(cfgPath)
.Select(line => {
if (line.StartsWith("home = ")) {
return string.Format("home = C:\\{0:N}", Guid.NewGuid());
}
return line;
})
);
}
}
Console.WriteLine("All files:");
foreach (var f in Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)) {
Console.WriteLine(PathUtils.GetRelativeFilePath(sourcePath, f));
}
Assert.IsTrue(
File.Exists(Path.Combine(sourcePath, "env", expectedFile)),
"Virtualenv was not created correctly"
);
settings.SourcePath = sourcePath;
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
// Does not include any .py files from the virtualenv
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"main.py",
"A\\__init__.py"
);
// Does not contain 'env'
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"A"
);
var env = proj.Descendants(proj.GetName("Interpreter")).SingleOrDefault();
if (brokenBaseInterpreter) {
Assert.IsNull(env);
} else {
Assert.AreEqual("env\\", env.Attribute("Include").Value);
Assert.AreNotEqual("", env.Descendant("Id").Value);
Assert.AreEqual(string.Format("env ({0})", python.Configuration.Description), env.Descendant("Description").Value);
Assert.AreEqual("scripts\\python.exe", env.Descendant("InterpreterPath").Value, true);
Assert.AreEqual("scripts\\pythonw.exe", env.Descendant("WindowsInterpreterPath").Value, true);
Assert.AreEqual("PYTHONPATH", env.Descendant("PathEnvironmentVariable").Value, true);
Assert.AreEqual(python.Configuration.Version.ToString(), env.Descendant("Version").Value, true);
Assert.AreEqual(python.Configuration.Architecture.ToString("X"), env.Descendant("Architecture").Value, true);
}
}
}
[TestMethod, Priority(1)]
public void ImportWizardVirtualEnv() {
var python = PythonPaths.Versions.LastOrDefault(pv =>
pv.IsCPython &&
File.Exists(Path.Combine(pv.PrefixPath, "Lib", "site-packages", "virtualenv.py")) &&
// CPython 3.3.4 does not work correctly with virtualenv, so
// skip testing on 3.3 to avoid false failures
pv.Version != PythonLanguageVersion.V33
);
ImportWizardVirtualEnvWorker(python, "virtualenv", "lib\\orig-prefix.txt", false);
}
[TestMethod, Priority(1)]
public void ImportWizardVEnv() {
var python = PythonPaths.Versions.LastOrDefault(pv =>
pv.IsCPython && File.Exists(Path.Combine(pv.PrefixPath, "Lib", "venv", "__main__.py"))
);
ImportWizardVirtualEnvWorker(python, "venv", "pyvenv.cfg", false);
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void ImportWizardBrokenVirtualEnv() {
var python = PythonPaths.Versions.LastOrDefault(pv =>
pv.IsCPython &&
File.Exists(Path.Combine(pv.PrefixPath, "Lib", "site-packages", "virtualenv.py")) &&
// CPython 3.3.4 does not work correctly with virtualenv, so
// skip testing on 3.3 to avoid false failures
pv.Version != PythonLanguageVersion.V33
);
ImportWizardVirtualEnvWorker(python, "virtualenv", "lib\\orig-prefix.txt", true);
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void ImportWizardBrokenVEnv() {
var python = PythonPaths.Versions.LastOrDefault(pv =>
pv.IsCPython && File.Exists(Path.Combine(pv.PrefixPath, "Lib", "venv", "__main__.py"))
);
ImportWizardVirtualEnvWorker(python, "venv", "pyvenv.cfg", true);
}
private static void ImportWizardCustomizationsWorker(ProjectCustomization customization, Action<XDocument> verify) {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py;*.pyproj";
settings.StartupFile = "Program.py";
settings.UseCustomization = true;
settings.Customization = customization;
settings.ProjectPath = Path.Combine(TestData.GetTempPath("ImportWizardCustomizations_" + customization.GetType().Name), "Project.pyproj");
Directory.CreateDirectory(Path.GetDirectoryName(settings.ProjectPath));
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
Console.WriteLine(File.ReadAllText(path));
var proj = XDocument.Load(path);
verify(proj);
}
}
[TestMethod, Priority(1)]
public void ImportWizardCustomizations() {
ImportWizardCustomizationsWorker(DefaultProjectCustomization.Instance, proj => {
Assert.AreEqual("Program.py", proj.Descendant("StartupFile").Value);
Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets"));
});
ImportWizardCustomizationsWorker(BottleProjectCustomization.Instance, proj => {
Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("e614c764-6d9e-4607-9337-b7073809a0bd", StringComparison.OrdinalIgnoreCase));
Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets"));
Assert.AreEqual("Web launcher", proj.Descendant("LaunchProvider").Value);
});
ImportWizardCustomizationsWorker(DjangoProjectCustomization.Instance, proj => {
Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("5F0BE9CA-D677-4A4D-8806-6076C0FAAD37", StringComparison.OrdinalIgnoreCase));
Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Django.targets"));
Assert.AreEqual("Django launcher", proj.Descendant("LaunchProvider").Value);
});
ImportWizardCustomizationsWorker(FlaskProjectCustomization.Instance, proj => {
Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("789894c7-04a9-4a11-a6b5-3f4435165112", StringComparison.OrdinalIgnoreCase));
Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets"));
Assert.AreEqual("Web launcher", proj.Descendant("LaunchProvider").Value);
});
}
static T Wait<T>(System.Threading.Tasks.Task<T> task) {
task.Wait();
return task.Result;
}
[TestMethod, Priority(1)]
public void ImportWizardCandidateStartupFiles() {
var sourcePath = TestData.GetTempPath(randomSubPath: true);
// Create a fake set of files to import
File.WriteAllText(Path.Combine(sourcePath, "a.py"), "");
File.WriteAllText(Path.Combine(sourcePath, "b.py"), "");
File.WriteAllText(Path.Combine(sourcePath, "c.py"), "");
File.WriteAllText(Path.Combine(sourcePath, "a.pyw"), "");
File.WriteAllText(Path.Combine(sourcePath, "b.pyw"), "");
File.WriteAllText(Path.Combine(sourcePath, "c.pyw"), "");
File.WriteAllText(Path.Combine(sourcePath, "a.txt"), "");
File.WriteAllText(Path.Combine(sourcePath, "b.txt"), "");
File.WriteAllText(Path.Combine(sourcePath, "c.txt"), "");
AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "")),
"a.py",
"b.py",
"c.py"
);
AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "*.pyw")),
"a.py",
"b.py",
"c.py",
"a.pyw",
"b.pyw",
"c.pyw"
);
AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "b.pyw")),
"a.py",
"b.py",
"c.py",
"b.pyw"
);
AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "*.txt")),
"a.py",
"b.py",
"c.py"
);
}
[TestMethod, Priority(1)]
public void ImportWizardDefaultStartupFile() {
var files = new[] { "a.py", "b.py", "c.py" };
var expectedDefault = files[0];
Assert.AreEqual(expectedDefault, ImportSettings.SelectDefaultStartupFile(files, null));
Assert.AreEqual(expectedDefault, ImportSettings.SelectDefaultStartupFile(files, "not in list"));
Assert.AreEqual("b.py", ImportSettings.SelectDefaultStartupFile(files, "b.py"));
}
}
}
| |
// 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 AndUInt64()
{
var test = new SimpleBinaryOpTest__AndUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// 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();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndUInt64
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[ElementCount];
private static UInt64[] _data2 = new UInt64[ElementCount];
private static Vector256<UInt64> _clsVar1;
private static Vector256<UInt64> _clsVar2;
private Vector256<UInt64> _fld1;
private Vector256<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64> _dataTable;
static SimpleBinaryOpTest__AndUInt64()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64>(_data1, _data2, new UInt64[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.And(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.And(
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.And(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr);
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndUInt64();
var result = Avx2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.And(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt64> left, Vector256<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[ElementCount];
UInt64[] inArray2 = new UInt64[ElementCount];
UInt64[] outArray = new UInt64[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[ElementCount];
UInt64[] inArray2 = new UInt64[ElementCount];
UInt64[] outArray = new UInt64[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
if ((ulong)(left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((ulong)(left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.And)}<UInt64>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal class test
{
public static int Main()
{
double x;
double y;
bool pass = true;
x = -10.0;
y = 4.0;
x = x + y;
if (x != -6)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x + y failed. x: {0}, \texpected: -6\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x - y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x - y failed. x: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x * y;
if (x != -40)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x * y failed. x: {0}, \texpected: -40\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x / y;
if (x != -2.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x / y failed. x: {0}, \texpected: -2.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x % y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x % y failed. x: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x + y;
if (x != -16)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x + y failed. x: {0}, \texpected: -16\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x - y;
if (x != -24)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x - y failed. x: {0}, \texpected: -24\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x * y;
if (x != -50)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x * y failed. x: {0}, \texpected: -50\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x / y;
if (x != -12.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x / y failed. x: {0}, \texpected: -12.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x % y;
if (x != -12)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x % y failed. x: {0}, \texpected: -12\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x + y;
if (x != -4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x + y failed. x: {0}, \texpected: -4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x - y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x - y failed. x: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x * y;
if (x != 30)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x * y failed. x: {0}, \texpected: 30\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x / y;
if (x != -7.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x / y failed. x: {0}, \texpected: -7.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x % y;
if (x != -8)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x % y failed. x: {0}, \texpected: -8\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x + y;
if (x != 60)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x + y failed. x: {0}, \texpected: 60\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x - y;
if (x != 140)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x - y failed. x: {0}, \texpected: 140\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x * y;
if (x != 400)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x * y failed. x: {0}, \texpected: 400\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x / y;
if (x != 25)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x / y failed. x: {0}, \texpected: 25\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x % y;
if (x != 20)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x % y failed. x: {0}, \texpected: 20\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x + y;
if (x != 1.6666666666666667)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x + y failed. x: {0}, \texpected: 1.6666666666666667\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x - y;
if (x != 0.7142857142857143)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x - y failed. x: {0}, \texpected: 0.7142857142857143\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x * y;
if (x != 0.25)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x * y failed. x: {0}, \texpected: 0.25\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x / y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x / y failed. x: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x % y;
if (x != 5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x % y failed. x: {0}, \texpected: 5\n", x);
pass = false;
}
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
return 1;
}
}
| |
// Copyright 2018 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 Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Bigtable.V2;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Bigtable.V2.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedBigtableClientSnippets
{
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRows()
{
// Snippet: ReadRows(ReadRowsRequest,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument
ReadRowsRequest request = new ReadRowsRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
};
// Make the request, returning a streaming response
BigtableClient.ReadRowsStream streamingResponse = bigtableClient.ReadRows(request);
// Read streaming responses from server until complete
IAsyncEnumerator<ReadRowsResponse> responseStream = streamingResponse.ResponseStream;
while (await responseStream.MoveNext())
{
ReadRowsResponse response = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for SampleRowKeys</summary>
public async Task SampleRowKeys()
{
// Snippet: SampleRowKeys(SampleRowKeysRequest,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument
SampleRowKeysRequest request = new SampleRowKeysRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
};
// Make the request, returning a streaming response
BigtableClient.SampleRowKeysStream streamingResponse = bigtableClient.SampleRowKeys(request);
// Read streaming responses from server until complete
IAsyncEnumerator<SampleRowKeysResponse> responseStream = streamingResponse.ResponseStream;
while (await responseStream.MoveNext())
{
SampleRowKeysResponse response = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for MutateRowAsync</summary>
public async Task MutateRowAsync()
{
// Snippet: MutateRowAsync(TableName,ByteString,IEnumerable<Mutation>,CallSettings)
// Additional: MutateRowAsync(TableName,ByteString,IEnumerable<Mutation>,CancellationToken)
// Create client
BigtableClient bigtableClient = await BigtableClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.CopyFromUtf8("");
IEnumerable<Mutation> mutations = new List<Mutation>();
// Make the request
MutateRowResponse response = await bigtableClient.MutateRowAsync(tableName, rowKey, mutations);
// End snippet
}
/// <summary>Snippet for MutateRow</summary>
public void MutateRow()
{
// Snippet: MutateRow(TableName,ByteString,IEnumerable<Mutation>,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument(s)
TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.CopyFromUtf8("");
IEnumerable<Mutation> mutations = new List<Mutation>();
// Make the request
MutateRowResponse response = bigtableClient.MutateRow(tableName, rowKey, mutations);
// End snippet
}
/// <summary>Snippet for MutateRowAsync</summary>
public async Task MutateRowAsync_RequestObject()
{
// Snippet: MutateRowAsync(MutateRowRequest,CallSettings)
// Create client
BigtableClient bigtableClient = await BigtableClient.CreateAsync();
// Initialize request argument(s)
MutateRowRequest request = new MutateRowRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.CopyFromUtf8(""),
Mutations = { },
};
// Make the request
MutateRowResponse response = await bigtableClient.MutateRowAsync(request);
// End snippet
}
/// <summary>Snippet for MutateRow</summary>
public void MutateRow_RequestObject()
{
// Snippet: MutateRow(MutateRowRequest,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument(s)
MutateRowRequest request = new MutateRowRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.CopyFromUtf8(""),
Mutations = { },
};
// Make the request
MutateRowResponse response = bigtableClient.MutateRow(request);
// End snippet
}
/// <summary>Snippet for MutateRows</summary>
public async Task MutateRows()
{
// Snippet: MutateRows(MutateRowsRequest,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument
MutateRowsRequest request = new MutateRowsRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
Entries = { },
};
// Make the request, returning a streaming response
BigtableClient.MutateRowsStream streamingResponse = bigtableClient.MutateRows(request);
// Read streaming responses from server until complete
IAsyncEnumerator<MutateRowsResponse> responseStream = streamingResponse.ResponseStream;
while (await responseStream.MoveNext())
{
MutateRowsResponse response = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for CheckAndMutateRowAsync</summary>
public async Task CheckAndMutateRowAsync()
{
// Snippet: CheckAndMutateRowAsync(TableName,ByteString,RowFilter,IEnumerable<Mutation>,IEnumerable<Mutation>,CallSettings)
// Additional: CheckAndMutateRowAsync(TableName,ByteString,RowFilter,IEnumerable<Mutation>,IEnumerable<Mutation>,CancellationToken)
// Create client
BigtableClient bigtableClient = await BigtableClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.CopyFromUtf8("");
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new List<Mutation>();
IEnumerable<Mutation> falseMutations = new List<Mutation>();
// Make the request
CheckAndMutateRowResponse response = await bigtableClient.CheckAndMutateRowAsync(tableName, rowKey, predicateFilter, trueMutations, falseMutations);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRow</summary>
public void CheckAndMutateRow()
{
// Snippet: CheckAndMutateRow(TableName,ByteString,RowFilter,IEnumerable<Mutation>,IEnumerable<Mutation>,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument(s)
TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.CopyFromUtf8("");
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new List<Mutation>();
IEnumerable<Mutation> falseMutations = new List<Mutation>();
// Make the request
CheckAndMutateRowResponse response = bigtableClient.CheckAndMutateRow(tableName, rowKey, predicateFilter, trueMutations, falseMutations);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRowAsync</summary>
public async Task CheckAndMutateRowAsync_RequestObject()
{
// Snippet: CheckAndMutateRowAsync(CheckAndMutateRowRequest,CallSettings)
// Create client
BigtableClient bigtableClient = await BigtableClient.CreateAsync();
// Initialize request argument(s)
CheckAndMutateRowRequest request = new CheckAndMutateRowRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.CopyFromUtf8(""),
};
// Make the request
CheckAndMutateRowResponse response = await bigtableClient.CheckAndMutateRowAsync(request);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRow</summary>
public void CheckAndMutateRow_RequestObject()
{
// Snippet: CheckAndMutateRow(CheckAndMutateRowRequest,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument(s)
CheckAndMutateRowRequest request = new CheckAndMutateRowRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.CopyFromUtf8(""),
};
// Make the request
CheckAndMutateRowResponse response = bigtableClient.CheckAndMutateRow(request);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRowAsync</summary>
public async Task ReadModifyWriteRowAsync()
{
// Snippet: ReadModifyWriteRowAsync(TableName,ByteString,IEnumerable<ReadModifyWriteRule>,CallSettings)
// Additional: ReadModifyWriteRowAsync(TableName,ByteString,IEnumerable<ReadModifyWriteRule>,CancellationToken)
// Create client
BigtableClient bigtableClient = await BigtableClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.CopyFromUtf8("");
IEnumerable<ReadModifyWriteRule> rules = new List<ReadModifyWriteRule>();
// Make the request
ReadModifyWriteRowResponse response = await bigtableClient.ReadModifyWriteRowAsync(tableName, rowKey, rules);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRow</summary>
public void ReadModifyWriteRow()
{
// Snippet: ReadModifyWriteRow(TableName,ByteString,IEnumerable<ReadModifyWriteRule>,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument(s)
TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.CopyFromUtf8("");
IEnumerable<ReadModifyWriteRule> rules = new List<ReadModifyWriteRule>();
// Make the request
ReadModifyWriteRowResponse response = bigtableClient.ReadModifyWriteRow(tableName, rowKey, rules);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRowAsync</summary>
public async Task ReadModifyWriteRowAsync_RequestObject()
{
// Snippet: ReadModifyWriteRowAsync(ReadModifyWriteRowRequest,CallSettings)
// Create client
BigtableClient bigtableClient = await BigtableClient.CreateAsync();
// Initialize request argument(s)
ReadModifyWriteRowRequest request = new ReadModifyWriteRowRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.CopyFromUtf8(""),
Rules = { },
};
// Make the request
ReadModifyWriteRowResponse response = await bigtableClient.ReadModifyWriteRowAsync(request);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRow</summary>
public void ReadModifyWriteRow_RequestObject()
{
// Snippet: ReadModifyWriteRow(ReadModifyWriteRowRequest,CallSettings)
// Create client
BigtableClient bigtableClient = BigtableClient.Create();
// Initialize request argument(s)
ReadModifyWriteRowRequest request = new ReadModifyWriteRowRequest
{
TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.CopyFromUtf8(""),
Rules = { },
};
// Make the request
ReadModifyWriteRowResponse response = bigtableClient.ReadModifyWriteRow(request);
// End snippet
}
}
}
| |
// OutputWindow.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace GitHub.ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// Contains the output from the Inflation process.
/// We need to have a window so that we can refer backwards into the output stream
/// to repeat stuff.<br/>
/// Author of the original java version : John Leuner
/// </summary>
public class OutputWindow
{
#region Constants
const int WindowSize = 1 << 15;
const int WindowMask = WindowSize - 1;
#endregion
#region Instance Fields
byte[] window = new byte[WindowSize]; //The window is 2^15 bytes
int windowEnd;
int windowFilled;
#endregion
/// <summary>
/// Write a byte to this output window
/// </summary>
/// <param name="value">value to write</param>
/// <exception cref="InvalidOperationException">
/// if window is full
/// </exception>
public void Write(int value)
{
if (windowFilled++ == WindowSize) {
throw new InvalidOperationException("Window full");
}
window[windowEnd++] = (byte) value;
windowEnd &= WindowMask;
}
private void SlowRepeat(int repStart, int length, int distance)
{
while (length-- > 0) {
window[windowEnd++] = window[repStart++];
windowEnd &= WindowMask;
repStart &= WindowMask;
}
}
/// <summary>
/// Append a byte pattern already in the window itself
/// </summary>
/// <param name="length">length of pattern to copy</param>
/// <param name="distance">distance from end of window pattern occurs</param>
/// <exception cref="InvalidOperationException">
/// If the repeated data overflows the window
/// </exception>
public void Repeat(int length, int distance)
{
if ((windowFilled += length) > WindowSize) {
throw new InvalidOperationException("Window full");
}
int repStart = (windowEnd - distance) & WindowMask;
int border = WindowSize - length;
if ( (repStart <= border) && (windowEnd < border) ) {
if (length <= distance) {
System.Array.Copy(window, repStart, window, windowEnd, length);
windowEnd += length;
} else {
// We have to copy manually, since the repeat pattern overlaps.
while (length-- > 0) {
window[windowEnd++] = window[repStart++];
}
}
} else {
SlowRepeat(repStart, length, distance);
}
}
/// <summary>
/// Copy from input manipulator to internal window
/// </summary>
/// <param name="input">source of data</param>
/// <param name="length">length of data to copy</param>
/// <returns>the number of bytes copied</returns>
public int CopyStored(StreamManipulator input, int length)
{
length = Math.Min(Math.Min(length, WindowSize - windowFilled), input.AvailableBytes);
int copied;
int tailLen = WindowSize - windowEnd;
if (length > tailLen) {
copied = input.CopyBytes(window, windowEnd, tailLen);
if (copied == tailLen) {
copied += input.CopyBytes(window, 0, length - tailLen);
}
} else {
copied = input.CopyBytes(window, windowEnd, length);
}
windowEnd = (windowEnd + copied) & WindowMask;
windowFilled += copied;
return copied;
}
/// <summary>
/// Copy dictionary to window
/// </summary>
/// <param name="dictionary">source dictionary</param>
/// <param name="offset">offset of start in source dictionary</param>
/// <param name="length">length of dictionary</param>
/// <exception cref="InvalidOperationException">
/// If window isnt empty
/// </exception>
public void CopyDict(byte[] dictionary, int offset, int length)
{
if ( dictionary == null ) {
throw new ArgumentNullException("dictionary");
}
if (windowFilled > 0) {
throw new InvalidOperationException();
}
if (length > WindowSize) {
offset += length - WindowSize;
length = WindowSize;
}
System.Array.Copy(dictionary, offset, window, 0, length);
windowEnd = length & WindowMask;
}
/// <summary>
/// Get remaining unfilled space in window
/// </summary>
/// <returns>Number of bytes left in window</returns>
public int GetFreeSpace()
{
return WindowSize - windowFilled;
}
/// <summary>
/// Get bytes available for output in window
/// </summary>
/// <returns>Number of bytes filled</returns>
public int GetAvailable()
{
return windowFilled;
}
/// <summary>
/// Copy contents of window to output
/// </summary>
/// <param name="output">buffer to copy to</param>
/// <param name="offset">offset to start at</param>
/// <param name="len">number of bytes to count</param>
/// <returns>The number of bytes copied</returns>
/// <exception cref="InvalidOperationException">
/// If a window underflow occurs
/// </exception>
public int CopyOutput(byte[] output, int offset, int len)
{
int copyEnd = windowEnd;
if (len > windowFilled) {
len = windowFilled;
} else {
copyEnd = (windowEnd - windowFilled + len) & WindowMask;
}
int copied = len;
int tailLen = len - copyEnd;
if (tailLen > 0) {
System.Array.Copy(window, WindowSize - tailLen, output, offset, tailLen);
offset += tailLen;
len = copyEnd;
}
System.Array.Copy(window, copyEnd - len, output, offset, len);
windowFilled -= copied;
if (windowFilled < 0) {
throw new InvalidOperationException();
}
return copied;
}
/// <summary>
/// Reset by clearing window so <see cref="GetAvailable">GetAvailable</see> returns 0
/// </summary>
public void Reset()
{
windowFilled = windowEnd = 0;
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2006, Frank Blumenberg
//
// See License.txt for complete licensing and attribution information.
// 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.
//
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//
// This code contains code from SimplePsd class library by Igor Tolmachev.
// http://www.codeproject.com/csharp/simplepsd.asp
//
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
namespace PhotoshopFile
{
public class ImageDecoder
{
public ImageDecoder()
{
}
///////////////////////////////////////////////////////////////////////////
#if !TEST
public struct PixelData
{
public byte Blue;
public byte Green;
public byte Red;
public byte Alpha;
}
#endif
///////////////////////////////////////////////////////////////////////////
public static int BytesFromBits(int bits)
{
return (bits + 7) / 8;
}
///////////////////////////////////////////////////////////////////////////
public static int RoundUp(int value, int stride)
{
return ((value + stride - 1) / stride) * stride;
}
///////////////////////////////////////////////////////////////////////////
public static byte GetBitmapValue(byte[] bitmap, int pos)
{
byte mask = (byte)(0x80 >> (pos % 8));
byte bwValue = (byte)(bitmap[pos / 8] & mask);
bwValue = (bwValue == 0) ? (byte)255 : (byte)0;
return bwValue;
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Decodes the main, composed layer of a PSD file into a bitmap with no transparency.
/// </summary>
/// <param name="psdFile"></param>
/// <returns></returns>
public static Bitmap DecodeImage(PsdFile psdFile)
{
Bitmap bitmap = new Bitmap(psdFile.Columns, psdFile.Rows, PixelFormat.Format32bppArgb);
#if TEST
for (int y = 0; y < psdFile.Rows; y++)
{
int rowIndex = y * psdFile.Columns;
for (int x = 0; x < psdFile.Columns; x++)
{
int pos = rowIndex + x;
Color pixelColor=GetColor(psdFile,pos);
bitmap.SetPixel(x, y, pixelColor);
}
}
#else
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bd = bitmap.LockBits(r, ImageLockMode.ReadWrite, bitmap.PixelFormat);
unsafe
{
byte* pCurrRowPixel = (byte*)bd.Scan0.ToPointer();
for (int y = 0; y < psdFile.Rows; y++)
{
int rowIndex = y * psdFile.Columns;
PixelData* pCurrPixel = (PixelData*)pCurrRowPixel;
for (int x = 0; x < psdFile.Columns; x++)
{
int pos = rowIndex + x;
Color pixelColor = GetColor(psdFile, pos);
pCurrPixel->Alpha = 255;
pCurrPixel->Red = pixelColor.R;
pCurrPixel->Green = pixelColor.G;
pCurrPixel->Blue = pixelColor.B;
pCurrPixel += 1;
}
pCurrRowPixel += bd.Stride;
}
}
bitmap.UnlockBits(bd);
#endif
return bitmap;
}
///////////////////////////////////////////////////////////////////////////
private static Color GetColor(PsdFile psdFile, int pos)
{
Color c = Color.White;
switch (psdFile.ColorMode)
{
case PsdFile.ColorModes.RGB:
c = Color.FromArgb(psdFile.ImageData[0][pos],
psdFile.ImageData[1][pos],
psdFile.ImageData[2][pos]);
break;
case PsdFile.ColorModes.CMYK:
c = CMYKToRGB(psdFile.ImageData[0][pos],
psdFile.ImageData[1][pos],
psdFile.ImageData[2][pos],
psdFile.ImageData[3][pos]);
break;
case PsdFile.ColorModes.Multichannel:
c = CMYKToRGB(psdFile.ImageData[0][pos],
psdFile.ImageData[1][pos],
psdFile.ImageData[2][pos],
0);
break;
case PsdFile.ColorModes.Bitmap:
byte bwValue = ImageDecoder.GetBitmapValue(psdFile.ImageData[0], pos);
c = Color.FromArgb(bwValue, bwValue, bwValue);
break;
case PsdFile.ColorModes.Grayscale:
case PsdFile.ColorModes.Duotone:
c = Color.FromArgb(psdFile.ImageData[0][pos],
psdFile.ImageData[0][pos],
psdFile.ImageData[0][pos]);
break;
case PsdFile.ColorModes.Indexed:
{
int index = (int)psdFile.ImageData[0][pos];
c = Color.FromArgb((int)psdFile.ColorModeData[index],
psdFile.ColorModeData[index + 256],
psdFile.ColorModeData[index + 2 * 256]);
}
break;
case PsdFile.ColorModes.Lab:
{
c = LabToRGB(psdFile.ImageData[0][pos],
psdFile.ImageData[1][pos],
psdFile.ImageData[2][pos]);
}
break;
}
return c;
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Decodes a layer to create a bitmap with transparency.
/// </summary>
/// <param name="layer"></param>
/// <returns></returns>
public static Bitmap DecodeImage(Layer layer)
{
int width = layer.Rect.Width;
int height = layer.Rect.Height;
if (width == 0 || height == 0) return null;
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
#if TEST
for (int y = 0; y < layer.Rect.Height; y++)
{
int rowIndex = y * layer.Rect.Width;
for (int x = 0; x < layer.Rect.Width; x++)
{
int pos = rowIndex + x;
//Color pixelColor=GetColor(psdFile,pos);
Color pixelColor = Color.FromArgb(x % 255, Color.ForestGreen);// 255, 128, 0);
bitmap.SetPixel(x, y, pixelColor);
}
}
#else
Rectangle r = new Rectangle(0, 0, width, height);
BitmapData bd = bitmap.LockBits(r, ImageLockMode.ReadWrite, bitmap.PixelFormat);
LayerWrapper l = new LayerWrapper(layer);
unsafe
{
byte* pCurrRowPixel = (byte*)bd.Scan0.ToPointer();
for (int y = 0; y < height; y++)
{
int rowIndex = y * width;
PixelData* pCurrPixel = (PixelData*)pCurrRowPixel;
for (int x = 0; x < width; x++)
{
int pos = rowIndex + x;
//Fast path for RGB mode, somewhat inlined.
if (l.colorMode == PsdFile.ColorModes.RGB)
{
//Add alpha channel if it exists.
if (l.hasalpha)
pCurrPixel->Alpha = l.alphabytes[pos];
else
pCurrPixel->Alpha = 255;
//Apply mask if present.
if (l.hasmask)
pCurrPixel->Alpha = (byte)((pCurrPixel->Alpha * GetMaskValue(layer.MaskData, x, y)) / 255);
pCurrPixel->Red = l.ch0bytes[pos];
pCurrPixel->Green = l.ch1bytes[pos];
pCurrPixel->Blue = l.ch2bytes[pos];
}
else
{
Color pixelColor = GetColor(l, pos);
if (l.hasmask)
{
int maskAlpha = GetMaskValue(layer.MaskData, x, y);
int oldAlpha = pixelColor.A;
int newAlpha = (oldAlpha * maskAlpha) / 255;
pixelColor = Color.FromArgb(newAlpha, pixelColor);
}
pCurrPixel->Alpha = pixelColor.A;
pCurrPixel->Red = pixelColor.R;
pCurrPixel->Green = pixelColor.G;
pCurrPixel->Blue = pixelColor.B;
}
pCurrPixel += 1;
}
pCurrRowPixel += bd.Stride;
}
}
bitmap.UnlockBits(bd);
#endif
return bitmap;
}
/// <summary>
/// This class caches direct references to objects used for every pixel, bypassing b-tree lookups and dereferencing.
/// </summary>
private class LayerWrapper
{
public LayerWrapper(Layer l)
{
colorMode = l.PsdFile.ColorMode;
hasalpha = l.SortedChannels.ContainsKey(-1);
hasmask = l.SortedChannels.ContainsKey(-2);
hasch0 = l.SortedChannels.ContainsKey(0);
hasch1 = l.SortedChannels.ContainsKey(1);
hasch2 = l.SortedChannels.ContainsKey(2);
hasch3 = l.SortedChannels.ContainsKey(3);
if (hasalpha) alphabytes = l.SortedChannels[-1].ImageData;
if (hasmask) mask = l.MaskData;
if (hasch0) ch0bytes = l.SortedChannels[0].ImageData;
if (hasch1) ch1bytes = l.SortedChannels[1].ImageData;
if (hasch2) ch2bytes = l.SortedChannels[2].ImageData;
if (hasch3) ch3bytes = l.SortedChannels[3].ImageData;
colorModeData = l.PsdFile.ColorModeData;
}
public PsdFile.ColorModes colorMode;
public byte[] colorModeData;
public byte[] alphabytes;
public Layer.Mask mask;
public byte[] ch0bytes;
public byte[] ch1bytes;
public byte[] ch2bytes;
public byte[] ch3bytes;
public bool hasalpha;
public bool hasmask;
public bool hasch0;
public bool hasch1;
public bool hasch2;
public bool hasch3;
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Builds a color instance from the specified layer and position. Adds alpha value if channel exists.
/// </summary>
/// <param name="layer"></param>
/// <param name="pos"></param>
/// <returns></returns>
private static Color GetColor(LayerWrapper layer, int pos)
{
Color c = Color.White;
switch (layer.colorMode)
{
case PsdFile.ColorModes.RGB:
c = Color.FromArgb(layer.ch0bytes[pos],
layer.ch1bytes[pos],
layer.ch2bytes[pos]);
break;
case PsdFile.ColorModes.CMYK:
c = CMYKToRGB(layer.ch0bytes[pos],
layer.ch1bytes[pos],
layer.ch2bytes[pos],
layer.ch3bytes[pos]);
break;
case PsdFile.ColorModes.Multichannel:
c = CMYKToRGB(layer.ch0bytes[pos],
layer.ch1bytes[pos],
layer.ch2bytes[pos],
0);
break;
case PsdFile.ColorModes.Bitmap:
byte bwValue = ImageDecoder.GetBitmapValue(layer.ch0bytes, pos);
c = Color.FromArgb(bwValue, bwValue, bwValue);
break;
case PsdFile.ColorModes.Grayscale:
case PsdFile.ColorModes.Duotone:
c = Color.FromArgb(layer.ch0bytes[pos],
layer.ch0bytes[pos],
layer.ch0bytes[pos]);
break;
case PsdFile.ColorModes.Indexed:
{
int index = (int)layer.ch0bytes[pos];
c = Color.FromArgb((int)layer.colorModeData[index],
layer.colorModeData[index + 256],
layer.colorModeData[index + 2 * 256]);
}
break;
case PsdFile.ColorModes.Lab:
{
c = LabToRGB(layer.ch0bytes[pos],
layer.ch1bytes[pos],
layer.ch2bytes[pos]);
}
break;
}
if (layer.hasalpha)
c = Color.FromArgb(layer.alphabytes[pos], c);
return c;
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the alpha value of the mask at the specified coordinates
/// </summary>
/// <param name="mask"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
private static int GetMaskValue(Layer.Mask mask, int x, int y)
{
int c = 255;
if (mask.PositionIsRelative)
{
x -= mask.Rect.X;
y -= mask.Rect.Y;
}
else
{
x = (x + mask.Layer.Rect.X) - mask.Rect.X;
y = (y + mask.Layer.Rect.Y) - mask.Rect.Y;
}
if (y >= 0 && y < mask.Rect.Height &&
x >= 0 && x < mask.Rect.Width)
{
int pos = y * mask.Rect.Width + x;
if (pos < mask.ImageData.Length)
c = mask.ImageData[pos];
else
c = 255;
}
return c;
}
///////////////////////////////////////////////////////////////////////////
public static Bitmap DecodeImage(Layer.Mask mask)
{
Layer layer = mask.Layer;
if (mask.Rect.Width == 0 || mask.Rect.Height == 0)
{
return null;
}
Bitmap bitmap = new Bitmap(mask.Rect.Width, mask.Rect.Height, PixelFormat.Format32bppArgb);
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bd = bitmap.LockBits(r, ImageLockMode.ReadWrite, bitmap.PixelFormat);
unsafe
{
byte* pCurrRowPixel = (byte*)bd.Scan0.ToPointer();
for (int y = 0; y < mask.Rect.Height; y++)
{
int rowIndex = y * mask.Rect.Width;
PixelData* pCurrPixel = (PixelData*)pCurrRowPixel;
for (int x = 0; x < mask.Rect.Width; x++)
{
int pos = rowIndex + x;
Color pixelColor = Color.FromArgb(mask.ImageData[pos], mask.ImageData[pos], mask.ImageData[pos]);
pCurrPixel->Alpha = 255;
pCurrPixel->Red = pixelColor.R;
pCurrPixel->Green = pixelColor.G;
pCurrPixel->Blue = pixelColor.B;
pCurrPixel += 1;
}
pCurrRowPixel += bd.Stride;
}
}
bitmap.UnlockBits(bd);
return bitmap;
}
///////////////////////////////////////////////////////////////////////////
private static Color LabToRGB(byte lb, byte ab, byte bb)
{
double exL, exA, exB;
exL = (double)lb;
exA = (double)ab;
exB = (double)bb;
double L_coef, a_coef, b_coef;
L_coef = 256.0 / 100.0;
a_coef = 256.0 / 256.0;
b_coef = 256.0 / 256.0;
int L = (int)(exL / L_coef);
int a = (int)(exA / a_coef - 128.0);
int b = (int)(exB / b_coef - 128.0);
// For the conversion we first convert values to XYZ and then to RGB
// Standards used Observer = 2, Illuminant = D65
const double ref_X = 95.047;
const double ref_Y = 100.000;
const double ref_Z = 108.883;
double var_Y = ((double)L + 16.0) / 116.0;
double var_X = (double)a / 500.0 + var_Y;
double var_Z = var_Y - (double)b / 200.0;
if (Math.Pow(var_Y, 3) > 0.008856)
var_Y = Math.Pow(var_Y, 3);
else
var_Y = (var_Y - 16 / 116) / 7.787;
if (Math.Pow(var_X, 3) > 0.008856)
var_X = Math.Pow(var_X, 3);
else
var_X = (var_X - 16 / 116) / 7.787;
if (Math.Pow(var_Z, 3) > 0.008856)
var_Z = Math.Pow(var_Z, 3);
else
var_Z = (var_Z - 16 / 116) / 7.787;
double X = ref_X * var_X;
double Y = ref_Y * var_Y;
double Z = ref_Z * var_Z;
return XYZToRGB(X, Y, Z);
}
////////////////////////////////////////////////////////////////////////////
private static Color XYZToRGB(double X, double Y, double Z)
{
// Standards used Observer = 2, Illuminant = D65
// ref_X = 95.047, ref_Y = 100.000, ref_Z = 108.883
double var_X = X / 100.0;
double var_Y = Y / 100.0;
double var_Z = Z / 100.0;
double var_R = var_X * 3.2406 + var_Y * (-1.5372) + var_Z * (-0.4986);
double var_G = var_X * (-0.9689) + var_Y * 1.8758 + var_Z * 0.0415;
double var_B = var_X * 0.0557 + var_Y * (-0.2040) + var_Z * 1.0570;
if (var_R > 0.0031308)
var_R = 1.055 * (Math.Pow(var_R, 1 / 2.4)) - 0.055;
else
var_R = 12.92 * var_R;
if (var_G > 0.0031308)
var_G = 1.055 * (Math.Pow(var_G, 1 / 2.4)) - 0.055;
else
var_G = 12.92 * var_G;
if (var_B > 0.0031308)
var_B = 1.055 * (Math.Pow(var_B, 1 / 2.4)) - 0.055;
else
var_B = 12.92 * var_B;
int nRed = (int)(var_R * 256.0);
int nGreen = (int)(var_G * 256.0);
int nBlue = (int)(var_B * 256.0);
if (nRed < 0) nRed = 0;
else if (nRed > 255) nRed = 255;
if (nGreen < 0) nGreen = 0;
else if (nGreen > 255) nGreen = 255;
if (nBlue < 0) nBlue = 0;
else if (nBlue > 255) nBlue = 255;
return Color.FromArgb(nRed, nGreen, nBlue);
}
///////////////////////////////////////////////////////////////////////////////
//
// The algorithms for these routines were taken from:
// http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html
//
// RGB --> CMYK CMYK --> RGB
// --------------------------------------- --------------------------------------------
// Black = minimum(1-Red,1-Green,1-Blue) Red = 1-minimum(1,Cyan*(1-Black)+Black)
// Cyan = (1-Red-Black)/(1-Black) Green = 1-minimum(1,Magenta*(1-Black)+Black)
// Magenta = (1-Green-Black)/(1-Black) Blue = 1-minimum(1,Yellow*(1-Black)+Black)
// Yellow = (1-Blue-Black)/(1-Black)
//
private static Color CMYKToRGB(byte c, byte m, byte y, byte k)
{
double C, M, Y, K;
double exC, exM, exY, exK;
double dMaxColours = Math.Pow(2, 8);
exC = (double)c;
exM = (double)m;
exY = (double)y;
exK = (double)k;
C = (1.0 - exC / dMaxColours);
M = (1.0 - exM / dMaxColours);
Y = (1.0 - exY / dMaxColours);
K = (1.0 - exK / dMaxColours);
int nRed = (int)((1.0 - (C * (1 - K) + K)) * 255);
int nGreen = (int)((1.0 - (M * (1 - K) + K)) * 255);
int nBlue = (int)((1.0 - (Y * (1 - K) + K)) * 255);
if (nRed < 0) nRed = 0;
else if (nRed > 255) nRed = 255;
if (nGreen < 0) nGreen = 0;
else if (nGreen > 255) nGreen = 255;
if (nBlue < 0) nBlue = 0;
else if (nBlue > 255) nBlue = 255;
return Color.FromArgb(nRed, nGreen, nBlue);
}
}
}
| |
using System;
using System.Text;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Tests
{
/// <remarks>
/// MAC tester - vectors from
/// <a href="http://www.itl.nist.gov/fipspubs/fip81.htm">FIP 81</a> and
/// <a href="http://www.itl.nist.gov/fipspubs/fip113.htm">FIP 113</a>.
/// </remarks>
[TestFixture]
public class MacTest
: SimpleTest
{
private static readonly byte[] keyBytes = Hex.Decode("0123456789abcdef");
private static readonly byte[] ivBytes = Hex.Decode("1234567890abcdef");
private static readonly byte[] input = Hex.Decode("37363534333231204e6f77206973207468652074696d6520666f7220");
private static readonly byte[] output1 = Hex.Decode("f1d30f68");
private static readonly byte[] output2 = Hex.Decode("58d2e77e");
private static readonly byte[] output3 = Hex.Decode("cd647403");
private static readonly byte[] keyBytesISO9797 = Hex.Decode("7CA110454A1A6E570131D9619DC1376E");
private static readonly byte[] inputISO9797 = Encoding.ASCII.GetBytes("Hello World !!!!");
private static readonly byte[] outputISO9797 = Hex.Decode("F09B856213BAB83B");
private static readonly byte[] inputDesEDE64 = Encoding.ASCII.GetBytes("Hello World !!!!");
private static readonly byte[] outputDesEDE64 = Hex.Decode("862304d33af01096");
private void aliasTest(
KeyParameter key,
string primary,
params string[] aliases)
{
IMac mac = MacUtilities.GetMac(primary);
//
// standard DAC - zero IV
//
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
byte[] refBytes = new byte[mac.GetMacSize()];
mac.DoFinal(refBytes, 0);
for (int i = 0; i != aliases.Length; i++)
{
mac = MacUtilities.GetMac(aliases[i]);
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
byte[] outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, refBytes))
{
Fail("Failed - expected "
+ Hex.ToHexString(refBytes) + " got "
+ Hex.ToHexString(outBytes));
}
}
}
public override void PerformTest()
{
KeyParameter key = new DesParameters(keyBytes);
IMac mac = MacUtilities.GetMac("DESMac");
//
// standard DAC - zero IV
//
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
//byte[] outBytes = mac.DoFinal();
byte[] outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output1))
{
Fail("Failed - expected "
+ Hex.ToHexString(output1) + " got "
+ Hex.ToHexString(outBytes));
}
//
// mac with IV.
//
mac.Init(new ParametersWithIV(key, ivBytes));
mac.BlockUpdate(input, 0, input.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output2))
{
Fail("Failed - expected "
+ Hex.ToHexString(output2) + " got "
+ Hex.ToHexString(outBytes));
}
//
// CFB mac with IV - 8 bit CFB mode
//
mac = MacUtilities.GetMac("DESMac/CFB8");
mac.Init(new ParametersWithIV(key, ivBytes));
mac.BlockUpdate(input, 0, input.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output3))
{
Fail("Failed - expected "
+ Hex.ToHexString(output3) + " got "
+ Hex.ToHexString(outBytes));
}
//
// ISO9797 algorithm 3 using DESEDE
//
key = new DesEdeParameters(keyBytesISO9797);
mac = MacUtilities.GetMac("ISO9797ALG3");
mac.Init(key);
mac.BlockUpdate(inputISO9797, 0, inputISO9797.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, outputISO9797))
{
Fail("Failed - expected "
+ Hex.ToHexString(outputISO9797) + " got "
+ Hex.ToHexString(outBytes));
}
//
// 64bit DESede Mac
//
key = new DesEdeParameters(keyBytesISO9797);
mac = MacUtilities.GetMac("DESEDE64");
mac.Init(key);
mac.BlockUpdate(inputDesEDE64, 0, inputDesEDE64.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, outputDesEDE64))
{
Fail("Failed - expected "
+ Hex.ToHexString(outputDesEDE64) + " got "
+ Hex.ToHexString(outBytes));
}
aliasTest(
ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
"DESedeMac64withISO7816-4Padding",
"DESEDE64WITHISO7816-4PADDING",
"DESEDEISO9797ALG1MACWITHISO7816-4PADDING",
"DESEDEISO9797ALG1WITHISO7816-4PADDING");
aliasTest(
ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
"ISO9797ALG3WITHISO7816-4PADDING",
"ISO9797ALG3MACWITHISO7816-4PADDING");
}
public override string Name
{
get { return "Mac"; }
}
public static void Main(
string[] args)
{
RunTest(new MacTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Windows.Forms;
using System.Text;
using Epi;
using Epi.Data;
using Epi.Windows.Dialogs;
namespace Epi.Windows.Dialogs
{
public enum SelectedItemType
{
Form,
Table
}
/// <summary>
/// Dialog for Read command
/// </summary>
public partial class ReadRelatedDialog : DialogBase
{
#region Private Nested Class
private class ComboBoxItem
{
#region Implementation
private string key;
public string Key
{
get { return key; }
set { key = value; }
}
private object value;
public object Value
{
get { return this.value; }
set { this.value = value; }
}
private string text;
public string Text
{
get { return text; }
set { text = value; }
}
public ComboBoxItem(string key, string text, object value)
{
this.key = key;
this.value = value;
this.text = text;
}
public override string ToString()
{
return text.ToString();
}
#endregion
}
#endregion Private Nested Class
#region Private Attributes
private SelectedItemType selectedItemType;
private string selectedDataProvider;
private string mruSelectedDatabaseName;
private Project selectedProject;
private object selectedDataSource;
private bool ignoreDataFormatIndexChange = false;
private string savedConnectionStringDescription = string.Empty;
private Dictionary<string, string> parentTableColumnNames;
private bool useUnmatched = true;
#endregion Private Attributes
#region Constructor
public ReadRelatedDialog(Dictionary<string, string> parentTableColumnNames)
{
InitializeComponent();
Construct();
this.parentTableColumnNames = parentTableColumnNames;
}
public ReadRelatedDialog(IDbDriver database, Dictionary<string, string> parentTableColumnNames)
{
InitializeComponent();
Construct();
selectedDataSource = database;
this.parentTableColumnNames = parentTableColumnNames;
SelectedItemType = Dialogs.SelectedItemType.Table;
}
public ReadRelatedDialog(Project project, Dictionary<string, string> parentTableColumnNames)
{
InitializeComponent();
Construct();
selectedDataSource = project;
selectedProject = project;
this.parentTableColumnNames = parentTableColumnNames;
SelectedItemType = Dialogs.SelectedItemType.Form;
RefreshForm();
}
#endregion Constructor
#region Private Methods
private void Construct()
{
if (!this.DesignMode) // designer throws an error
{
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
}
}
private void btnOK_Click(object sender, System.EventArgs e)
{
OnOK();
}
private void LoadForm()
{
PopulateDataSourcePlugIns();
PopulateRecentDataSources();
List<string> cols = new List<string>();
foreach (KeyValuePair<string, string> kvp in parentTableColumnNames)
{
cols.Add(kvp.Key);
}
cols.Sort();
cmbParentKey.DataSource = cols;
try
{
//Project project = null;
//string filePath = System.IO.Directory.GetCurrentDirectory().ToString() + "\\Projects\\Sample.prj";
//if (System.IO.File.Exists(filePath))
//{
// Project prj = new Project(filePath);
// try
// {
// selectedDataSource = prj;
// this.selectedProject = prj;
// this.selectedDataSource = prj;
// }
// catch (Exception ex)
// {
// MessageBox.Show("Could not load project: \n\n" + ex.Message);
// return;
// }
//}
}
catch (CurrentProjectInvalidException ex)
{
Epi.Windows.MsgBox.ShowInformation(ex.Message);
}
RefreshForm();
}
private void RefreshForm()
{
lvDataSourceObjects.Groups.Clear();
lvDataSourceObjects.Items.Clear();
if (selectedDataSource is IDbDriver)
{
IDbDriver db = selectedDataSource as IDbDriver;
switch (db.ToString())
{
case "Epi.Data.Office.AccessDatabase":
case "Epi.Data.Office.Access2007Database":
case "Epi.Data.Office.ExcelWorkbook":
case "Epi.Data.Office.Excel2007Workbook":
this.txtDataSource.Text = db.DataSource;
break;
default:
this.txtDataSource.Text = db.ConnectionString;
break;
}
List<string> tableNames = db.GetTableNames();
foreach (string tableName in tableNames)
{
ListViewItem newItem = new ListViewItem(new string[] { tableName, tableName });
this.lvDataSourceObjects.Items.Add(newItem);
}
gbxExplorer.Enabled = true;
}
else if (selectedDataSource is Project)
{
Project project = selectedDataSource as Project;
txtDataSource.Text = (selectedDataSource == selectedProject) ? SharedStrings.CURRENT_PROJECT : project.FullName;
try
{
if (chkViews.Checked)
{
ListViewGroup viewGroup = new ListViewGroup("Epi Info Forms");
this.lvDataSourceObjects.Groups.Add(viewGroup);
foreach (string s in project.GetViewNames())
{
ListViewItem newItem = new ListViewItem(new string[] { s, "View" }, viewGroup);
this.lvDataSourceObjects.Items.Add(newItem);
}
}
if (chkTables.Checked)
{
ListViewGroup tablesGroup = new ListViewGroup("Tables");
this.lvDataSourceObjects.Groups.Add(tablesGroup);
foreach (string s in project.GetNonViewTableNames())
{
ListViewItem newItem = new ListViewItem(new string[] { s, "Table" }, tablesGroup);
this.lvDataSourceObjects.Items.Add(newItem);
}
}
}
catch (Exception ex)
{
Epi.Windows.MsgBox.ShowException(ex);
txtDataSource.Text = string.Empty;
return;
}
gbxExplorer.Enabled = true;
}
else
{
// Clear ...
this.txtDataSource.Text = "(none)";
this.lvDataSourceObjects.Items.Clear();// DataSource = null;
gbxExplorer.Enabled = false;
}
this.CheckForInputSufficiency();
}
/// <summary>
/// Attach the DataFormats combobox with supported data formats
/// </summary>
private void PopulateDataSourcePlugIns()
{
try
{
Configuration config = Configuration.GetNewInstance();
ignoreDataFormatIndexChange = true;
if (cmbDataSourcePlugIns.Items.Count == 0)
{
cmbDataSourcePlugIns.Items.Clear();
cmbDataSourcePlugIns.Items.Add(new ComboBoxItem(null, "Epi Info 7 Project", null));
foreach (Epi.DataSets.Config.DataDriverRow row in config.DataDrivers)
{
cmbDataSourcePlugIns.Items.Add(new ComboBoxItem(row.Type,row.DisplayName,null));
}
}
cmbDataSourcePlugIns.SelectedIndex = 0;
}
finally
{
ignoreDataFormatIndexChange = false;
}
}
/// <summary>
/// Attach the Recent data sources combobox with the list of recent sources
/// </summary>
private void PopulateRecentDataSources()
{
try
{
Configuration config = Configuration.GetNewInstance();
ignoreDataFormatIndexChange = true;
if (cmbRecentSources.Items.Count == 0)
{
cmbRecentSources.Items.Clear();
cmbRecentSources.Items.Add(string.Empty);
foreach (Epi.DataSets.Config.RecentDataSourceRow row in config.RecentDataSources)
{
cmbRecentSources.Items.Add(new ComboBoxItem(row.DataProvider, row.Name, row.ConnectionString));
}
}
cmbRecentSources.SelectedIndex = 0;
}
finally
{
ignoreDataFormatIndexChange = false;
}
}
private void OpenSelectProjectDialog()
{
try
{
Project oldSelectedProject = this.selectedProject;
Project newSelectedProject = base.SelectProject();
if (newSelectedProject != null)
{
this.selectedProject = newSelectedProject;
if (oldSelectedProject != newSelectedProject)
{
SetDataSourceToSelectedProject();
}
this.RefreshForm();
}
}
catch (Exception ex)
{
MsgBox.ShowException(ex);
}
}
private void SetDataSourceToSelectedProject()
{
this.selectedDataSource = selectedProject;
this.cmbDataSourcePlugIns.SelectedIndex = 0;
}
private void OpenSelectDataSourceDialog()
{
bool formNeedsRefresh = false;
ComboBoxItem selectedPlugIn = cmbDataSourcePlugIns.SelectedItem as ComboBoxItem;
if (selectedPlugIn == null)
{
throw new GeneralException("No data source plug-in is selected in combo box.");
}
if (selectedPlugIn.Key == null)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = SharedStrings.SELECT_DATA_SOURCE;
openFileDialog.Filter = "Epi Info " + SharedStrings.PROJECT_FILE + " (*.prj)|*.prj";
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false;
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
string filePath = openFileDialog.FileName.Trim();
if (System.IO.File.Exists(filePath))
{
try
{
selectedDataSource = new Project(filePath);
formNeedsRefresh = true;
}
catch (Exception ex)
{
MessageBox.Show("Could not load project: \n\n" + ex.Message);
return;
}
}
}
}
else
{
IDbDriverFactory dbFactory = null;
selectedDataProvider = selectedPlugIn.Key;
dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(selectedPlugIn.Key);
if (dbFactory.ArePrerequisitesMet())
{
DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();
if (!string.IsNullOrEmpty(savedConnectionStringDescription))
{
int splitIndex = savedConnectionStringDescription.IndexOf("::");
if (splitIndex > -1)
{
string serverName = savedConnectionStringDescription.Substring(0, splitIndex);
string databaseName = savedConnectionStringDescription.Substring(splitIndex + 2, savedConnectionStringDescription.Length - splitIndex - 2);
dialog.SetDatabaseName(databaseName);
dialog.SetServerName(serverName);
}
}
DialogResult result = ((Form)dialog).ShowDialog();
if (result == DialogResult.OK)
{
this.savedConnectionStringDescription = dialog.ConnectionStringDescription;
bool success = false;
db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();
try
{
success = db.TestConnection();
}
catch
{
success = false;
MessageBox.Show("Could not connect to selected data source.");
}
if (success)
{
this.selectedDataSource = db;
formNeedsRefresh = true;
}
else
{
this.selectedDataSource = null;
}
}
else
{
this.selectedDataSource = null;
}
}
else
{
MessageBox.Show(dbFactory.PrerequisiteMessage, "Prerequisites not found");
}
}
if (formNeedsRefresh)
{
RefreshForm();
}
}
#endregion Private Methods
#region Protected Methods
/// <summary>
/// Validates input
/// </summary>
/// <returns>true if validation passes; else false</returns>
protected override bool ValidateInput()
{
base.ValidateInput ();
if (cmbDataSourcePlugIns.SelectedIndex == -1)
{
ErrorMessages.Add(SharedStrings.SPECIFY_DATAFORMAT);
}
if (string.IsNullOrEmpty(txtDataSource.Text))
{
ErrorMessages.Add(SharedStrings.SPECIFY_DATASOURCE);
}
if (this.lvDataSourceObjects.SelectedIndices.Count == 0)
{
ErrorMessages.Add(SharedStrings.SPECIFY_TABLE_OR_VIEW);
}
return (ErrorMessages.Count == 0);
}
/// <summary>
/// Generate the Read command
/// </summary>
protected void GenerateCommand()
{
StringBuilder sb = new StringBuilder();
sb.Append(Epi.CommandNames.READ);
sb.Append(StringLiterals.SPACE);
string dsName = txtDataSource.Text;
if (dsName.Equals(SharedStrings.CURRENT_PROJECT))
{
dsName = selectedProject.FilePath;
}
if (!(cmbDataSourcePlugIns.SelectedItem.ToString().Equals("Epi Info 7 Project")))
{
selectedProject = null;
}
if (!string.IsNullOrEmpty(dsName) && !dsName.Equals(SharedStrings.CURRENT_PROJECT))
{
sb.Append("{").Append(dsName).Append("}");
}
if (!dsName.Equals(SharedStrings.CURRENT_PROJECT))
{
sb.Append(StringLiterals.COLON);
}
//Delete this line once complex read is implemented
string Identifier = lvDataSourceObjects.SelectedItems[0].Text;
if (Identifier.IndexOf(' ') > -1)
{
sb.Append('[');
sb.Append(Identifier);
sb.Append(']');
}
else
{
sb.Append(Identifier);
}
sb.Append(StringLiterals.SPACE);
//CommandText = sb.ToString();
}
public bool UseUnmatched
{
get
{
return useUnmatched;
}
set
{
this.useUnmatched = value;
}
}
public object SelectedDataSource
{
get
{
return selectedDataSource;
}
}
public string SelectedDataMember
{
get
{
return lvDataSourceObjects.SelectedItems[0].Text;
}
}
public string ChildKeyField
{
get
{
return this.cmbChildKey.Text;
}
}
public string ParentKeyField
{
get
{
return this.cmbParentKey.Text;
}
}
public string SelectedDataProvider
{
get
{
return selectedDataProvider;
}
}
public SelectedItemType SelectedItemType
{
get
{
return this.selectedItemType;
}
set
{
selectedItemType = value;
}
}
/// <summary>
/// Before executing the command, preprocesses information gathered from the dialog.
/// If the current project has changed, updates Global.CurrentProject
/// </summary>
protected void PreProcess()
{
//base.PreProcess();
// dcs0 8/13/2008 the below doesn't seem necessary, the command processor should do all of this
//IProjectHost host = Module.GetService(typeof(IProjectHost)) as IProjectHost;
//if (host == null)
//{
// throw new GeneralException("No project is hosted by service provider.");
//}
//if ((host.CurrentProject == null) || (!host.CurrentProject.Equals(this.selectedProject)))
//{
// Configuration config = Configuration.GetNewInstance();
// host.CurrentProject = this.selectedProject;
// config.CurrentProjectFilePath = selectedProject.FullName;
// Configuration.Save(config);
//}
// add to the config
Configuration config = Configuration.GetNewInstance();
string name = string.Empty;
string connectionString = string.Empty;
string dataProvider = string.Empty;
if (SelectedDataSource is IDbDriver)
{
IDbDriver db = selectedDataSource as IDbDriver;
name = db.DbName;
connectionString = db.ConnectionString;
dataProvider = SelectedDataProvider;
}
else if (SelectedDataSource is Project)
{
Project project = selectedDataSource as Project;
name = project.FileName;
connectionString = project.FilePath;
dataProvider = project.CollectedDataDriver;
}
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(connectionString))
{
Configuration.OnDataSourceAccessed(name, Configuration.Encrypt(connectionString), dataProvider);
}
}
/// <summary>
/// Checks if the input provided is sufficient and enables control buttons accordingly.
/// </summary>
public override void CheckForInputSufficiency()
{
bool inputValid = ValidateInput();
btnOK.Enabled = inputValid;
}
#endregion Protected Methods
#region Event Handlers
private void ReadDialog_Load(object sender, System.EventArgs e)
{
LoadForm();
}
private void btnFindProject_Click(object sender, System.EventArgs e)
{
OpenSelectProjectDialog();
}
private void cmbDataSourcePlugIns_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (ignoreDataFormatIndexChange) return;
ComboBox CB = (ComboBox) sender;
if (CB.SelectedIndex == 0)
{
chkViews.Enabled = true;
chkTables.Enabled = true;
}
else
{
chkViews.Enabled = false;
chkTables.Enabled = false;
chkViews.Checked = true;
chkTables.Checked = true;
}
this.selectedDataSource = null;
// TODO: Review this code. Select known database driver from configuration or prj file
this.RefreshForm();
}
private void btnClear_Click(object sender, System.EventArgs e)
{
lvDataSourceObjects.SelectedItems.Clear(); //.SelectedIndex = -1;
SetDataSourceToSelectedProject();
}
private void txtCurrentProj_TextChanged(object sender, System.EventArgs e)
{
CheckForInputSufficiency();
}
private void txtDataSource_TextChanged(object sender, System.EventArgs e)
{
CheckForInputSufficiency();
}
private void btnFindDataSource_Click(object sender, System.EventArgs e)
{
OpenSelectDataSourceDialog();
}
private void lvDataSourceObjects_SelectedIndexChanged(object sender, System.EventArgs e)
{
CheckForInputSufficiency();
if (lvDataSourceObjects.SelectedItems.Count <= 0)
{
return;
}
if (selectedDataSource is IDbDriver)
{
IDbDriver dbDriver = selectedDataSource as IDbDriver;
DataTable dt = dbDriver.GetTopTwoTable(lvDataSourceObjects.SelectedItems[0].Text);
List<string> childCols = new List<string>();
foreach (DataColumn dc in dt.Columns)
{
childCols.Add(dc.ColumnName);
}
childCols.Sort();
cmbChildKey.DataSource = childCols;
SelectedItemType = Dialogs.SelectedItemType.Table;
}
else if (selectedDataSource is Project)
{
Project project = selectedDataSource as Project;
string viewName = lvDataSourceObjects.SelectedItems[0].Text;
List<string> childCols = new List<string>();
if (project.Views.Contains(viewName) && lvDataSourceObjects.SelectedItems[0].Group.ToString().ToLowerInvariant().Equals("epi info forms"))
{
foreach (Epi.Fields.Field field in project.Views[viewName].Fields.DataFields)
{
childCols.Add(field.Name);
}
childCols.Sort();
cmbChildKey.DataSource = childCols;
SelectedItemType = Dialogs.SelectedItemType.Form;
}
else if (lvDataSourceObjects.SelectedItems[0].Group.ToString().ToLowerInvariant().Equals("tables"))
{
IDbDriver dbDriver = project.CollectedData.GetDbDriver();
DataTable dt = dbDriver.GetTopTwoTable(lvDataSourceObjects.SelectedItems[0].Text);
foreach (DataColumn dc in dt.Columns)
{
childCols.Add(dc.ColumnName);
}
childCols.Sort();
cmbChildKey.DataSource = childCols;
SelectedItemType = Dialogs.SelectedItemType.Table;
}
}
}
private void lvDataSourceObjects_DataSourceChanged(object sender, System.EventArgs e)
{
if (lvDataSourceObjects.Items.Count > 0)
{
lvDataSourceObjects.SelectedIndices.Clear();
}
}
private void lvDataSourceObjects_Resize(object sender, EventArgs e)
{
// leave space for scroll bar
this.lvDataSourceObjects.Columns[0].Width = this.lvDataSourceObjects.Width - 25;
}
private void lvDataSourceObjects_DoubleClick(object sender, EventArgs e)
{
if (this.btnOK.Enabled)
{
OnOK();
}
}
private void OnOK()
{
if (ValidateInput() == true)
{
UseUnmatched = cbxUseUnmatched.Checked;
GenerateCommand();
PreProcess();
this.DialogResult = DialogResult.OK;
this.Hide();
}
else
{
this.DialogResult = DialogResult.None;
ShowErrorMessages();
}
}
private void CheckBox_CheckedChanged(object sender, EventArgs e)
{
if (!(chkViews.Checked) && !(chkTables.Checked))
{
chkViews.Checked = true;
}
RefreshForm();
}
#endregion Event Handlers
private void cmbRecentSources_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//this.RefreshForm();
if (cmbRecentSources.SelectedItem != null && !string.IsNullOrEmpty(cmbRecentSources.SelectedItem.ToString()))
{
string connectionString = Configuration.Decrypt(((ComboBoxItem)cmbRecentSources.SelectedItem).Value.ToString());
string name = ((ComboBoxItem)cmbRecentSources.SelectedItem).Text.ToString();
string provider = ((ComboBoxItem)cmbRecentSources.SelectedItem).Key.ToString();
mruSelectedDatabaseName = name;
selectedDataProvider = provider;
if (name.ToLowerInvariant().EndsWith(".prj"))
{
Project project = new Project(connectionString);
try
{
project.CollectedData.TestConnection();
}
catch (Exception ex)
{
Epi.Windows.MsgBox.ShowException(ex);
return;
}
this.selectedDataSource = project;
this.selectedProject = project;
}
else
{
IDbDriverFactory dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(provider);
if (dbFactory.ArePrerequisitesMet())
{
DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
db.ConnectionString = connectionString;
try
{
db.TestConnection();
}
catch (Exception ex)
{
Epi.Windows.MsgBox.ShowException(ex);
return;
}
this.selectedDataSource = db;
}
}
}
else if (cmbRecentSources.SelectedItem != null && string.IsNullOrEmpty(cmbRecentSources.SelectedItem.ToString()))
{
mruSelectedDatabaseName = string.Empty;
}
RefreshForm();
}
catch (System.IO.DirectoryNotFoundException ex)
{
MsgBox.ShowException(ex);
mruSelectedDatabaseName = string.Empty;
cmbRecentSources.SelectedIndex = -1;
}
catch (System.IO.FileNotFoundException ex)
{
MsgBox.ShowException(ex);
mruSelectedDatabaseName = string.Empty;
cmbRecentSources.SelectedIndex = -1;
}
catch (Exception ex)
{
MsgBox.ShowException(ex);
mruSelectedDatabaseName = string.Empty;
cmbRecentSources.SelectedIndex = -1;
}
}
}
}
| |
namespace VZF.Controls
{
#region Using
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using VZF.Data.Common;
using VZF.Utils;
using YAF.Classes;
using YAF.Core;
using YAF.Types;
using YAF.Types.Interfaces;
#endregion
/// <summary>
/// The thanks list mode.
/// </summary>
public enum ThanksListMode
{
/// <summary>
/// The from user.
/// </summary>
FromUser,
/// <summary>
/// The to user.
/// </summary>
ToUser
}
/// <summary>
/// Summary description for buddies.
/// </summary>
public partial class ViewThanksList : BaseUserControl
{
/* Data Fields */
/// <summary>
/// Gets or sets a value indicating whether Auto Databind.
/// </summary>
public bool AutoDatabind { get; set; }
/* Properties */
#region Constants and Fields
/// <summary>
/// The _count.
/// </summary>
private int _count;
/// <summary>
/// The user id.
/// </summary>
private int userID;
#endregion
#region Properties
/// <summary>
/// Determines what is th current mode of the control.
/// </summary>
public ThanksListMode CurrentMode { get; set; }
/// <summary>
/// The Thanks Info.
/// </summary>
public DataTable ThanksInfo { get; set; }
/// <summary>
/// The User ID.
/// </summary>
public int UserID { get; set; }
#endregion
// keeps count
/* Event Handlers */
/* Methods */
#region Public Methods
/// <summary>
/// The bind data.
/// </summary>
public void BindData()
{
// we'll hold topics in this table
DataTable topicList = null;
// set the page size here
this.PagerTop.PageSize = this.Get<YafBoardSettings>().MyTopicsListPageSize;
// now depending on mode fill the table
switch (this.CurrentMode)
{
case ThanksListMode.FromUser:
topicList = CommonDb.user_viewthanksfrom(PageContext.PageModuleID, userID, this.PageContext.PageUserID, this.PagerTop.CurrentPageIndex, this.PagerTop.PageSize);
break;
case ThanksListMode.ToUser:
topicList = CommonDb.user_viewthanksto(PageContext.PageModuleID, userID, this.PageContext.PageUserID, this.PagerTop.CurrentPageIndex, this.PagerTop.PageSize);
break;
}
if (topicList == null)
{
this.PagerTop.Count = 0;
return;
}
if (topicList.Rows.Count <= 0)
{
this.PagerTop.Count = 0;
this.ThanksRes.DataSource = null;
this.ThanksRes.DataBind();
return;
}
// let's page the results
this.PagerTop.Count = topicList.Rows.Count > 0
? topicList.AsEnumerable().First().Field<int>("TotalRows")
: 0;
this.ThanksRes.DataSource = topicList.AsEnumerable();
// data bind controls
this.DataBind();
}
#endregion
#region Methods
/// <summary>
/// Returns <see langword="true"/> if the count is odd
/// </summary>
/// <returns>
/// The is odd.
/// </returns>
protected bool IsOdd()
{
return (this._count++ % 2) == 0;
}
/* Methods */
/// <summary>
/// The page_ load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
this.userID = (int)Security.StringToLongOrRedirect(this.Request.QueryString.GetFirstOrDefault("u"));
if (this.AutoDatabind)
{
this.BindData();
}
}
/// <summary>
/// The pager_ page change.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Pager_PageChange([NotNull] object sender, [NotNull] EventArgs e)
{
this.BindData();
}
/// <summary>
/// Handles the ItemCreated event of the ThanksRes control.
/// </summary>
/// <param name="sender">
/// The source of the event.
/// </param>
/// <param name="e">
/// The <see cref="System.Web.UI.WebControls.RepeaterItemEventArgs"/>
/// instance containing the event data.
/// </param>
protected void ThanksRes_ItemCreated([NotNull] object sender, [NotNull] RepeaterItemEventArgs e)
{
switch (this.CurrentMode)
{
case ThanksListMode.FromUser:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var thanksNumberCell = (HtmlTableCell)e.Item.FindControl("ThanksNumberCell");
thanksNumberCell.Visible = false;
}
break;
case ThanksListMode.ToUser:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var nameCell = (HtmlTableCell)e.Item.FindControl("NameCell");
nameCell.Visible = false;
}
break;
}
}
#endregion
}
}
| |
// 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.Azure.Test.HttpRecorder;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Compute.Tests
{
public class ImageTests : VMTestBase
{
[Fact]
[Trait("Name", "TestCreateImage_with_DiskEncryptionSet")]
public void TestCreateImage_with_DiskEncryptionSet()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
using (MockContext context = MockContext.Start(this.GetType()))
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "centraluseuap");
EnsureClientsInitialized(context);
string diskEncryptionSetId = getDefaultDiskEncryptionSetId();
CreateImageTestHelper(originalTestLocation, diskEncryptionSetId);
}
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
[Fact]
[Trait("Name", "TestCreateImage_without_DiskEncryptionSet")]
public void TestCreateImage_without_DiskEncryptionSet()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
using (MockContext context = MockContext.Start(this.GetType()))
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "FranceCentral");
EnsureClientsInitialized(context);
CreateImageTestHelper(originalTestLocation, diskEncryptionSetId: null);
}
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
private void CreateImageTestHelper(string originalTestLocation, string diskEncryptionSetId)
{
VirtualMachine inputVM = null;
// Create resource group
var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
var imageName = ComputeManagementTestUtilities.GenerateName("imageTest");
// Create a VM, so we can use its OS disk for creating the image
string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string asName = ComputeManagementTestUtilities.GenerateName("as");
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
try
{
// Create Storage Account
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
// Add data disk to the VM.
Action<VirtualMachine> addDataDiskToVM = vm =>
{
string containerName = HttpMockServer.GetAssetName("TestImageOperations", TestPrefix);
var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName;
var vhduri = vhdContainer + string.Format("/{0}.vhd", HttpMockServer.GetAssetName("TestImageOperations", TestPrefix));
vm.HardwareProfile.VmSize = VirtualMachineSizeTypes.StandardA4;
vm.StorageProfile.DataDisks = new List<DataDisk>();
foreach (int index in new int[] { 1, 2 })
{
var diskName = "dataDisk" + index;
var ddUri = vhdContainer + string.Format("/{0}{1}.vhd", diskName, HttpMockServer.GetAssetName("TestImageOperations", TestPrefix));
var dd = new DataDisk
{
Caching = CachingTypes.None,
Image = null,
DiskSizeGB = 10,
CreateOption = DiskCreateOptionTypes.Empty,
Lun = 1 + index,
Name = diskName,
Vhd = new VirtualHardDisk
{
Uri = ddUri
}
};
vm.StorageProfile.DataDisks.Add(dd);
}
var testStatus = new InstanceViewStatus
{
Code = "test",
Message = "test"
};
var testStatusList = new List<InstanceViewStatus> { testStatus };
};
// Create the VM, whose OS disk will be used in creating the image
var createdVM = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM, addDataDiskToVM);
int expectedDiskLunWithDiskEncryptionSet = createdVM.StorageProfile.DataDisks[0].Lun;
// Create the Image
var imageInput = new Image()
{
Location = m_location,
Tags = new Dictionary<string, string>()
{
{"RG", "rg"},
{"testTag", "1"},
},
StorageProfile = new ImageStorageProfile()
{
OsDisk = new ImageOSDisk()
{
BlobUri = createdVM.StorageProfile.OsDisk.Vhd.Uri,
DiskEncryptionSet = diskEncryptionSetId == null ? null : new DiskEncryptionSetParameters()
{
Id = diskEncryptionSetId
},
OsState = OperatingSystemStateTypes.Generalized,
OsType = OperatingSystemTypes.Windows,
},
DataDisks = new List<ImageDataDisk>()
{
new ImageDataDisk()
{
BlobUri = createdVM.StorageProfile.DataDisks[0].Vhd.Uri,
DiskEncryptionSet = diskEncryptionSetId == null ? null: new DiskEncryptionSetParameters()
{
Id = diskEncryptionSetId
},
Lun = expectedDiskLunWithDiskEncryptionSet,
}
}
},
HyperVGeneration = HyperVGeneration.V1
};
var image = m_CrpClient.Images.CreateOrUpdate(rgName, imageName, imageInput);
var getImage = m_CrpClient.Images.Get(rgName, imageName);
ValidateImage(imageInput, getImage);
if( diskEncryptionSetId != null)
{
Assert.True(getImage.StorageProfile.OsDisk.DiskEncryptionSet != null, "OsDisk.DiskEncryptionSet is null");
Assert.True(string.Equals(diskEncryptionSetId, getImage.StorageProfile.OsDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
"getImage.StorageProfile.OsDisk.DiskEncryptionSet is not matching with expected DiskEncryptionSet resource");
Assert.Equal(1, getImage.StorageProfile.DataDisks.Count);
Assert.True(getImage.StorageProfile.DataDisks[0].DiskEncryptionSet != null, ".DataDisks.DiskEncryptionSet is null");
Assert.True(string.Equals(diskEncryptionSetId, getImage.StorageProfile.DataDisks[0].DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
"DataDisks.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");
}
ImageUpdate updateParams = new ImageUpdate()
{
Tags = getImage.Tags
};
string tagKey = "UpdateTag";
updateParams.Tags.Add(tagKey, "TagValue");
m_CrpClient.Images.Update(rgName, imageName, updateParams);
getImage = m_CrpClient.Images.Get(rgName, imageName);
Assert.True(getImage.Tags.ContainsKey(tagKey));
var listResponse = m_CrpClient.Images.ListByResourceGroup(rgName);
Assert.Single(listResponse);
m_CrpClient.Images.Delete(rgName, image.Name);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
if (inputVM != null)
{
m_CrpClient.VirtualMachines.Delete(rgName, inputVM.Name);
}
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
void ValidateImage(Image imageIn, Image imageOut)
{
Assert.True(!string.IsNullOrEmpty(imageOut.ProvisioningState));
if(imageIn.Tags != null)
{
foreach(KeyValuePair<string, string> kvp in imageIn.Tags)
{
Assert.True(imageOut.Tags[kvp.Key] == kvp.Value);
}
}
Assert.NotNull(imageOut.StorageProfile.OsDisk);
if (imageIn.StorageProfile.OsDisk != null)
{
Assert.True(imageOut.StorageProfile.OsDisk.BlobUri
== imageIn.StorageProfile.OsDisk.BlobUri);
Assert.True(imageOut.StorageProfile.OsDisk.OsState
== imageIn.StorageProfile.OsDisk.OsState);
Assert.True(imageOut.StorageProfile.OsDisk.OsType
== imageIn.StorageProfile.OsDisk.OsType);
}
if (imageIn.StorageProfile.DataDisks != null &&
imageIn.StorageProfile.DataDisks.Any())
{
foreach (var dataDisk in imageIn.StorageProfile.DataDisks)
{
var dataDiskOut = imageOut.StorageProfile.DataDisks.FirstOrDefault(
d => int.Equals(dataDisk.Lun, d.Lun));
Assert.NotNull(dataDiskOut);
Assert.NotNull(dataDiskOut.BlobUri);
Assert.NotNull(dataDiskOut.DiskSizeGB);
}
}
Assert.Equal(imageIn.StorageProfile.ZoneResilient, imageOut.StorageProfile.ZoneResilient);
}
}
}
| |
// Copyright 2017 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
//
// 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.
// Don't warn about using .Handle; see comment below about SafeHandle
#pragma warning disable 618
using System;
using System.IO;
namespace TiltBrushToolkit {
public class RawImage {
public UnityEngine.Color32[] colorData;
public int colorWidth;
public int colorHeight;
public UnityEngine.TextureFormat format;
}
// ----------------------------------------------------------------------
public interface IBufferReader : IDisposable {
void Read(IntPtr destination, int readStart, int readSize);
/// <summary>
/// Reads bytes into the given byte buffer.
/// </summary>
/// <param name="destination">The byte buffer to write the results of the read into.</param>
/// <param name="destinationOffset">The offset in <c>destination</c> to start writing.</param>
/// <param name="readStart">The offset in the source buffer to start reading from.</param>
/// <param name="readSize">The number of bytes to read.</param>
void Read(byte[] destination, int destinationOffset, int readStart, int readSize);
/// <summary>
/// Returns the length of the content, if known in advance.
/// </summary>
/// <returns>The length of the content, or -1 if not known in advance.</returns>
long GetContentLength();
}
public interface IUriLoader {
/// <summary>
/// Returns an object that can read bytes from the passed uri
/// </summary>
/// <param name="uri">The relative uri to load. A null argument means to return
/// the glb binary chunk.</param>
IBufferReader Load(string uri);
/// <summary>
/// Returns true if the method LoadAsImage() is supported.
/// </summary>
bool CanLoadImages();
/// <summary>
/// Returns the contents of the passed uri as a decoded image.
/// Should raise NotSupportedException if not supported.
/// </summary>
/// <param name="uri">The relative uri to load</param>
RawImage LoadAsImage(string uri);
#if UNITY_EDITOR
/// <summary>
/// Returns the contents of the passed uri as a Texture2D such that
/// AssetDatabase.Contains(tex) == true; or null on failure.
/// Possible causes of failure are:
/// - uri lies outside of Assets/
/// - uri does not reference a texture
/// </summary>
/// <param name="uri">The relative uri to load</param>
UnityEngine.Texture2D LoadAsAsset(string uri);
#endif
}
// ----------------------------------------------------------------------
public class Reader : IBufferReader {
private byte[] data;
public Reader(byte[] data) {
this.data = data;
}
public void Dispose() { }
public void Read(IntPtr destination, int readStart, int readSize) {
System.Runtime.InteropServices.Marshal.Copy(
data, readStart, destination, readSize);
}
public void Read(byte[] dest, int destOffset, int readStart, int readSize) {
Buffer.BlockCopy(data, readStart, dest, destOffset, readSize);
}
public long GetContentLength() {
return data.Length;
}
}
/// Performs reads just-in-time from a FileStream.
public class BufferedStreamLoader : IUriLoader {
private string glbPath;
private string uriBase;
private int bufferSize;
/// glbPath is the .gltf or .glb file being read; or null.
public BufferedStreamLoader(string glbPath, string uriBase, int bufferSize=4096) {
this.glbPath = glbPath;
this.uriBase = uriBase;
this.bufferSize = bufferSize;
}
public IBufferReader Load(string uri) {
Stream stream;
if (uri == null) {
var range = GlbParser.GetBinChunk(glbPath);
stream = new SubStream(File.OpenRead(glbPath), range.start, range.length);
} else {
stream = File.OpenRead(Path.Combine(uriBase, uri));
}
return new BufferedStreamReader(stream, bufferSize, stream.Length);
}
public bool CanLoadImages() { return false; }
public RawImage LoadAsImage(string uri) { throw new NotSupportedException(); }
#if UNITY_EDITOR
public UnityEngine.Texture2D LoadAsAsset(string uri) {
if (uri == null) {
// Texture data is embedded within the glb; thanks jfx@
return null;
}
// If we're running in the editor, we can assume that:
// - the current directory is the project directory
// - uriBase is relative
// - therefore, uriBase starts with Assets/
string path = Path.Combine(uriBase, uri);
return UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.Texture2D>(path);
}
#endif
}
/// Takes an arbitrary seekable stream and reads it chunk-by-chunk,
/// because there's otherwise no way to read into an IntPtr.
///
/// PRO: doesn't need to buffer the entire .bin into memory
/// CON: still needs a tiny buffer to stage the data
/// CON: an extra copy
sealed class BufferedStreamReader : IBufferReader {
Stream stream;
byte[] tempBuffer;
long contentLength;
// Takes ownership of the stream
public BufferedStreamReader(Stream stream, int bufferSize, long contentLength) {
this.stream = stream;
this.tempBuffer = new byte[bufferSize];
this.contentLength = contentLength;
}
public void Dispose() {
if (stream != null) { stream.Dispose(); }
}
public void Read(IntPtr destination, int readStart, int readSize) {
stream.Seek(readStart, SeekOrigin.Begin);
// Invariant: (destination + readSize) == (currentDestination + currentReadSize)
int currentReadSize = readSize;
// operator + (IntPtr, int) didn't come along until .net 4
Int64 currentDestination = destination.ToInt64();
while (currentReadSize > 0) {
int numRead = stream.Read(tempBuffer, 0, Math.Min(currentReadSize, tempBuffer.Length));
if (numRead <= 0) {
break;
}
System.Runtime.InteropServices.Marshal.Copy(
tempBuffer, 0, (IntPtr)currentDestination, numRead);
currentReadSize -= numRead;
currentDestination += numRead;
}
}
public void Read(byte[] dest, int destOffset, int readStart, int readSize) {
stream.Seek(readStart, SeekOrigin.Begin);
while (readSize > 0) {
int bytesRead = stream.Read(dest, destOffset, readSize);
if (bytesRead <= 0) break;
destOffset += bytesRead;
readSize -= bytesRead;
}
}
public long GetContentLength() {
return contentLength;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Client.Compute
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Client.Compute;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Compute client.
/// </summary>
internal class ComputeClient : IComputeClient
{
/** */
private readonly IgniteClient _ignite;
/** */
private readonly ComputeClientFlags _flags;
/** */
private readonly TimeSpan _timeout;
/** */
private readonly IClientClusterGroup _clusterGroup;
/// <summary>
/// Initializes a new instance of <see cref="ComputeClient"/>.
/// </summary>
internal ComputeClient(
IgniteClient ignite,
ComputeClientFlags flags,
TimeSpan? timeout,
IClientClusterGroup clusterGroup)
{
_ignite = ignite;
_flags = flags;
_timeout = timeout ?? TimeSpan.Zero;
_clusterGroup = clusterGroup;
}
/** <inheritdoc /> */
public TRes ExecuteJavaTask<TRes>(string taskName, object taskArg)
{
IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName");
return ExecuteJavaTaskAsync<TRes>(taskName, taskArg).Result;
}
/** <inheritdoc /> */
public Task<TRes> ExecuteJavaTaskAsync<TRes>(string taskName, object taskArg)
{
return ExecuteJavaTaskAsync<TRes>(taskName, taskArg, CancellationToken.None);
}
/** <inheritdoc /> */
public Task<TRes> ExecuteJavaTaskAsync<TRes>(string taskName, object taskArg,
CancellationToken cancellationToken)
{
IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName");
var tcs = new TaskCompletionSource<TRes>();
cancellationToken.Register(() => tcs.TrySetCanceled());
var keepBinary = (_flags & ComputeClientFlags.KeepBinary) == ComputeClientFlags.KeepBinary;
var task = _ignite.Socket.DoOutInOpAsync(
ClientOp.ComputeTaskExecute,
ctx => WriteJavaTaskRequest(ctx, taskName, taskArg),
ctx => ReadJavaTaskResponse(ctx, tcs, cancellationToken, keepBinary));
// ReSharper disable once AssignNullToNotNullAttribute (t.Exception won't be null).
task.ContinueWith(t => tcs.TrySetException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(t => tcs.TrySetCanceled(), TaskContinuationOptions.OnlyOnCanceled);
return tcs.Task;
}
/** <inheritdoc /> */
public IComputeClient WithTimeout(TimeSpan timeout)
{
return _timeout != timeout
? new ComputeClient(_ignite, _flags, timeout, _clusterGroup)
: this;
}
/** <inheritdoc /> */
public IComputeClient WithNoFailover()
{
return SetFlag(ComputeClientFlags.NoFailover);
}
/** <inheritdoc /> */
public IComputeClient WithNoResultCache()
{
return SetFlag(ComputeClientFlags.NoResultCache);
}
/** <inheritdoc /> */
public IComputeClient WithKeepBinary()
{
return SetFlag(ComputeClientFlags.KeepBinary);
}
/// <summary>
/// Returns a new instance with the given flag enabled, or this instance if the flag is already present.
/// </summary>
private IComputeClient SetFlag(ComputeClientFlags newFlag)
{
var flags = _flags | newFlag;
return flags != _flags
? new ComputeClient(_ignite, flags, _timeout, _clusterGroup)
: this;
}
/// <summary>
/// Writes the java task.
/// </summary>
private void WriteJavaTaskRequest(ClientRequestContext ctx, string taskName, object taskArg)
{
var writer = ctx.Writer;
if (_clusterGroup != null)
{
var nodes = _clusterGroup.GetNodes();
writer.WriteInt(nodes.Count);
foreach (var node in nodes)
{
BinaryUtils.WriteGuid(node.Id, ctx.Stream);
}
}
else
{
writer.WriteInt(0);
}
writer.WriteByte((byte) _flags);
writer.WriteLong((long) _timeout.TotalMilliseconds);
writer.WriteString(taskName);
writer.WriteObject(taskArg);
ctx.Socket.ExpectNotifications();
}
/// <summary>
/// Reads java task execution response.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static object ReadJavaTaskResponse<TRes>(ClientResponseContext ctx, TaskCompletionSource<TRes> tcs,
CancellationToken cancellationToken, bool keepBinary)
{
var taskId = ctx.Stream.ReadLong();
cancellationToken.Register(() =>
{
ctx.Socket.DoOutInOpAsync<object>(ClientOp.ResourceClose,
c => c.Stream.WriteLong(taskId),
_ => null,
(status, msg) =>
{
if (status == ClientStatusCode.ResourceDoesNotExist)
{
// Task finished before we could cancel it - ignore.
return null;
}
throw new IgniteClientException(msg, null, status);
});
});
ctx.Socket.AddNotificationHandler(taskId, (stream, ex) =>
{
ctx.Socket.RemoveNotificationHandler(taskId);
if (ex != null)
{
tcs.TrySetException(ex);
return;
}
var reader = ctx.Marshaller.StartUnmarshal(stream,
keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize);
try
{
var flags = (ClientFlags) reader.ReadShort();
var opCode = (ClientOp) reader.ReadShort();
if (opCode != ClientOp.ComputeTaskFinished)
{
tcs.TrySetException(new IgniteClientException(
string.Format("Invalid server notification code. Expected {0}, but got {1}",
ClientOp.ComputeTaskFinished, opCode)));
}
else if ((flags & ClientFlags.Error) == ClientFlags.Error)
{
var status = (ClientStatusCode) reader.ReadInt();
var msg = reader.ReadString();
tcs.TrySetException(new IgniteClientException(msg, null, status));
}
else
{
tcs.TrySetResult(reader.ReadObject<TRes>());
}
}
catch (Exception e)
{
tcs.TrySetException(e);
}
});
return null;
}
}
}
| |
namespace AngleSharp.Core.Tests.Urls
{
using AngleSharp.Dom;
using NUnit.Framework;
[TestFixture]
public class UrlApiTests
{
[Test]
public void UrlSearchWithoutQueryIsEmpty()
{
var url = new Url("https://florian-rappl.de/foo/bar");
Assert.AreEqual("", url.Search);
Assert.AreEqual(null, url.Query);
Assert.AreEqual("", url.SearchParams.ToString());
}
[Test]
public void UrlSearchWithQueryIsNotEmpty()
{
var url = new Url("https://florian-rappl.de/foo/bar?qxz=baz");
Assert.AreEqual("?qxz=baz", url.Search);
Assert.AreEqual("qxz=baz", url.Query);
Assert.AreEqual("qxz=baz", url.SearchParams.ToString());
}
[Test]
public void UrlHashhWithoutFragmentIsEmpty()
{
var url = new Url("https://florian-rappl.de/foo/bar");
Assert.AreEqual("", url.Hash);
Assert.AreEqual(null, url.Fragment);
}
[Test]
public void UrlHashhWithFragmentIsNotEmpty()
{
var url = new Url("https://florian-rappl.de/foo/bar#baz");
Assert.AreEqual("#baz", url.Hash);
Assert.AreEqual("baz", url.Fragment);
}
[Test]
public void UrlHashAssigningStringWithHash()
{
var url = new Url("https://florian-rappl.de/foo/bar#baz");
Assert.AreEqual("#baz", url.Hash);
Assert.AreEqual("baz", url.Fragment);
url.Hash = "#foobar";
Assert.AreEqual("#foobar", url.Hash);
Assert.AreEqual("foobar", url.Fragment);
}
[Test]
public void UrlHashAssigningStringWithoutHash()
{
var url = new Url("https://florian-rappl.de/foo/bar#baz");
Assert.AreEqual("#baz", url.Hash);
Assert.AreEqual("baz", url.Fragment);
url.Hash = "foobar";
Assert.AreEqual("#foobar", url.Hash);
Assert.AreEqual("foobar", url.Fragment);
}
[Test]
public void UrlHashAssigningEmpty()
{
var url = new Url("https://florian-rappl.de/foo/bar#baz");
Assert.AreEqual("#baz", url.Hash);
Assert.AreEqual("baz", url.Fragment);
url.Hash = "";
Assert.AreEqual("", url.Hash);
Assert.AreEqual(null, url.Fragment);
}
[Test]
public void UrlPathnameIncludesSlash()
{
var url = new Url("https://florian-rappl.de/foo/bar");
Assert.AreEqual("/foo/bar", url.PathName);
Assert.AreEqual("foo/bar", url.Path);
}
[Test]
public void UrlPathnameIsNeverEmpty()
{
var url = new Url("https://florian-rappl.de");
Assert.AreEqual("/", url.PathName);
Assert.AreEqual("", url.Path);
}
[Test]
public void UrlUsernameAndPasswordAreEmptyIfNotGiven()
{
var url = new Url("https://florian-rappl.de/foo/bar");
Assert.AreEqual("", url.UserName);
Assert.AreEqual("", url.Password);
}
[Test]
public void UrlQueryIsClearedWithNull()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("bar", url.SearchParams.Get("qxz"));
Assert.AreEqual(true, url.SearchParams.Has("qxz"));
Assert.AreEqual(null, url.SearchParams.Get("foo"));
Assert.AreEqual("qxz=bar", url.SearchParams.ToString());
Assert.AreEqual("qxz=bar", url.Query);
Assert.AreEqual("?qxz=bar", url.Search);
url.Query = null;
Assert.AreEqual(null, url.SearchParams.Get("qxz"));
Assert.AreEqual(false, url.SearchParams.Has("qxz"));
Assert.AreEqual("", url.SearchParams.ToString());
Assert.AreEqual(null, url.Query);
Assert.AreEqual("", url.Search);
}
[Test]
public void UrlQueryIsClearedWithEmpty()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("bar", url.SearchParams.Get("qxz"));
Assert.AreEqual(true, url.SearchParams.Has("qxz"));
Assert.AreEqual(null, url.SearchParams.Get("foo"));
Assert.AreEqual("qxz=bar", url.SearchParams.ToString());
Assert.AreEqual("qxz=bar", url.Query);
Assert.AreEqual("?qxz=bar", url.Search);
url.Query = "";
Assert.AreEqual(null, url.SearchParams.Get("qxz"));
Assert.AreEqual(false, url.SearchParams.Has("qxz"));
Assert.AreEqual("", url.SearchParams.ToString());
Assert.AreEqual("", url.Query);
Assert.AreEqual("", url.Search);
}
[Test]
public void UrlParamsAreLive()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("bar", url.SearchParams.Get("qxz"));
Assert.AreEqual(true, url.SearchParams.Has("qxz"));
Assert.AreEqual(null, url.SearchParams.Get("foo"));
url.Query = "foo=bar";
Assert.AreEqual(null, url.SearchParams.Get("qxz"));
Assert.AreEqual(false, url.SearchParams.Has("qxz"));
Assert.AreEqual("bar", url.SearchParams.Get("foo"));
Assert.AreEqual("foo=bar", url.Query);
}
[Test]
public void UrlQueryDoesNotDependOnParams()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("bar", url.SearchParams.Get("qxz"));
Assert.AreEqual(true, url.SearchParams.Has("qxz"));
Assert.AreEqual(null, url.SearchParams.Get("foo"));
url.Query = "foo";
Assert.AreEqual(null, url.SearchParams.Get("qxz"));
Assert.AreEqual(false, url.SearchParams.Has("qxz"));
Assert.AreEqual("", url.SearchParams.Get("foo"));
Assert.AreEqual("foo", url.Query);
}
[Test]
public void UrlSearchAssigningStringWithoutQuestion()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("bar", url.SearchParams.Get("qxz"));
Assert.AreEqual(true, url.SearchParams.Has("qxz"));
Assert.AreEqual(null, url.SearchParams.Get("foo"));
url.Search = "foo=bar";
Assert.AreEqual(null, url.SearchParams.Get("qxz"));
Assert.AreEqual(false, url.SearchParams.Has("qxz"));
Assert.AreEqual("bar", url.SearchParams.Get("foo"));
Assert.AreEqual("foo=bar", url.Query);
}
[Test]
public void UrlSearchAssigningStringWithQuestion()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("bar", url.SearchParams.Get("qxz"));
Assert.AreEqual(true, url.SearchParams.Has("qxz"));
Assert.AreEqual(null, url.SearchParams.Get("foo"));
url.Search = "?foo=bar";
Assert.AreEqual(null, url.SearchParams.Get("qxz"));
Assert.AreEqual(false, url.SearchParams.Has("qxz"));
Assert.AreEqual("bar", url.SearchParams.Get("foo"));
Assert.AreEqual("foo=bar", url.Query);
}
[Test]
public void UrlSearchAssigningEmpty()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("bar", url.SearchParams.Get("qxz"));
Assert.AreEqual(true, url.SearchParams.Has("qxz"));
Assert.AreEqual(null, url.SearchParams.Get("foo"));
url.Search = "";
Assert.AreEqual(null, url.SearchParams.Get("qxz"));
Assert.AreEqual(false, url.SearchParams.Has("qxz"));
Assert.AreEqual(null, url.SearchParams.Get("foo"));
Assert.AreEqual(null, url.Query);
}
[Test]
public void UrlParamsAreConnectedWhenAppend()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("qxz=bar", url.Query);
url.SearchParams.Append("foo", "bar");
Assert.AreEqual("qxz=bar&foo=bar", url.Query);
}
[Test]
public void UrlParamsAreConnectedWhenDelete()
{
var url = new Url("https://florian-rappl.de?qxz=bar");
Assert.AreEqual("qxz=bar", url.Query);
url.SearchParams.Delete("qxz");
Assert.AreEqual("", url.Query);
}
[Test]
public void UrlParamsResolveValuesDecoded()
{
var url = new Url("https://florian-rappl.de?qxz=%20foo%20yo");
Assert.AreEqual(" foo yo", url.SearchParams.Get("qxz"));
Assert.AreEqual("?qxz=%20foo%20yo", url.Search);
Assert.AreEqual("qxz=%20foo%20yo", url.SearchParams.ToString());
}
[Test]
public void UrlParamsResolveValuesDecodedAlsoWhenAdded()
{
var url = new Url("https://florian-rappl.de?qxz=%20foo%20yo");
url.SearchParams.Set("qxz", "foo");
Assert.AreEqual("foo", url.SearchParams.Get("qxz"));
url.SearchParams.Set("bar", "crazy / shit ?");
Assert.AreEqual("?qxz=foo&bar=crazy%20%2F%20shit%20%3F", url.Search);
Assert.AreEqual("crazy / shit ?", url.SearchParams.Get("bar"));
Assert.AreEqual("qxz=foo&bar=crazy%20%2F%20shit%20%3F", url.SearchParams.ToString());
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for SkipUrlEncodingOperations.
/// </summary>
public static partial class SkipUrlEncodingOperationsExtensions
{
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetMethodPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodPathValidAsync(unencodedPathParam), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetMethodPathValidAsync(this ISkipUrlEncodingOperations operations, string unencodedPathParam, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetMethodPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetPathPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathPathValidAsync(unencodedPathParam), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetPathPathValidAsync(this ISkipUrlEncodingOperations operations, string unencodedPathParam, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetPathPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void GetSwaggerPathValid(this ISkipUrlEncodingOperations operations)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerPathValidAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetSwaggerPathValidAsync(this ISkipUrlEncodingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetSwaggerPathValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetMethodQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryValidAsync(q1), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetMethodQueryValidAsync(this ISkipUrlEncodingOperations operations, string q1, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetMethodQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
public static void GetMethodQueryNull(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryNullAsync(q1), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetMethodQueryNullAsync(this ISkipUrlEncodingOperations operations, string q1 = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetMethodQueryNullWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetPathQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathQueryValidAsync(q1), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetPathQueryValidAsync(this ISkipUrlEncodingOperations operations, string q1, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetPathQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void GetSwaggerQueryValid(this ISkipUrlEncodingOperations operations)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerQueryValidAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetSwaggerQueryValidAsync(this ISkipUrlEncodingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetSwaggerQueryValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Text;
using Xunit;
namespace System.Net.Tests
{
public partial class WebUtilityTests
{
// HtmlEncode + HtmlDecode
public static IEnumerable<object[]> HtmlDecode_TestData()
{
// Needs decoding
yield return new object[] { "Hello! '"<&>\u2665♥\u00E7çç", "Hello! '\"<&>\u2665\u2665\u00E7\u00E7\u00E7" };
yield return new object[] { "퟿퟿", "\uD7FF\uD7FF" };
yield return new object[] { "", "\uE000\uE000" };
yield return new object[] { "abc", "abc" };
// Surrogate pairs
yield return new object[] { "𐀀", "\uD800\uDC00" };
yield return new object[] { "a𐀀b", "a\uD800\uDC00b" };
yield return new object[] { "𣎴", char.ConvertFromUtf32(144308) };
// Invalid encoding
yield return new object[] { "&", "&" };
yield return new object[] { "&#", "&#" };
yield return new object[] { "&#x", "&#x" };
yield return new object[] { "&abc", "&abc" };
yield return new object[] { "&abc;", "&abc;" };
yield return new object[] { "𐀀", "𐀀" };
yield return new object[] { "퟿", "퟿" };
yield return new object[] { "&#xG123;", "&#xG123;" };
yield return new object[] { "�", "�" };
yield return new object[] { "�", "�" };
yield return new object[] { "�", "�" };
yield return new object[] { "�", "�" };
yield return new object[] { "�", "�" };
yield return new object[] { "�", "�" };
// High BMP non-chars
yield return new object[] { "\uFFFD", "\uFFFD" };
yield return new object[] { "\uFFFE", "\uFFFE" };
yield return new object[] { "\uFFFF", "\uFFFF" };
// Basic
yield return new object[] { "Hello, world!", "Hello, world!" };
yield return new object[] { "Hello, world! \"<>\u2665\u00E7", "Hello, world! \"<>\u2665\u00E7" };
yield return new object[] { " ", " " };
// Empty
yield return new object[] { "", "" };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(HtmlDecode_TestData))]
public static void HtmlDecode(string value, string expected)
{
Assert.Equal(expected, WebUtility.HtmlDecode(value));
}
public static IEnumerable<object[]> HtmlEncode_TestData()
{
// Single quotes need to be encoded as ' rather than ' since ' is valid both for
// HTML and XHTML, but ' is valid only for XHTML.
// For more info: http://fishbowl.pastiche.org/2003/07/01/the_curse_of_apos/
yield return new object[] { "'", "'" };
yield return new object[] { "Hello! '\"<&>\u2665\u00E7 World", "Hello! '"<&>\u2665ç World" };
yield return new object[] { "<>\"\\&", "<>"\\&" };
yield return new object[] { "\u00A0", " " };
yield return new object[] { "\u00FF", "ÿ" };
yield return new object[] { "\u0100", "\u0100" };
yield return new object[] { "\u0021\u0023\u003D\u003F", "!#=?" };
// Surrogate pairs - default strict settings
yield return new object[] { char.ConvertFromUtf32(144308), "𣎴" };
yield return new object[] { "\uD800\uDC00", "𐀀" };
yield return new object[] { "a\uD800\uDC00b", "a𐀀b" };
// High BMP non-chars
yield return new object[] { "\uFFFD", "\uFFFD" };
yield return new object[] { "\uFFFE", "\uFFFE" };
yield return new object[] { "\uFFFF", "\uFFFF" };
// Lone high surrogate
yield return new object[] { "\uD800", "\uFFFD" };
yield return new object[] { "\uD800a", "\uFFFDa" };
// Lone low surrogate
yield return new object[] { "\uDC00", "\uFFFD" };
yield return new object[] { "\uDC00a", "\uFFFDa" };
// Invalid surrogate pair
yield return new object[] { "\uD800\uD800", "\uFFFD\uFFFD" }; // High, high
yield return new object[] { "\uDC00\uD800", "\uFFFD\uFFFD" }; // Low, high
yield return new object[] { "\uDC00\uDC00", "\uFFFD\uFFFD" }; // Low, low
// Basic
yield return new object[] { "Hello, world!", "Hello, world!" };
yield return new object[] { " ", " " };
// Empty string
yield return new object[] { "", "" };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(HtmlEncode_TestData))]
public static void HtmlEncode(string value, string expected)
{
Assert.Equal(expected, WebUtility.HtmlEncode(value));
}
// Shared test data for UrlEncode + Decode and their ToBytes counterparts
public static IEnumerable<Tuple<string, string>> UrlDecode_SharedTestData()
{
// Escaping needed - case insensitive hex
yield return Tuple.Create("%2F%5C%22%09Hello!+%E2%99%A5%3F%2F%5C%22%09World!+%E2%99%A5%3F%E2%99%A5", "/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665");
yield return Tuple.Create("%2f%5c%22%09Hello!+%e2%99%a5%3f%2f%5c%22%09World!+%e2%99%a5%3F%e2%99%a5", "/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665");
// Unecessary escaping
yield return Tuple.Create("%61%62%63", "abc");
yield return Tuple.Create("\u1234%61%62%63\u1234", "\u1234abc\u1234");
// Surrogate pair
yield return Tuple.Create("%F0%90%8F%BF", "\uD800\uDFFF");
yield return Tuple.Create("\uD800\uDFFF", "\uD800\uDFFF");
// Spaces
yield return Tuple.Create("abc+def", "abc def");
yield return Tuple.Create("++++", " ");
yield return Tuple.Create(" ", " ");
// No decoding needed
yield return Tuple.Create("abc", "abc");
yield return Tuple.Create("", "");
yield return Tuple.Create("Hello, world", "Hello, world");
yield return Tuple.Create("\u1234\u2345", "\u1234\u2345");
yield return Tuple.Create("abc\u1234\u2345def\u1234", "abc\u1234\u2345def\u1234");
// Invalid percent encoding
yield return Tuple.Create("%", "%");
yield return Tuple.Create("%A", "%A");
yield return Tuple.Create("%\01", "%\01");
yield return Tuple.Create("%1\0", "%1\0");
yield return Tuple.Create("%g1", "%g1");
yield return Tuple.Create("%1g", "%1g");
yield return Tuple.Create("%G1", "%G1");
yield return Tuple.Create("%1G", "%1G");
}
public static IEnumerable<Tuple<string, string>> UrlEncode_SharedTestData()
{
// RFC 3986 requires returned hex-encoded chars to be uppercase
yield return Tuple.Create("/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665", "%2F%5C%22%09Hello!+%E2%99%A5%3F%2F%5C%22%09World!+%E2%99%A5%3F%E2%99%A5");
yield return Tuple.Create("'", "%27");
yield return Tuple.Create("\uD800\uDFFF", "%F0%90%8F%BF"); // Surrogate pairs should be encoded as 4 bytes together
// No encoding needed
yield return Tuple.Create("abc", "abc");
yield return Tuple.Create("", "");
// Spaces
yield return Tuple.Create("abc def", "abc+def");
yield return Tuple.Create(" ", "++++");
yield return Tuple.Create("++++", "%2B%2B%2B%2B");
// Tests for stray surrogate chars (all should be encoded as U+FFFD)
yield return Tuple.Create("\uD800", "%EF%BF%BD"); // High surrogate
yield return Tuple.Create("\uDC00", "%EF%BF%BD"); // Low surrogate
yield return Tuple.Create("\uDC00\uD800", "%EF%BF%BD%EF%BF%BD"); // Low + high
yield return Tuple.Create("\uD900\uDA00", "%EF%BF%BD%EF%BF%BD"); // High + high
yield return Tuple.Create("\uDE00\uDF00", "%EF%BF%BD%EF%BF%BD"); // Low + low
yield return Tuple.Create("!\uDB00@", "!%EF%BF%BD%40"); // Non-surrogate + high + non-surrogate
yield return Tuple.Create("#\uDD00$", "%23%EF%BF%BD%24"); // Non-surrogate + low + non-surrogate
}
public static IEnumerable<object[]> UrlEncodeDecode_Roundtrip_SharedTestData()
{
yield return new object[] { "'" };
yield return new object[] { "http://www.microsoft.com" };
yield return new object[] { "/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665" };
yield return new object[] { "\uD800\uDFFF" }; // Surrogate pairs
yield return new object[] { CharRange('\uE000', '\uF8FF') }; // BMP private use chars
yield return new object[] { CharRange('\uFDD0', '\uFDEF') }; // Low BMP non-chars
yield return new object[] { "\uFFFE\uFFFF" }; // High BMP non-chars
yield return new object[] { CharRange('\0', '\u001F') }; // C0 controls
yield return new object[] { CharRange('\u0080', '\u009F') }; // C1 controls
yield return new object[] { CharRange('\u202A', '\u202E') }; // BIDI embedding and override
yield return new object[] { CharRange('\u2066', '\u2069') }; // BIDI isolate
yield return new object[] { "\uFEFF" }; // BOM
}
// UrlEncode + UrlDecode
public static IEnumerable<object[]> UrlDecode_TestData()
{
foreach (var tuple in UrlDecode_SharedTestData())
yield return new object[] { tuple.Item1, tuple.Item2 };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(UrlDecode_TestData))]
public static void UrlDecode(string encodedValue, string expected)
{
Assert.Equal(expected, WebUtility.UrlDecode(encodedValue));
}
public static IEnumerable<object[]> UrlEncode_TestData()
{
foreach (var tuple in UrlEncode_SharedTestData())
yield return new object[] { tuple.Item1, tuple.Item2 };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(UrlEncode_TestData))]
public static void UrlEncode(string value, string expected)
{
Assert.Equal(expected, WebUtility.UrlEncode(value));
}
[Theory]
[MemberData(nameof(UrlEncodeDecode_Roundtrip_SharedTestData))]
public static void UrlEncodeDecode_Roundtrip(string value)
{
string encoded = WebUtility.UrlEncode(value);
Assert.Equal(value, WebUtility.UrlDecode(encoded));
}
[Fact]
public static void UrlEncodeDecode_Roundtrip_AstralPlanes()
{
// These were separated out of the UrlEncodeDecode_Roundtrip_SharedTestData member data
// due to the CharRange calls resulting in giant (several megabyte) strings. Since these
// values become part of the test names, they're resulting in gigantic logs. To avoid that,
// they've been separated out of the theory.
// Astral plane private use chars
UrlEncodeDecode_Roundtrip(CharRange(0xF0000, 0xFFFFD));
UrlEncodeDecode_Roundtrip(CharRange(0x100000, 0x10FFFD));
// Astral plane non-chars
UrlEncodeDecode_Roundtrip(CharRange(0x2FFFE, 0x10FFFF));
UrlEncodeDecode_Roundtrip("\U0001FFFE");
UrlEncodeDecode_Roundtrip("\U0001FFFF");
}
// UrlEncode + DecodeToBytes
public static IEnumerable<object[]> UrlDecodeToBytes_TestData()
{
foreach (var tuple in UrlDecode_SharedTestData())
{
byte[] input = Encoding.UTF8.GetBytes(tuple.Item1);
byte[] output = Encoding.UTF8.GetBytes(tuple.Item2);
yield return new object[] { input, 0, input.Length, output };
}
// Ranges
byte[] bytes = new byte[] { 97, 37, 67, 50, 37, 56, 48, 98 };
yield return new object[] { bytes, 1, 6, new byte[] { 194, 128 } };
yield return new object[] { bytes, 7, 1, new byte[] { 98 } };
yield return new object[] { bytes, 0, 0, new byte[0] };
yield return new object[] { bytes, 8, 0, new byte[0] };
// Empty
yield return new object[] { new byte[0], 0, 0, new byte[0] };
// Null
yield return new object[] { null, 0, 0, null };
yield return new object[] { null, int.MinValue, 0, null };
yield return new object[] { null, int.MaxValue, 0, null };
}
[Theory]
[MemberData(nameof(UrlDecodeToBytes_TestData))]
public static void UrlDecodeToBytes(byte[] value, int offset, int count, byte[] expected)
{
byte[] actual = WebUtility.UrlDecodeToBytes(value, offset, count);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlDecodeToBytes_NullBytes_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("bytes", () => WebUtility.UrlDecodeToBytes(null, 0, 1));
}
[Theory]
[InlineData(-1)]
[InlineData(2)]
public static void UrlDecodeToBytes_InvalidOffset_ThrowsArgumentOutOfRangeException(int offset)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlDecodeToBytes(new byte[1], offset, 1));
}
[Theory]
[InlineData(1, 0, -1)]
[InlineData(1, 0, 2)]
[InlineData(1, 1, 1)]
[InlineData(3, 2, 2)]
public static void UrlDecodeToBytes_InvalidCount_ThrowsArgumentOutOfRangeException(int byteCount, int offset, int count)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlDecodeToBytes(new byte[byteCount], offset, count));
}
public static IEnumerable<object[]> UrlEncodeToBytes_TestData()
{
foreach (var tuple in UrlEncode_SharedTestData())
{
byte[] input = Encoding.UTF8.GetBytes(tuple.Item1);
byte[] output = Encoding.UTF8.GetBytes(tuple.Item2);
yield return new object[] { input, 0, input.Length, output };
}
// Nothing to encode
yield return new object[] { new byte[] { 97 }, 0, 1, new byte[] { 97 } };
yield return new object[] { new byte[] { 97 }, 1, 0, new byte[0] };
yield return new object[] { new byte[] { 97, 98, 99 }, 0, 3, new byte[] { 97, 98, 99 } };
yield return new object[] { new byte[] { 97, 98, 99 }, 1, 2, new byte[] { 98, 99 } };
yield return new object[] { new byte[] { 97, 98, 99 }, 1, 1, new byte[] { 98 } };
yield return new object[] { new byte[] { 97, 98, 99, 100 }, 1, 2, new byte[] { 98, 99 } };
yield return new object[] { new byte[] { 97, 98, 99, 100 }, 2, 2, new byte[] { 99, 100 } };
// Mixture of ASCII and non-URL safe chars (full and in a range)
yield return new object[] { new byte[] { 97, 225, 136, 180, 98 }, 0, 5, new byte[] { 97, 37, 69, 49, 37, 56, 56, 37, 66, 52, 98 } };
yield return new object[] { new byte[] { 97, 225, 136, 180, 98 }, 1, 3, new byte[] { 37, 69, 49, 37, 56, 56, 37, 66, 52 } };
// Empty
yield return new object[] { new byte[0], 0, 0, new byte[0] };
// Null
yield return new object[] { null, 0, 0, null };
yield return new object[] { null, int.MinValue, 0, null };
yield return new object[] { null, int.MaxValue, 0, null };
}
[Theory]
[MemberData(nameof(UrlEncodeToBytes_TestData))]
public static void UrlEncodeToBytes(byte[] value, int offset, int count, byte[] expected)
{
byte[] actual = WebUtility.UrlEncodeToBytes(value, offset, count);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlEncodeToBytes_NullBytes_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("bytes", () => WebUtility.UrlEncodeToBytes(null, 0, 1));
}
[Theory]
[InlineData(-1)]
[InlineData(2)]
public static void UrlEncodeToBytes_InvalidOffset_ThrowsArgumentOutOfRangeException(int offset)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlEncodeToBytes(new byte[1], offset, 0));
}
[Theory]
[InlineData(1, 0, -1)]
[InlineData(1, 0, 2)]
[InlineData(1, 1, 1)]
[InlineData(3, 2, 2)]
public static void UrlEncodeToBytes_InvalidCount_ThrowsArgumentOutOfRangeExceptioh(int byteCount, int offset, int count)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlEncodeToBytes(new byte[byteCount], offset, count));
}
[Theory]
[MemberData(nameof(UrlEncodeDecode_Roundtrip_SharedTestData))]
public static void UrlEncodeDecodeToBytes_Roundtrip(string url)
{
byte[] input = Encoding.UTF8.GetBytes(url);
byte[] encoded = WebUtility.UrlEncodeToBytes(input, 0, input.Length);
Assert.Equal(input, WebUtility.UrlDecodeToBytes(encoded, 0, encoded.Length));
}
[Fact]
public static void UrlEncodeDecodeToBytes_Roundtrip_AstralPlanes()
{
// These were separated out of the UrlEncodeDecode_Roundtrip_SharedTestData member data
// due to the CharRange calls resulting in giant (several megabyte) strings. Since these
// values become part of the test names, they're resulting in gigantic logs. To avoid that,
// they've been separated out of the theory.
// Astral plane private use chars
UrlEncodeDecodeToBytes_Roundtrip(CharRange(0xF0000, 0xFFFFD));
UrlEncodeDecodeToBytes_Roundtrip(CharRange(0x100000, 0x10FFFD));
// Astral plane non-chars
UrlEncodeDecodeToBytes_Roundtrip(CharRange(0x2FFFE, 0x10FFFF));
UrlEncodeDecodeToBytes_Roundtrip("\U0001FFFE");
UrlEncodeDecodeToBytes_Roundtrip("\U0001FFFF");
}
[Theory]
[InlineData("FooBarQuux", 3, 7, "BarQuux")]
public static void UrlEncodeToBytes_ExcludeIrrelevantData(string value, int offset, int count, string expected)
{
byte[] input = Encoding.UTF8.GetBytes(value);
byte[] encoded = WebUtility.UrlEncodeToBytes(input, offset, count);
string actual = Encoding.UTF8.GetString(encoded);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlEncodeToBytes_NoEncodingNeeded_ReturnsNewClonedArray()
{
// We have to make sure it always returns a new array, to
// prevent problems where the input array is changed if
// the output one is modified.
byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Encoding");
byte[] output = WebUtility.UrlEncodeToBytes(input, 0, input.Length);
Assert.NotSame(input, output);
}
[Fact]
public static void UrlDecodeToBytes_NoDecodingNeeded_ReturnsNewClonedArray()
{
byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Decoding");
byte[] output = WebUtility.UrlDecodeToBytes(input, 0, input.Length);
Assert.NotSame(input, output);
}
public static string CharRange(int start, int end)
{
Debug.Assert(start <= end);
int capacity = end - start + 1;
var builder = new StringBuilder(capacity);
for (int i = start; i <= end; i++)
{
// 0 -> \0, 65 -> A, 0x10FFFF -> \U0010FFFF
builder.Append(char.ConvertFromUtf32(i));
}
return builder.ToString();
}
[Theory]
[MemberData(nameof(HtmlDecode_TestData))]
public static void HtmlDecode_TextWriterOutput(string value, string expected)
{
if(value == null)
expected = string.Empty;
StringWriter output = new StringWriter(CultureInfo.InvariantCulture);
WebUtility.HtmlDecode(value, output);
Assert.Equal(expected, output.ToString());
}
[Theory]
[MemberData(nameof(HtmlEncode_TestData))]
public static void HtmlEncode_TextWriterOutput(string value, string expected)
{
if(value == null)
expected = string.Empty;
StringWriter output = new StringWriter(CultureInfo.InvariantCulture);
WebUtility.HtmlEncode(value, output);
Assert.Equal(expected, output.ToString());
}
}
}
| |
/** Copyright (c) 2006, All-In-One Creations, Ltd.
* 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 All-In-One Creations, Ltd. 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.
**/
/**
* Project: emergetk: stateful web framework for the masses
* File name: FilterInfo.cs
* Description: filter defininition for RecordLists.
*
* Author: Ben Joldersma
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace EmergeTk.Model
{
public enum FilterOperation
{
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqual,
Equals,
DoesNotEqual,
In,
NotIn,
Contains,
NotContains
}
public class FilterInfo : IQueryInfo, IFilterRule
{
public string ColumnName;
public object Value;
public FilterOperation Operation;
public FilterInfo(string columnName, object value):this(columnName,value,FilterOperation.Equals){}
public FilterInfo(string columnName, object value, FilterOperation op)
{
ColumnName = columnName;
Value = value;
Operation = op;
}
public static bool Filter(FilterOperation op, object lvalue, object rvalue)
{
bool isMatch = false;
switch (op)
{
case FilterOperation.Equals:
case FilterOperation.GreaterThan:
case FilterOperation.LessThan:
case FilterOperation.DoesNotEqual:
if (lvalue == null || rvalue == null)
{
return op == FilterOperation.DoesNotEqual;
}
if (lvalue.GetType() != rvalue.GetType())
{
try
{
rvalue = PropertyConverter.Convert(rvalue, lvalue.GetType());
}
catch
{
if (op == FilterOperation.DoesNotEqual)
return true;
}
}
IComparable l = lvalue as IComparable;
IComparable r = rvalue as IComparable;
if( l == null || r == null )
{
if( op == FilterOperation.Equals )
{
if( rvalue == null && lvalue == null ) //should null == null?
return true;
else if( rvalue == null || lvalue == null )
return false;
return rvalue.Equals(lvalue);
}
else if( op == FilterOperation.DoesNotEqual )
{
if( rvalue == null || lvalue == null )
return true;
return ! rvalue.Equals(lvalue);
}
}
int result = l.CompareTo( r );
if( result == 0 )
isMatch = op == FilterOperation.Equals;
else if( result < 0 )
isMatch = op == FilterOperation.LessThan || op == FilterOperation.DoesNotEqual;
else
isMatch = op == FilterOperation.GreaterThan || op == FilterOperation.DoesNotEqual;
break;
case FilterOperation.In:
case FilterOperation.NotIn:
if (rvalue is IList)
{
IList list = rvalue as IList;
isMatch = list.Contains(lvalue);
}
else if( rvalue is IRecordList )
{
IRecordList irl = (IRecordList)rvalue;
isMatch = irl.Contains(lvalue as AbstractRecord);
}
else if (rvalue is string)
{
isMatch = rvalue.ToString().Contains(lvalue.ToString());
}
if (op == FilterOperation.NotIn) isMatch = !isMatch;
break;
case FilterOperation.Contains:
case FilterOperation.NotContains:
if( lvalue is IList )
{
isMatch = (lvalue as IList).Contains(rvalue);
}
else if( lvalue is string && rvalue != null )
{
isMatch = (lvalue as string).Contains(rvalue.ToString());
}
if( op == FilterOperation.NotContains )
isMatch = ! isMatch;
break;
}
return isMatch;
}
public override string ToString()
{
object oVal = Value is AbstractRecord ? (Value as AbstractRecord).ObjectId : Value;
string v = oVal != null ? oVal.ToString() :null;
if( this.Operation == FilterOperation.Equals && oVal == null )
{
return ColumnName + " IS NULL";
}
if( this.Operation == FilterOperation.DoesNotEqual && oVal == null )
{
return ColumnName + " IS NOT NULL";
}
if( this.Operation == FilterOperation.Contains || this.Operation == FilterOperation.NotContains )
{
v = Util.Surround(v,"%");
}
else if( this.Operation == FilterOperation.In || this.Operation == FilterOperation.NotIn)
{
if( Value is IList )
v = string.Format("({0})",Util.Join( (IList)Value, ",", false ) );
else if( Value is IRecordList )
{
IRecordList irl = (IRecordList)Value;
v = string.Format("({0})",Util.Join( irl.ToIdArray(), ",", false ) );
}
}
if( oVal is DateTime )
{
DateTime d = (DateTime)oVal;
v = "'" + d.ToString("s") + "'";
}
else if (oVal is string || oVal is bool)
{
v = "'" + v.ToString().Replace("'", "''") + "'";
}
else if (oVal is Enum)
{
v = Convert.ToInt32(oVal).ToString();
}
return string.Format("{0} {1} {2}", ColumnName, FilterOperationToString(Operation), v);
}
public override bool Equals (object o)
{
if( o is FilterInfo )
{
FilterInfo fi = o as FilterInfo;
return fi.ColumnName == this.ColumnName && fi.Operation == this.Operation && fi.Value == this.Value;
}
return base.Equals (o);
}
public override int GetHashCode ()
{
return (Operation.ToString() + ColumnName + Value.ToString()).GetHashCode();
}
static public string FilterOperationToString(FilterOperation op)
{
string symbol = "UNK";
switch (op)
{
case FilterOperation.Equals:
symbol = "=";
break;
case FilterOperation.DoesNotEqual:
symbol = "<>";
break;
case FilterOperation.GreaterThan:
symbol = ">";
break;
case FilterOperation.LessThan:
symbol = "<";
break;
case FilterOperation.In:
symbol = "IN";
break;
case FilterOperation.NotIn:
symbol = "NOT IN";
break;
case FilterOperation.Contains:
symbol = "LIKE";
break;
case FilterOperation.NotContains:
symbol = "NOT LIKE";
break;
case FilterOperation.GreaterThanOrEqual:
symbol = ">=";
break;
case FilterOperation.LessThanOrEqual:
symbol = "<=";
break;
}
return symbol;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
using Twin.Logging;
namespace Twin {// [Twin] Copyright eBay Inc., Twin authors, and other contributors.
// This file is provided to you under the terms of the Apache License, Version 2.0.
// See LICENSE.txt and NOTICE.txt for license and copyright information.
// Represents a file on disk
// On creation, uses win32 calls to open the file and get its volume and serial number
// this is used for equality testing. This seems to be the only reliable way to determine whether
// two paths are to the same file, and there's no C# API.
// http://stackoverflow.com/questions/410705/best-way-to-determine-if-two-path-reference-to-same-file-in-c
// new FileRef("path1").equals(new FileRef("path2"));
//
// Note that if the file must be held open by some process between creation of the filerefs for this check to be valid
// we use it for attaching to running processes, so this is no problem.
// otherwise, use FileRef.PathsAreEqual which ensures this.
class FileRef {
private uint fileIndexLow;
private uint fileIndexHigh;
private uint volumeIndex;
private FileRef(IntPtr handle) {
populate(handle);
}
public FileRef(Process process) : this(GetProcessPath(process)) {
}
public override bool Equals(Object other) {
if (!(other is FileRef))
return false;
FileRef otherRef = (FileRef)other;
return otherRef.fileIndexLow == fileIndexLow && otherRef.fileIndexHigh == fileIndexHigh && otherRef.volumeIndex == volumeIndex;
}
public override int GetHashCode() {
return (int)((fileIndexHigh * 31 + fileIndexLow) * 31 + volumeIndex);
}
public static bool PathsAreEqual(string path1, string path2) {
IntPtr handle1 = GetFileHandle(path1);
try {
IntPtr handle2 = GetFileHandle(path2);
try {
return new FileRef(handle1).Equals(new FileRef(handle2));
} finally {
CloseHandle(handle2);
}
} finally {
CloseHandle(handle1);
}
}
public FileRef(string path) {
IntPtr handle = GetFileHandle(path);
try {
populate(handle);
} finally {
CloseHandle(handle);
}
}
private void populate(IntPtr fh) {
BY_HANDLE_FILE_INFORMATION info;
if (!GetFileInformationByHandle(fh, out info))
throw new Win32Exception(Marshal.GetLastWin32Error());
this.fileIndexHigh = info.FileIndexHigh;
this.fileIndexLow = info.FileIndexLow;
this.volumeIndex = info.VolumeSerialNumber;
}
private static string GetProcessPath(Process process) {
IntPtr handle = OpenProcess(0x410, 0, (uint)process.Id); // PROCESS_QUERY_INFORMATION | PROCESS_VM_READ
if (handle == IntPtr.Zero) {
int lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_ACCESS_DENIED)
throw new UnauthorizedAccessException("Couldn't read process: "+process, new Win32Exception(lastError));
throw new Exception("Cannot open process: " + process, new Win32Exception(lastError));
}
try {
StringBuilder result = new StringBuilder(1024);
if (GetModuleFileNameEx(handle, IntPtr.Zero, result, result.Capacity) == 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
return result.ToString();
} finally {
CloseHandle(handle);
}
}
public static IntPtr GetFileHandle(string path) {
if (path == null)
throw new ArgumentNullException("path");
IntPtr handle = CreateFile(
path,
EFileAccess.GenericNone,
EFileShare.All,
IntPtr.Zero,
ECreationDisposition.OpenExisting,
EFileAttributes.Normal,
IntPtr.Zero);
if (handle == INVALID_HANDLE)
throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to get handle for " + path);
return handle;
}
// pinvoke cruft
[DllImport("psapi.dll", SetLastError = true)]
static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, [In] [MarshalAs(UnmanagedType.U4)] int nSize);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId);
private const int ERROR_ACCESS_DENIED = 5;
private static readonly IntPtr INVALID_HANDLE = (IntPtr)(-1);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
[StructLayout(LayoutKind.Sequential)]
private struct BY_HANDLE_FILE_INFORMATION {
public uint FileAttributes;
public FILETIME CreationTime;
public FILETIME LastAccessTime;
public FILETIME LastWriteTime;
public uint VolumeSerialNumber;
public uint FileSizeHigh;
public uint FileSizeLow;
public uint NumberOfLinks;
public uint FileIndexHigh;
public uint FileIndexLow;
}
[StructLayout(LayoutKind.Sequential)]
private struct FILETIME {
public UInt32 dwLowDateTime;
public UInt32 dwHighDateTime;
}
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreateFile(
string fileName,
EFileAccess fileAccess,
EFileShare fileShare,
IntPtr securityAttributes,
ECreationDisposition creationDisposition,
EFileAttributes flags,
IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[Flags]
private enum EFileAccess : uint {
GenericNone = 0,
GenericRead = 0x80000000,
GenericWrite = 0x40000000,
GenericExecute = 0x20000000,
GenericAll = 0x10000000
}
[Flags]
private enum EFileShare : uint {
None = 0x00000000,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004,
All = 0x00000007
}
private enum ECreationDisposition : uint {
New = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5
}
[Flags]
private enum EFileAttributes : uint {
Readonly = 0x00000001,
Hidden = 0x00000002,
System = 0x00000004,
Directory = 0x00000010,
Archive = 0x00000020,
Device = 0x00000040,
Normal = 0x00000080,
Temporary = 0x00000100,
SparseFile = 0x00000200,
ReparsePoint = 0x00000400,
Compressed = 0x00000800,
Offline = 0x00001000,
NotContentIndexed = 0x00002000,
Encrypted = 0x00004000,
Write_Through = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x08000000,
DeleteOnClose = 0x04000000,
BackupSemantics = 0x02000000,
PosixSemantics = 0x01000000,
OpenReparsePoint = 0x00200000,
OpenNoRecall = 0x00100000,
FirstPipeInstance = 0x00080000
}
}
}
| |
using DotVVM.Framework.Compilation.Styles;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Routing;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.ViewModel;
using DotVVM.Framework.ViewModel.Serialization;
using DotVVM.Samples.BasicSamples.Controls;
using DotVVM.Samples.BasicSamples.ViewModels.FeatureSamples.Redirect;
using DotVVM.Samples.BasicSamples.ViewModels.FeatureSamples.Serialization;
using DotVVM.Samples.BasicSamples.ViewModels.FeatureSamples.StaticCommand;
using DotVVM.Samples.Common;
using DotVVM.Samples.Common.ViewModels.FeatureSamples.DependencyInjection;
using DotVVM.Samples.Common.ViewModels.FeatureSamples.ServerSideStyles;
using Microsoft.Extensions.DependencyInjection;
using DotVVM.Framework.Controls;
using System.Collections.Generic;
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
using DotVVM.Samples.Common.Api.AspNetCore;
using DotVVM.Samples.Common.Api.Owin;
using DotVVM.Samples.Common.Controls;
using DotVVM.Framework.Utils;
using DotVVM.Framework.Compilation.Javascript;
using DotVVM.Framework.Compilation.Javascript.Ast;
using DotVVM.Samples.Common.ViewModels.FeatureSamples.JavascriptTranslation;
using DotVVM.Samples.Common.Views.FeatureSamples.PostbackAbortSignal;
using DotVVM.Samples.Common.ViewModels.FeatureSamples.BindingVariables;
using DotVVM.Samples.Common.Views.ControlSamples.TemplateHost;
namespace DotVVM.Samples.BasicSamples
{
public class DotvvmStartup : IDotvvmStartup
{
public const string GitHubTokenEnvName = "GITHUB_TOKEN";
public const string GitHubTokenConfigName = "githubApiToken";
public void Configure(DotvvmConfiguration config, string applicationPath)
{
config.DefaultCulture = "en-US";
AddControls(config);
AddStyles(config);
AddRedirections(config);
AddRoutes(config);
// configure serializer
config.GetSerializationMapper()
.Map(typeof(SerializationViewModel), map => {
map.Property(nameof(SerializationViewModel.Value)).Bind(Direction.ServerToClient);
map.Property(nameof(SerializationViewModel.Value2)).Bind(Direction.ClientToServer);
map.Property(nameof(SerializationViewModel.IgnoredProperty)).Ignore();
});
// new GithubApiClient.GithubApiClient().Repos.GetIssues()
config.RegisterApiGroup(typeof(Common.Api.Owin.TestWebApiClientOwin), "http://localhost:61453/", "Scripts/TestWebApiClientOwin.js", "_apiOwin");
config.RegisterApiClient(typeof(Common.Api.AspNetCore.TestWebApiClientAspNetCore), "http://localhost:5001/", "Scripts/TestWebApiClientAspNetCore.js", "_apiCore");
config.RegisterApiClient(typeof(AzureFunctionsApi.Client), "https://dotvvmazurefunctionstest.azurewebsites.net/", "Scripts/AzureFunctionsApiClient.js", "_azureFuncApi");
LoadSampleConfiguration(config, applicationPath);
config.Markup.JavascriptTranslator.MethodCollection.AddMethodTranslator(typeof(JavascriptTranslationTestMethods),
nameof(JavascriptTranslationTestMethods.Unwrap),
new GenericMethodCompiler((a) =>
new JsIdentifierExpression("unwrap")
.Invoke(a[1])
), allowGeneric: true, allowMultipleMethods: true);
config.Diagnostics.CompilationPage.IsApiEnabled = true;
config.Diagnostics.CompilationPage.ShouldCompileAllOnLoad = false;
config.AssertConfigurationIsValid();
config.RouteTable.Add("Errors_Routing_NonExistingView", "Errors/Routing/NonExistingView", "Views/Errors/Routing/NonExistingView.dothml");
}
private void LoadSampleConfiguration(DotvvmConfiguration config, string applicationPath)
{
var jsonText = File.ReadAllText(Path.Combine(applicationPath, "sampleConfig.json"));
var json = JObject.Parse(jsonText);
// find active profile
var activeProfile = json.Value<string>("activeProfile");
var profiles = json.Value<JArray>("profiles");
var profile = profiles.Single(p => p.Value<string>("name") == activeProfile);
JsonConvert.PopulateObject(profile.Value<JObject>("config").ToString(), config);
var githubTokenEnv = Environment.GetEnvironmentVariable(GitHubTokenEnvName);
if (githubTokenEnv is object)
{
json.Value<JObject>("appSettings")[GitHubTokenConfigName] = githubTokenEnv;
}
SampleConfiguration.Initialize(
json.Value<JObject>("appSettings").Properties().ToDictionary(p => p.Name, p => p.Value.Value<string>())
);
}
public static void AddStyles(DotvvmConfiguration config)
{
// HasViewInDirectory samples
config.Styles.Register<ServerSideStylesControl>(c => c.HasViewInDirectory("Views/FeatureSamples/ServerSideStyles/DirectoryStyle/"))
.SetAttribute("directory", "matching");
config.Styles.Register("customTagName", c => c.HasViewInDirectory("Views/FeatureSamples/ServerSideStyles/DirectoryStyle/"))
.SetAttribute("directory", "matching");
// HasDataContext and HasRootDataContext samples
config.Styles.Register("customDataContextTag", c => c.HasRootDataContext<ServerSideStylesMatchingViewModel>()).
SetAttribute("rootDataContextCheck", "matching");
config.Styles.Register("customDataContextTag", c => c.HasDataContext<ServerSideStylesMatchingViewModel.TestingObject>()).
SetAttribute("dataContextCheck", "matching");
// All style samples
config.Styles.Register<ServerSideStylesControl>()
.SetAttribute("value", "Text changed")
.SetDotvvmProperty(ServerSideStylesControl.CustomProperty, "Custom property changed", StyleOverrideOptions.Ignore)
.SetAttribute("class", "Class changed", StyleOverrideOptions.Overwrite);
config.Styles.Register("customTagName")
.SetAttribute("ignore", "Attribute ignored", StyleOverrideOptions.Ignore)
.SetAttribute("overwrite", "Attribute changed", StyleOverrideOptions.Overwrite)
.SetAttribute("append", "Attribute appended", StyleOverrideOptions.Append)
.SetAttribute("class", "new-class", StyleOverrideOptions.Append);
config.Styles.Register<ServerSideStylesControl>(c => c.HasProperty(ServerSideStylesControl.CustomProperty), false)
.SetAttribute("derivedAttr", "Derived attribute");
config.Styles.Register<ServerSideStylesControl>(c => c.HasProperty(ServerSideStylesControl.AddedProperty))
.SetAttribute("addedAttr", "Added attribute");
config.Styles.Register<Button>(c => c.HasHtmlAttribute("server-side-style-attribute"))
.SetControlProperty(PostBack.HandlersProperty, new ConfirmPostBackHandler("ConfirmPostBackHandler Content"));
}
private static void AddRedirections(DotvvmConfiguration config)
{
config.RouteTable.AddUrlRedirection("Redirection1", "FeatureSamples/Redirect/RedirectionHelpers_PageA", (_) => "https://www.dotvvm.com");
config.RouteTable.AddRouteRedirection("Redirection2", "FeatureSamples/Redirect/RedirectionHelpers_PageB/{Id}", (_) => "FeatureSamples_Redirect_RedirectionHelpers_PageC-PageDetail", new { Id = 66 }, urlSuffixProvider: c => "?test=aaa");
config.RouteTable.AddRouteRedirection("Redirection3", "FeatureSamples/Redirect/RedirectionHelpers_PageD/{Id}", (_) => "FeatureSamples_Redirect_RedirectionHelpers_PageE-PageDetail", new { Id = 77 },
parametersProvider: (context) => {
var newDict = new Dictionary<string, object>(context.Parameters);
newDict["Id"] = 1221;
return newDict;
});
}
private static void AddRoutes(DotvvmConfiguration config)
{
config.RouteTable.Add("Default", "", "Views/Default.dothtml");
config.RouteTable.Add("ComplexSamples_SPARedirect_home", "ComplexSamples/SPARedirect", "Views/ComplexSamples/SPARedirect/home.dothtml");
config.RouteTable.Add("ControlSamples_SpaContentPlaceHolder_HistoryApi_PageA", "ControlSamples/SpaContentPlaceHolder_HistoryApi/PageA/{Id}", "Views/ControlSamples/SpaContentPlaceHolder_HistoryApi/PageA.dothtml", new { Id = 0 });
config.RouteTable.Add("ControlSamples_SpaContentPlaceHolder_HistoryApi", "ControlSamples/SpaContentPlaceHolder_HistoryApi", "Views/ControlSamples/SpaContentPlaceHolder_HistoryApi/SpaMaster.dotmaster");
config.RouteTable.Add("ControlSamples_TextBox_TextBox_Format", "ControlSamples/TextBox/TextBox_Format", "Views/ControlSamples/TextBox/TextBox_Format.dothtml", presenterFactory: LocalizablePresenter.BasedOnQuery("lang"));
config.RouteTable.Add("ControlSamples_TextBox_TextBox_Format_Binding", "ControlSamples/TextBox/TextBox_Format_Binding", "Views/ControlSamples/TextBox/TextBox_Format_Binding.dothtml", presenterFactory: LocalizablePresenter.BasedOnQuery("lang"));
config.RouteTable.Add("FeatureSamples_ParameterBinding_ParameterBinding", "FeatureSamples/ParameterBinding/ParameterBinding/{A}", "Views/FeatureSamples/ParameterBinding/ParameterBinding.dothtml", new { A = 123 });
config.RouteTable.Add("FeatureSamples_Localization_Localization", "FeatureSamples/Localization/Localization", "Views/FeatureSamples/Localization/Localization.dothtml", presenterFactory: LocalizablePresenter.BasedOnQuery("lang"));
config.RouteTable.Add("FeatureSamples_Localization_Localization_NestedPage_Type", "FeatureSamples/Localization/Localization_NestedPage_Type", "Views/FeatureSamples/Localization/Localization_NestedPage_Type.dothtml", presenterFactory: LocalizablePresenter.BasedOnQuery("lang"));
config.RouteTable.Add("FeatureSamples_ParameterBinding_OptionalParameterBinding", "FeatureSamples/ParameterBinding/OptionalParameterBinding/{Id?}", "Views/FeatureSamples/ParameterBinding/OptionalParameterBinding.dothtml");
config.RouteTable.Add("FeatureSamples_ParameterBinding_OptionalParameterBinding2", "FeatureSamples/ParameterBinding/OptionalParameterBinding2/{Id?}", "Views/FeatureSamples/ParameterBinding/OptionalParameterBinding.dothtml", new { Id = 300 });
config.RouteTable.Add("FeatureSamples_Validation_Localization", "FeatureSamples/Validation/Localization", "Views/FeatureSamples/Validation/Localization.dothtml", presenterFactory: LocalizablePresenter.BasedOnQuery("lang"));
config.RouteTable.Add("FeatureSamples_Localization_Globalize", "FeatureSamples/Localization/Globalize", "Views/FeatureSamples/Localization/Globalize.dothtml", presenterFactory: LocalizablePresenter.BasedOnQuery("lang"));
config.RouteTable.AutoDiscoverRoutes(new DefaultRouteStrategy(config));
config.RouteTable.Add("ControlSamples_Repeater_RouteLinkQuery-PageDetail", "ControlSamples/Repeater/RouteLinkQuery/{Id}", "Views/ControlSamples/Repeater/RouteLinkQuery.dothtml", new { Id = 0 });
config.RouteTable.Add("FeatureSamples_Redirect_RedirectionHelpers_PageB-PageDetail", "FeatureSamples/Redirect/RedirectionHelpers_PageB/{Id}", "Views/FeatureSamples/Redirect/RedirectionHelpers_PageB.dothtml", new { Id = 22 });
config.RouteTable.Add("FeatureSamples_Redirect_RedirectionHelpers_PageC-PageDetail", "FeatureSamples/Redirect/RedirectionHelpers_PageC/{Id}", "Views/FeatureSamples/Redirect/RedirectionHelpers_PageC.dothtml", new { Id = 33 });
config.RouteTable.Add("FeatureSamples_Redirect_RedirectionHelpers_PageD-PageDetail", "FeatureSamples/Redirect/RedirectionHelpers_PageD/{Id}", "Views/FeatureSamples/Redirect/RedirectionHelpers_PageD.dothtml", new { Id = 44 });
config.RouteTable.Add("FeatureSamples_Redirect_RedirectionHelpers_PageE-PageDetail", "FeatureSamples/Redirect/RedirectionHelpers_PageE/{Id}", "Views/FeatureSamples/Redirect/RedirectionHelpers_PageE.dothtml", new { Id = 55 });
config.RouteTable.Add("RepeaterRouteLink-PageDetail", "ControlSamples/Repeater/RouteLink/{Id}", "Views/ControlSamples/Repeater/RouteLink.dothtml", new { Id = 0 });
config.RouteTable.Add("RepeaterRouteLink-PageDetail_IdOptional", "ControlSamples/Repeater/RouteLink/{Id?}", "Views/ControlSamples/Repeater/RouteLink.dothtml");
config.RouteTable.Add("RepeaterRouteLink-PageDetail_IdOptionalPrefixed", "ControlSamples/Repeater/RouteLink/id-{Id?}", "Views/ControlSamples/Repeater/RouteLink.dothtml");
config.RouteTable.Add("RepeaterRouteLink-PageDetail_IdOptionalAtStart", "id-{Id?}/ControlSamples/Repeater/RouteLink", "Views/ControlSamples/Repeater/RouteLink.dothtml");
config.RouteTable.Add("RepeaterRouteLinkUrlSuffix-PageDetail", "ControlSamples/Repeater/RouteLinkUrlSuffix/{Id}", "Views/ControlSamples/Repeater/RouteLink.dothtml", new { Id = 0 });
config.RouteTable.Add("FeatureSamples_Redirect_RedirectFromPresenter", "FeatureSamples/Redirect/RedirectFromPresenter", provider => new ViewModels.FeatureSamples.Redirect.RedirectingPresenter());
config.RouteTable.Add("FeatureSamples_EmbeddedResourceControls_EmbeddedResourceView", "FeatureSamples/EmbeddedResourceControls/EmbeddedResourceView", "embedded://EmbeddedResourceControls/EmbeddedResourceView.dothtml");
config.RouteTable.Add("FeatureSamples_PostBack_PostBackHandlers_Localized", "FeatureSamples/PostBack/PostBackHandlers_Localized", "Views/FeatureSamples/PostBack/ConfirmPostBackHandler.dothtml", presenterFactory: LocalizablePresenter.BasedOnQuery("lang"));
config.RouteTable.Add("Errors_UndefinedRouteLinkParameters-PageDetail", "Erros/UndefinedRouteLinkParameters/{Id}", "Views/Errors/UndefinedRouteLinkParameters.dothtml", new { Id = 0 });
}
private static void AddControls(DotvvmConfiguration config)
{
config.Markup.AddCodeControls("cc", typeof(Controls.ServerSideStylesControl));
config.Markup.AddCodeControls("cc", typeof(Controls.TextRepeater));
config.Markup.AddCodeControls("cc", typeof(DerivedControlUsageValidationTestControl));
config.Markup.AddCodeControls("PropertyUpdate", typeof(Controls.ServerRenderedLabel));
config.Markup.AddMarkupControl("IdGeneration", "Control", "Views/FeatureSamples/IdGeneration/IdGeneration_control.dotcontrol");
config.Markup.AddMarkupControl("FileUploadInRepeater", "FileUploadWrapper", "Views/ComplexSamples/FileUploadInRepeater/FileUploadWrapper.dotcontrol");
config.Markup.AddMarkupControl("cc", "RecursiveTextRepeater", "Views/FeatureSamples/PostBack/RecursiveTextRepeater.dotcontrol");
config.Markup.AddMarkupControl("cc", "RecursiveTextRepeater2", "Views/FeatureSamples/PostBack/RecursiveTextRepeater2.dotcontrol");
config.Markup.AddMarkupControl("cc", "ModuleControl", "Views/FeatureSamples/ViewModules/ModuleControl.dotcontrol");
config.Markup.AddMarkupControl("cc", "Incrementer", "Views/FeatureSamples/ViewModules/Incrementer.dotcontrol");
config.Markup.AddMarkupControl("cc", "TemplatedListControl", "Views/ControlSamples/TemplateHost/TemplatedListControl.dotcontrol");
config.Markup.AddMarkupControl("cc", "TemplatedMarkupControl", "Views/ControlSamples/TemplateHost/TemplatedMarkupControl.dotcontrol");
config.Markup.AddCodeControls("cc", typeof(CompositeControlWithTemplate));
config.Markup.AddCodeControls("cc", typeof(Loader));
config.Markup.AddMarkupControl("sample", "EmbeddedResourceControls_Button", "embedded://EmbeddedResourceControls/Button.dotcontrol");
config.Markup.AutoDiscoverControls(new DefaultControlRegistrationStrategy(config, "sample", "Views/"));
}
}
}
| |
using System;
using System.Data;
using System.Data.Odbc;
using ByteFX.Data.MySqlClient;
using ByteFX.Data;
using System.Collections;
using JCSLA;
namespace QED.Business{
public class Groups : BusinessCollectionBase {
#region Instance Data
private static object syncRoot = new Object();
static Groups _instance;
#endregion
const string _table = "Groups";
MySqlDBLayer _dbLayer;
#region Collection Members
public Group Add(Group obj) {
obj.BusinessCollection = this;
List.Add(obj); return obj;
}
public bool Contains(Group obj) {
foreach(Group child in List) {
if (obj.Equals(child)){
return true;
}
}
return false;
}
public Group this[int id] {
get{
return (Group) List[id];
}
}
public Group item(int id) {
foreach(Group obj in List) {
if (obj.Id == id)
return obj;
}
return null;
}
#endregion
#region DB Access and ctors
public static Groups Inst {
get {
if (_instance == null) {
lock (syncRoot) {
if (_instance == null)
_instance = new Groups();
}
}
return _instance;
}
}
private Groups() {
Group obj;
using(MySqlConnection conn = Connections.Inst.item("HTS").MySqlConnection){
using(MySqlDataReader dr = MySqlDBLayer.LoadAll(conn, _table)){
while(dr.Read()) {
obj = new Group(dr);
obj.BusinessCollection = this;
List.Add(new Group(dr));
}
}
}
}
#endregion
#region Business Members
public Groups Active{
get{
Groups gs = new Groups();
foreach(Group obj in List) {
if ( !obj.Retired)
gs.Add(obj);
}
return gs;
}
}
#endregion
#region System.Object overrides
public override string ToString(){
return this.ToString();
}
#endregion
}
public class Group : BusinessBase{
#region Instance Data
string _table = "Groups";
int _id;
string _name;
string _description;
string _email;
MySqlDBLayer _dbLayer;
BusinessCollectionBase _businessCollection;
bool _retired;
#endregion
#region DB Access / ctors
public override string Table {
get {
return _table;
}
}
public override object Conn {
get {
return Connections.Inst.item("HTS").MySqlConnection;
}
}
private void Setup() {
if (_dbLayer == null) {
_dbLayer = new MySqlDBLayer(this);
}
}
public override void SetId(int id) {
/* This function is public for technical reasons. It is intended to be used only by the db
* layer*/
_id = id;
}
public override BusinessCollectionBase BusinessCollection {
get{
return _businessCollection;
}
set {
_businessCollection = value;
}
}
public Group() {
Setup();
base.MarkNew();
}
public Group(int id) {
Setup();
this.Load(id);
}
public Group(MySqlDataReader dr) {
this.Load(dr);
}
public void Load(int id) {
SetId(id);
using(MySqlConnection conn = (MySqlConnection) this.Conn){
conn.Open();
using(MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + this.Table + " WHERE ID = @ID", conn)){
cmd.Parameters.Add("@Id", this.Id);
using (MySqlDataReader dr = cmd.ExecuteReader()){
if (dr.HasRows) {
dr.Read();
this.Load(dr);
}else{
throw new Exception("Groups " + id + " doesn't exist.");
}
}
}
}
}
public void Load(MySqlDataReader dr) {
Setup();
SetId(Convert.ToInt32(dr["Id"]));
string name = Convert.ToString(dr["Name"]);
string[] splitName = System.Text.RegularExpressions.Regex.Split(name, " - ");
if (splitName.Length == 1) {
this._name = splitName[0].Trim();
this._retired = false;
}else{
if (splitName[0] == "RETIRED") {
this._retired = true;
this._name = splitName[1].Trim();
}else{
this._retired = false;
this._name = splitName[0].Trim();
}
}
this._description = Convert.ToString(dr["Description"]);
this._email = Convert.ToString(dr["Email"]);
MarkOld();
}
public override void Update(){
throw new NotSupportedException("Update not available. Groups are read only.");
}
public override Hashtable ParamHash {
get {
Hashtable paramHash = new Hashtable();
paramHash.Add("@Id", this.Id);
return paramHash;
}
}
#endregion
#region Business Properties
public override int Id{
get{
return _id;
}
}
public string Name{
get{
return _name;
}
}
public string Description{
get{
return _description;
}
}
public string Email{
get{
return _email;
}
}
public bool Retired{
get{
return _retired;
}
}
#endregion
#region Validation Management
public override bool IsValid {
get {
return (this.BrokenRules.Count == 0);
}
}
public override BrokenRules BrokenRules {
get {
BrokenRules br = new BrokenRules();
return br;
}
}
#endregion
#region System.Object overrides
public override string ToString(){
return base.ToString();
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.WebSites;
using Microsoft.Azure.Management.WebSites.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.WebSites
{
/// <summary>
/// Operations for managing the Web Hosting Plans in a resource group. Web
/// hosting plans (WHPs) represent a set of features and capacity that you
/// can share across your web sites. Web hosting plans support the 4 Azure
/// Web Sites pricing tiers (Free, Shared, Basic, and Standard) where each
/// tier has its own capabilities and capacity. Sites in the same
/// subscription, resource group, and geographic location can share a web
/// hosting plan. All the sites sharing a web hosting plan can leverage
/// all the capabilities and features defined by the web hosting plan
/// tier. All web sites associated with a given web hosting plan run on
/// the resources defined by the web hosting plan. (see
/// http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
/// for more information)
/// </summary>
internal partial class WebHostingPlanOperations : IServiceOperations<WebSiteManagementClient>, IWebHostingPlanOperations
{
/// <summary>
/// Initializes a new instance of the WebHostingPlanOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal WebHostingPlanOperations(WebSiteManagementClient client)
{
this._client = client;
}
private WebSiteManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.WebSites.WebSiteManagementClient.
/// </summary>
public WebSiteManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates a new Web Hosting Plan or updates an existing one. (see
/// http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
/// for more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Server Farm operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Create Web Hosting Plan operation response.
/// </returns>
public async Task<WebHostingPlanCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, WebHostingPlanCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.WebHostingPlan == null)
{
throw new ArgumentNullException("parameters.WebHostingPlan");
}
if (parameters.WebHostingPlan.Location == null)
{
throw new ArgumentNullException("parameters.WebHostingPlan.Location");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Web/serverFarms/" + parameters.WebHostingPlan.Name.Trim() + "?";
url = url + "api-version=2014-06-01";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject webHostingPlanCreateOrUpdateParametersValue = new JObject();
requestDoc = webHostingPlanCreateOrUpdateParametersValue;
if (parameters.WebHostingPlan.Properties != null)
{
JObject propertiesValue = new JObject();
webHostingPlanCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["sku"] = parameters.WebHostingPlan.Properties.Sku.ToString();
propertiesValue["numberOfWorkers"] = parameters.WebHostingPlan.Properties.NumberOfWorkers;
propertiesValue["workerSize"] = parameters.WebHostingPlan.Properties.WorkerSize.ToString();
if (parameters.WebHostingPlan.Properties.AdminSiteName != null)
{
propertiesValue["adminSiteName"] = parameters.WebHostingPlan.Properties.AdminSiteName;
}
}
if (parameters.WebHostingPlan.Id != null)
{
webHostingPlanCreateOrUpdateParametersValue["id"] = parameters.WebHostingPlan.Id;
}
if (parameters.WebHostingPlan.Name != null)
{
webHostingPlanCreateOrUpdateParametersValue["name"] = parameters.WebHostingPlan.Name;
}
webHostingPlanCreateOrUpdateParametersValue["location"] = parameters.WebHostingPlan.Location;
if (parameters.WebHostingPlan.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.WebHostingPlan.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
webHostingPlanCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
if (parameters.WebHostingPlan.Type != null)
{
webHostingPlanCreateOrUpdateParametersValue["type"] = parameters.WebHostingPlan.Type;
}
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
WebHostingPlanCreateOrUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new WebHostingPlanCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
JToken serverFarmValue = responseDoc["ServerFarm"];
if (serverFarmValue != null && serverFarmValue.Type != JTokenType.Null)
{
WebHostingPlanCreateOrUpdateResponse serverFarmInstance = new WebHostingPlanCreateOrUpdateResponse();
WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
result.WebHostingPlan = webHostingPlanInstance;
JToken propertiesValue2 = serverFarmValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
WebHostingPlanProperties propertiesInstance = new WebHostingPlanProperties();
webHostingPlanInstance.Properties = propertiesInstance;
JToken skuValue = propertiesValue2["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
SkuOptions skuInstance = ((SkuOptions)Enum.Parse(typeof(SkuOptions), ((string)skuValue), true));
propertiesInstance.Sku = skuInstance;
}
JToken numberOfWorkersValue = propertiesValue2["numberOfWorkers"];
if (numberOfWorkersValue != null && numberOfWorkersValue.Type != JTokenType.Null)
{
int numberOfWorkersInstance = ((int)numberOfWorkersValue);
propertiesInstance.NumberOfWorkers = numberOfWorkersInstance;
}
JToken workerSizeValue = propertiesValue2["workerSize"];
if (workerSizeValue != null && workerSizeValue.Type != JTokenType.Null)
{
WorkerSizeOptions workerSizeInstance = ((WorkerSizeOptions)Enum.Parse(typeof(WorkerSizeOptions), ((string)workerSizeValue), true));
propertiesInstance.WorkerSize = workerSizeInstance;
}
JToken adminSiteNameValue = propertiesValue2["adminSiteName"];
if (adminSiteNameValue != null && adminSiteNameValue.Type != JTokenType.Null)
{
string adminSiteNameInstance = ((string)adminSiteNameValue);
propertiesInstance.AdminSiteName = adminSiteNameInstance;
}
}
JToken idValue = serverFarmValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
webHostingPlanInstance.Id = idInstance;
}
JToken nameValue = serverFarmValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
webHostingPlanInstance.Name = nameInstance;
}
JToken locationValue = serverFarmValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
webHostingPlanInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)serverFarmValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
webHostingPlanInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken typeValue = serverFarmValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
webHostingPlanInstance.Type = typeInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a Web Hosting Plan (see
/// http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
/// for more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='webHostingPlanName'>
/// Required. The name of the Web Hosting Plan to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> DeleteAsync(string resourceGroupName, string webHostingPlanName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (webHostingPlanName == null)
{
throw new ArgumentNullException("webHostingPlanName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webHostingPlanName", webHostingPlanName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Web/serverFarms/" + webHostingPlanName.Trim() + "?";
url = url + "api-version=2014-06-01";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets details of an existing Web Hosting Plan (see
/// http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
/// for more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='webHostingPlanName'>
/// Required. The name of the Web Hosting Plan.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Web Hosting Plan operation response.
/// </returns>
public async Task<WebHostingPlanGetResponse> GetAsync(string resourceGroupName, string webHostingPlanName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (webHostingPlanName == null)
{
throw new ArgumentNullException("webHostingPlanName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webHostingPlanName", webHostingPlanName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Web/serverFarms/" + webHostingPlanName.Trim() + "?";
url = url + "api-version=2014-06-01";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
WebHostingPlanGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new WebHostingPlanGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
result.WebHostingPlan = webHostingPlanInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
WebHostingPlanProperties propertiesInstance = new WebHostingPlanProperties();
webHostingPlanInstance.Properties = propertiesInstance;
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
SkuOptions skuInstance = ((SkuOptions)Enum.Parse(typeof(SkuOptions), ((string)skuValue), true));
propertiesInstance.Sku = skuInstance;
}
JToken numberOfWorkersValue = propertiesValue["numberOfWorkers"];
if (numberOfWorkersValue != null && numberOfWorkersValue.Type != JTokenType.Null)
{
int numberOfWorkersInstance = ((int)numberOfWorkersValue);
propertiesInstance.NumberOfWorkers = numberOfWorkersInstance;
}
JToken workerSizeValue = propertiesValue["workerSize"];
if (workerSizeValue != null && workerSizeValue.Type != JTokenType.Null)
{
WorkerSizeOptions workerSizeInstance = ((WorkerSizeOptions)Enum.Parse(typeof(WorkerSizeOptions), ((string)workerSizeValue), true));
propertiesInstance.WorkerSize = workerSizeInstance;
}
JToken adminSiteNameValue = propertiesValue["adminSiteName"];
if (adminSiteNameValue != null && adminSiteNameValue.Type != JTokenType.Null)
{
string adminSiteNameInstance = ((string)adminSiteNameValue);
propertiesInstance.AdminSiteName = adminSiteNameInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
webHostingPlanInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
webHostingPlanInstance.Name = nameInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
webHostingPlanInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
webHostingPlanInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
webHostingPlanInstance.Type = typeInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// You can retrieve historical usage metrics for a site by issuing an
/// HTTP GET request. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx
/// for more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='webHostingPlanName'>
/// Required. The name of the web hosting plan.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Get Historical Usage Metrics
/// Web hosting plan operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Historical Usage Metrics Web hosting plan operation
/// response.
/// </returns>
public async Task<WebHostingPlanGetHistoricalUsageMetricsResponse> GetHistoricalUsageMetricsAsync(string resourceGroupName, string webHostingPlanName, WebHostingPlanGetHistoricalUsageMetricsParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (webHostingPlanName == null)
{
throw new ArgumentNullException("webHostingPlanName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webHostingPlanName", webHostingPlanName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "GetHistoricalUsageMetricsAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Web/serverFarms/" + webHostingPlanName.Trim() + "/metrics?";
url = url + "api-version=2014-06-01";
if (parameters.MetricNames != null && parameters.MetricNames.Count > 0)
{
url = url + "&names=" + Uri.EscapeDataString(string.Join(",", parameters.MetricNames));
}
if (parameters.StartTime != null)
{
url = url + "&StartTime=" + Uri.EscapeDataString(string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.StartTime.Value.ToUniversalTime()));
}
if (parameters.EndTime != null)
{
url = url + "&EndTime=" + Uri.EscapeDataString(string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.EndTime.Value.ToUniversalTime()));
}
if (parameters.TimeGrain != null)
{
url = url + "&timeGrain=" + Uri.EscapeDataString(parameters.TimeGrain != null ? parameters.TimeGrain.Trim() : "");
}
url = url + "&details=" + Uri.EscapeDataString(parameters.IncludeInstanceBreakdown.ToString().ToLower());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
WebHostingPlanGetHistoricalUsageMetricsResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new WebHostingPlanGetHistoricalUsageMetricsResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken propertiesArray = responseDoc["properties"];
if (propertiesArray != null && propertiesArray.Type != JTokenType.Null)
{
foreach (JToken propertiesValue in ((JArray)propertiesArray))
{
HistoricalUsageMetric historicalUsageMetricInstance = new HistoricalUsageMetric();
result.UsageMetrics.Add(historicalUsageMetricInstance);
JToken codeValue = propertiesValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
historicalUsageMetricInstance.Code = codeInstance;
}
JToken dataValue = propertiesValue["data"];
if (dataValue != null && dataValue.Type != JTokenType.Null)
{
HistoricalUsageMetricData dataInstance = new HistoricalUsageMetricData();
historicalUsageMetricInstance.Data = dataInstance;
JToken displayNameValue = dataValue["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
dataInstance.DisplayName = displayNameInstance;
}
JToken endTimeValue = dataValue["EndTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTime endTimeInstance = ((DateTime)endTimeValue);
dataInstance.EndTime = endTimeInstance;
}
JToken nameValue = dataValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataInstance.Name = nameInstance;
}
JToken primaryAggregationTypeValue = dataValue["primaryAggregationType"];
if (primaryAggregationTypeValue != null && primaryAggregationTypeValue.Type != JTokenType.Null)
{
string primaryAggregationTypeInstance = ((string)primaryAggregationTypeValue);
dataInstance.PrimaryAggregationType = primaryAggregationTypeInstance;
}
JToken startTimeValue = dataValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
dataInstance.StartTime = startTimeInstance;
}
JToken timeGrainValue = dataValue["timeGrain"];
if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
{
string timeGrainInstance = ((string)timeGrainValue);
dataInstance.TimeGrain = timeGrainInstance;
}
JToken unitValue = dataValue["unit"];
if (unitValue != null && unitValue.Type != JTokenType.Null)
{
string unitInstance = ((string)unitValue);
dataInstance.Unit = unitInstance;
}
JToken valuesArray = dataValue["values"];
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
HistoricalUsageMetricSample metricSampleInstance = new HistoricalUsageMetricSample();
dataInstance.Values.Add(metricSampleInstance);
JToken countValue = valuesValue["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
int countInstance = ((int)countValue);
metricSampleInstance.Count = countInstance;
}
JToken maximumValue = valuesValue["maximum"];
if (maximumValue != null && maximumValue.Type != JTokenType.Null)
{
string maximumInstance = ((string)maximumValue);
metricSampleInstance.Maximum = maximumInstance;
}
JToken minimumValue = valuesValue["minimum"];
if (minimumValue != null && minimumValue.Type != JTokenType.Null)
{
string minimumInstance = ((string)minimumValue);
metricSampleInstance.Minimum = minimumInstance;
}
JToken timeCreatedValue = valuesValue["timeCreated"];
if (timeCreatedValue != null && timeCreatedValue.Type != JTokenType.Null)
{
DateTime timeCreatedInstance = ((DateTime)timeCreatedValue);
metricSampleInstance.TimeCreated = timeCreatedInstance;
}
JToken totalValue = valuesValue["total"];
if (totalValue != null && totalValue.Type != JTokenType.Null)
{
string totalInstance = ((string)totalValue);
metricSampleInstance.Total = totalInstance;
}
JToken instanceNameValue = valuesValue["instanceName"];
if (instanceNameValue != null && instanceNameValue.Type != JTokenType.Null)
{
string instanceNameInstance = ((string)instanceNameValue);
metricSampleInstance.InstanceName = instanceNameInstance;
}
}
}
}
JToken messageValue = propertiesValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
historicalUsageMetricInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets all Web Hosting Plans in a current subscription and Resource
/// Group. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx
/// for more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Web Hosting Plans operation response.
/// </returns>
public async Task<WebHostingPlanListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Web/serverFarms?";
url = url + "api-version=2014-06-01";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
WebHostingPlanListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new WebHostingPlanListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
result.WebHostingPlans.Add(webHostingPlanInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
WebHostingPlanProperties propertiesInstance = new WebHostingPlanProperties();
webHostingPlanInstance.Properties = propertiesInstance;
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
SkuOptions skuInstance = ((SkuOptions)Enum.Parse(typeof(SkuOptions), ((string)skuValue), true));
propertiesInstance.Sku = skuInstance;
}
JToken numberOfWorkersValue = propertiesValue["numberOfWorkers"];
if (numberOfWorkersValue != null && numberOfWorkersValue.Type != JTokenType.Null)
{
int numberOfWorkersInstance = ((int)numberOfWorkersValue);
propertiesInstance.NumberOfWorkers = numberOfWorkersInstance;
}
JToken workerSizeValue = propertiesValue["workerSize"];
if (workerSizeValue != null && workerSizeValue.Type != JTokenType.Null)
{
WorkerSizeOptions workerSizeInstance = ((WorkerSizeOptions)Enum.Parse(typeof(WorkerSizeOptions), ((string)workerSizeValue), true));
propertiesInstance.WorkerSize = workerSizeInstance;
}
JToken adminSiteNameValue = propertiesValue["adminSiteName"];
if (adminSiteNameValue != null && adminSiteNameValue.Type != JTokenType.Null)
{
string adminSiteNameInstance = ((string)adminSiteNameValue);
propertiesInstance.AdminSiteName = adminSiteNameInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
webHostingPlanInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
webHostingPlanInstance.Name = nameInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
webHostingPlanInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
webHostingPlanInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
webHostingPlanInstance.Type = typeInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
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
*/
#endregion
using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using Axiom.Configuration;
using Axiom.Core;
using Axiom.Input;
using Axiom.Overlays;
using Axiom.MathLib;
using Axiom.Graphics;
using Axiom.Utility;
using MouseButtons = Axiom.Input.MouseButtons;
namespace Axiom.Utility {
/// <summary>
/// Base class for Axiom examples.
/// </summary>
public abstract class TechDemo : IDisposable {
// Create a logger for use in this class
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(TechDemo));
#region Protected Fields
protected Root engine;
protected Camera camera;
protected Viewport viewport;
protected SceneManager scene;
protected RenderWindow window;
protected InputReader input;
protected Vector3 cameraVector = Vector3.Zero;
protected float cameraScale;
protected bool showDebugOverlay = true;
protected float statDelay = 0.0f;
protected float debugTextDelay = 0.0f;
protected float toggleDelay = 0.0f;
protected Vector3 camVelocity = Vector3.Zero;
protected Vector3 camAccel = Vector3.Zero;
protected float camSpeed = 2.5f;
protected int aniso = 1;
protected TextureFiltering filtering = TextureFiltering.Bilinear;
#endregion Protected Fields
#region Protected Methods
protected bool Configure() {
// HACK: Temporary
RenderSystem renderSystem = Root.Instance.RenderSystems[0];
Root.Instance.RenderSystem = renderSystem;
DisplayMode mode = renderSystem.ConfigOptions.FullscreenModes[0];
//mode.FullScreen = true;
renderSystem.ConfigOptions.SelectMode(mode.Width, mode.Height, mode.Depth, mode.Fullscreen);
window = Root.Instance.Initialize(true, "Axiom Engine Window");
ShowDebugOverlay(showDebugOverlay);
return true;
}
protected virtual void CreateCamera() {
// create a camera and initialize its position
camera = scene.CreateCamera("MainCamera");
camera.Position = new Vector3(0, 0, 500);
camera.LookAt(new Vector3(0, 0, -300));
// set the near clipping plane to be very close
camera.Near = 5;
}
/// <summary>
/// Shows the debug overlay, which displays performance statistics.
/// </summary>
protected void ShowDebugOverlay(bool show) {
// gets a reference to the default overlay
Overlay o = OverlayManager.Instance.GetByName("Core/DebugOverlay");
if(o == null) {
throw new Exception(string.Format("Could not find overlay named '{0}'.", "Core/DebugOverlay"));
}
if(show) {
o.Show();
}
else {
o.Hide();
}
}
protected void TakeScreenshot(string fileName) {
window.Save(fileName);
}
#endregion Protected Methods
#region Protected Virtual Methods
protected virtual void ChooseSceneManager() {
// Get the SceneManager, a generic one by default
scene = engine.SceneManagers.GetSceneManager(SceneType.Generic);
}
protected virtual void CreateViewports() {
Debug.Assert(window != null, "Attempting to use a null RenderWindow.");
// create a new viewport and set it's background color
viewport = window.AddViewport(camera, 0, 0, 1.0f, 1.0f, 100);
viewport.BackgroundColor = ColorEx.Black;
}
protected virtual bool Setup() {
// instantiate the Root singleton
engine = new Root("EngineConfig.xml", "AxiomEngine.log");
// add event handlers for frame events
engine.FrameStarted += new FrameEvent(OnFrameStarted);
engine.FrameEnded += new FrameEvent(OnFrameEnded);
// allow for setting up resource gathering
SetupResources();
//show the config dialog and collect options
if(!Configure()) {
// shutting right back down
engine.Shutdown();
return false;
}
ChooseSceneManager();
CreateCamera();
CreateViewports();
// set default mipmap level
TextureManager.Instance.DefaultNumMipMaps = 5;
// call the overridden CreateScene method
CreateScene();
// retreive and initialize the input system
input = PlatformManager.Instance.CreateInputReader();
input.Initialize(window, true, true, false, false, false);
return true;
}
/// <summary>
/// Loads default resource configuration if one exists.
/// </summary>
protected virtual void SetupResources() {
}
#endregion Protected Virtual Methods
#region Protected Abstract Methods
/// <summary>
///
/// </summary>
protected abstract void CreateScene();
#endregion Protected Abstract Methods
#region Public Methods
public virtual void Start() {
try {
if (Setup()) {
// start the engines rendering loop
engine.StartRendering();
}
}
catch (Exception ex) {
// try logging the error here first, before Root is disposed of
if (log != null)
log.Error(ex.Message);
throw;
}
}
public virtual void Dispose() {
if(engine != null) {
// remove event handlers
engine.FrameStarted -= new FrameEvent(OnFrameStarted);
engine.FrameEnded -= new FrameEvent(OnFrameEnded);
engine.Dispose();
}
}
#endregion Public Methods
#region Event Handlers
protected virtual void OnFrameEnded(Object source, FrameEventArgs e) {
}
private static TimingMeter onFrameStartedMeter = MeterManager.GetMeter("TechDemo OnFrameStarted", "TechDemo");
protected virtual void OnFrameStarted(Object source, FrameEventArgs e) {
onFrameStartedMeter.Enter();
float scaleMove = 200 * e.TimeSinceLastFrame;
// reset acceleration zero
camAccel = Vector3.Zero;
// set the scaling of camera motion
cameraScale = 100 * e.TimeSinceLastFrame;
// TODO: Move this into an event queueing mechanism that is processed every frame
input.Capture();
if(input.IsKeyPressed(KeyCodes.Escape)) {
Root.Instance.QueueEndRendering();
onFrameStartedMeter.Exit();
return;
}
if(input.IsKeyPressed(KeyCodes.A)) {
camAccel.x = -0.5f;
}
if(input.IsKeyPressed(KeyCodes.D)) {
camAccel.x = 0.5f;
}
if(input.IsKeyPressed(KeyCodes.W)) {
camAccel.z = -1.0f;
}
if(input.IsKeyPressed(KeyCodes.S)) {
camAccel.z = 1.0f;
}
camAccel.y += (float)(input.RelativeMouseZ * 0.1f);
if(input.IsKeyPressed(KeyCodes.Left)) {
camera.Yaw(cameraScale);
}
if(input.IsKeyPressed(KeyCodes.Right)) {
camera.Yaw(-cameraScale);
}
if(input.IsKeyPressed(KeyCodes.Up)) {
camera.Pitch(cameraScale);
}
if(input.IsKeyPressed(KeyCodes.Down)) {
camera.Pitch(-cameraScale);
}
// subtract the time since last frame to delay specific key presses
toggleDelay -= e.TimeSinceLastFrame;
// toggle rendering mode
if(input.IsKeyPressed(KeyCodes.R) && toggleDelay < 0) {
if(camera.SceneDetail == SceneDetailLevel.Points) {
camera.SceneDetail = SceneDetailLevel.Solid;
}
else if(camera.SceneDetail == SceneDetailLevel.Solid) {
camera.SceneDetail = SceneDetailLevel.Wireframe;
}
else {
camera.SceneDetail = SceneDetailLevel.Points;
}
log.InfoFormat("Rendering mode changed to '{0}'.", camera.SceneDetail);
toggleDelay = 1;
}
if(input.IsKeyPressed(KeyCodes.T) && toggleDelay < 0) {
// toggle the texture settings
switch(filtering) {
case TextureFiltering.Bilinear:
filtering = TextureFiltering.Trilinear;
aniso = 1;
break;
case TextureFiltering.Trilinear:
filtering = TextureFiltering.Anisotropic;
aniso = 8;
break;
case TextureFiltering.Anisotropic:
filtering = TextureFiltering.Bilinear;
aniso = 1;
break;
}
log.InfoFormat("Texture Filtering changed to '{0}'.", filtering);
// set the new default
MaterialManager.Instance.SetDefaultTextureFiltering(filtering);
MaterialManager.Instance.DefaultAnisotropy = aniso;
toggleDelay = 1;
}
if(input.IsKeyPressed(KeyCodes.P)) {
string[] temp = Directory.GetFiles(Environment.CurrentDirectory, "screenshot*.jpg");
string fileName = string.Format("screenshot{0}.jpg", temp.Length + 1);
TakeScreenshot(fileName);
// show briefly on the screen
window.DebugText = string.Format("Wrote screenshot '{0}'.", fileName);
// show for 2 seconds
debugTextDelay = 2.0f;
}
if(input.IsKeyPressed(KeyCodes.B)) {
scene.ShowBoundingBoxes = !scene.ShowBoundingBoxes;
}
if(input.IsKeyPressed(KeyCodes.F)) {
// hide all overlays, includes ones besides the debug overlay
viewport.OverlaysEnabled = !viewport.OverlaysEnabled;
}
if(!input.IsMousePressed(MouseButtons.Left)) {
float cameraYaw = -input.RelativeMouseX * .13f;
float cameraPitch = -input.RelativeMouseY * .13f;
camera.Yaw(cameraYaw);
camera.Pitch(cameraPitch);
}
else {
cameraVector.x += input.RelativeMouseX * 0.13f;
}
camVelocity += (camAccel * scaleMove * camSpeed);
// move the camera based on the accumulated movement vector
camera.MoveRelative(camVelocity * e.TimeSinceLastFrame);
// Now dampen the Velocity - only if user is not accelerating
if (camAccel == Vector3.Zero) {
camVelocity *= (1 - (6 * e.TimeSinceLastFrame));
}
// update performance stats once per second
if(statDelay < 0.0f && showDebugOverlay) {
UpdateStats();
statDelay = 1.0f;
}
else {
statDelay -= e.TimeSinceLastFrame;
}
// turn off debug text when delay ends
if(debugTextDelay < 0.0f) {
debugTextDelay = 0.0f;
window.DebugText = "";
}
else if(debugTextDelay > 0.0f) {
debugTextDelay -= e.TimeSinceLastFrame;
}
OverlayElement element = OverlayElementManager.Instance.GetElement("Core/DebugText");
element.Text = window.DebugText;
onFrameStartedMeter.Exit();
}
protected void UpdateStats() {
// TODO: Replace with CEGUI
OverlayElement element = OverlayElementManager.Instance.GetElement("Core/CurrFps");
element.Text = string.Format("Current FPS: {0}", Root.Instance.CurrentFPS);
element = OverlayElementManager.Instance.GetElement("Core/BestFps");
element.Text = string.Format("Best FPS: {0}", Root.Instance.BestFPS);
element = OverlayElementManager.Instance.GetElement("Core/WorstFps");
element.Text = string.Format("Worst FPS: {0}", Root.Instance.WorstFPS);
element = OverlayElementManager.Instance.GetElement("Core/AverageFps");
element.Text = string.Format("Average FPS: {0}", Root.Instance.AverageFPS);
element = OverlayElementManager.Instance.GetElement("Core/NumTris");
element.Text = string.Format("Triangle Count: {0}", scene.TargetRenderSystem.FacesRendered);
}
#endregion Event Handlers
}
}
| |
// 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.Text;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
namespace System.Buffers.Text.Tests
{
internal static partial class TestData
{
public static IEnumerable<ParserTestData<TimeSpan>> TimeSpanParserTestData
{
get
{
foreach (ParserTestData<TimeSpan> testData in GeneratedParserTestDataUsingParseExact<TimeSpan>('G', TimeSpanParserBigGTestData.Concat(TimeSpanCombinatorialData), TimeSpan.TryParseExact))
{
yield return testData;
}
foreach (ParserTestData<TimeSpan> testData in GeneratedParserTestDataUsingParseExact<TimeSpan>('g', TimeSpanParserLittleGTestData.Concat(TimeSpanCombinatorialData), TimeSpan.TryParseExact))
{
yield return testData;
}
foreach (ParserTestData<TimeSpan> testData in GeneratedParserTestDataUsingParseExact<TimeSpan>('c', TimeSpanParserCTestData.Concat(TimeSpanCombinatorialData), TimeSpan.TryParseExact))
{
yield return testData;
}
}
}
//
// Generate sequences of numbers separated by various combinations of periods and colons.
//
private static IEnumerable<string> TimeSpanCombinatorialData
{
get
{
for (int numComponents = 1; numComponents <= 6; numComponents++)
{
for (int separatorMask = 0; separatorMask < (1 << (numComponents - 1)); separatorMask++)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numComponents; i++)
{
sb.Append((20 + i).ToString("D", CultureInfo.InvariantCulture));
if (i != numComponents - 1)
{
char separator = ((separatorMask & (1 << i)) != 0) ? '.' : ':';
sb.Append(separator);
}
}
yield return sb.ToString();
}
}
}
}
private static IEnumerable<string> TimeSpanParserBigGTestData
{
get
{
yield return "1:02:03:04.5678912";
// Leading space (allowed)
yield return " 1:02:03:04.5678912";
yield return " 1:02:03:04.5678912";
yield return " \t 1:02:03:04.5678912";
// Sign (only '-' allowed at start)
yield return "-1:02:03:04.5678912";
yield return "+1:02:03:04.5678912";
yield return "1:-02:03:04.5678912";
yield return "1:+02:03:04.5678912";
yield return "1:02:-03:04.5678912";
yield return "1:02:+03:04.5678912";
yield return "1:02:03:-04.5678912";
yield return "1:02:03:+04.5678912";
yield return "1:02:03:04.-5678912";
yield return "1:02:03:04.+5678912";
// Random bad stuff
yield return "";
yield return "-";
yield return "10675199:02:48:05.4775807"; // TimeSpan.MaxValue
yield return "10675199:02:48:05.4775808"; // TimeSpan.MaxValue + 1
yield return "10675199:02:48:06.0000000"; // (next non-fractional overflow)
yield return "-10675199:02:48:05.4775808"; // TimeSpan.MinValue
yield return "-10675199:02:48:05.4775809"; // TimeSpan.MinValue - 1
yield return "-10675199:02:48:06.0000000"; // (next non-fractional underflow)
// Individual ranges
yield return "0:0:0:0.0000000";
yield return "0:23:0:0.0000000";
yield return "0:24:0:0.0000000";
yield return "0:0:59:0.0000000";
yield return "0:0:60:0.0000000";
yield return "0:0:0:59.0000000";
yield return "0:0:0:60.0000000";
yield return "0:0:0:0.9999999";
yield return "0:0:0:0.10000000";
yield return "-0:0:0:0.0000000";
yield return "-0:23:0:0.0000000";
yield return "-0:24:0:0.0000000";
yield return "-0:0:59:0.0000000";
yield return "-0:0:60:0.0000000";
yield return "-0:0:0:59.0000000";
yield return "-0:0:0:60.0000000";
yield return "-0:0:0:0.9999999";
yield return "-0:0:0:0.10000000";
// Padding
yield return "000001:0000002:000003:0000004.0000000";
yield return "0:0:0:0."; // Not allowed
yield return "0:0:0:0.1";
yield return "0:0:0:0.12";
yield return "0:0:0:0.123";
yield return "0:0:0:0.1234";
yield return "0:0:0:0.12345";
yield return "0:0:0:0.123456";
yield return "0:0:0:0.1234567";
// Not allowed (picky, picky)
yield return "0:0:0:0.12345670";
// Missing components (none allowed: 'G' is strict)
yield return "1";
yield return "1:";
yield return "1:2";
yield return "1:2:";
yield return "1:2:3";
yield return "1:2:3:";
yield return "1:2:3:4";
yield return "1:2:3:4.";
}
}
private static IEnumerable<string> TimeSpanParserLittleGTestData
{
get
{
// All BigG strings are valid LittleG Strings so reuse that data.
foreach (string bigG in TimeSpanParserBigGTestData)
{
yield return bigG;
}
yield return "1"; // 1-component -> day
yield return "1.9999999"; // illegal
yield return "4294967295"; // 1-component overflow
yield return "1:2"; // 2-component -> hour:minutes
yield return "1:2.9999999"; //illegal
yield return "1:4294967295"; // 2-component overflow
yield return "1:2:3"; // 3-component -> hour:minutes:seconds[.fraction]
yield return "1:2:3.9999999"; // 3-component -> hour:minutes:seconds[.fraction]
yield return "1:2:3.$$$$$$$"; //illegal
yield return "1:2:4294967295"; // 3-component overflow
yield return "1:2:4294967295.9999999"; // 4-component overflow
yield return "1:2:3:4"; // 4-component -> day:hour:minutes:seconds[.fraction]
yield return "1:2:3:4.9999999"; // 4-component -> day:hour:minutes:seconds[.fraction]
yield return "1:2:3:4.$$$$$$$"; //illegal
yield return "1:2:3:4294967295"; // 4-component overflow
yield return "1:2:3:4294967295.9999999"; // 4-component overflow
yield return "1:2:3:4:5"; // illegal - too many components
yield return "1:2:3:4:5.9999999"; // illegal - too many components
yield return "1:2:3:4.9999999:"; // intentionally flagged as error
yield return "1:2:3:4.9999999."; // intentionally flagged as error
}
}
private static IEnumerable<string> TimeSpanParserCTestData
{
get
{
yield return "1";
yield return "1.9999999";
yield return "4294967295";
yield return "1:2";
yield return "1:2.9999999";
yield return "1:4294967295";
yield return "1:2:3";
yield return "1.2:3";
yield return "1.2:3:4";
yield return "1:2:3.9999999";
yield return "1:2:3.$$$$$$$";
yield return "1:2:4294967295";
yield return "1:2:4294967295.9999999";
yield return "1:2:3:4";
yield return "1:2:3:4.9999999";
yield return "1:2:3:4.$$$$$$$";
yield return "1:2:3:4294967295";
yield return "1:2:3:4294967295.9999999";
yield return "1.2:3:4.9999999";
yield return "1.2:3:4.$$$$$$$";
yield return "1.2:3:4294967295";
yield return "1.2:3:4294967295.9999999";
yield return "1.2:3:4:5";
yield return "1.2:3:4:5.9999999";
yield return "1.2:3:4.9999999:";
yield return "1.2:3:4.9999999.";
yield return " \t 1"; // Leading whitespace is allowed
yield return "-"; // Illegal
yield return "+"; // Illegal
yield return "-1"; // Legal
yield return "+1"; // Illegal
}
}
}
}
| |
using UnityEngine;
/// <summary>
/// This class provides functions for generating curved meshes around a Spline.
/// </summary>
/// <remarks>
/// This class enables you to dynamically generate curved meshes like streets, rivers, tubes, ropes, tunnels, etc.
/// </remarks>
[ExecuteInEditMode]
[RequireComponent(typeof(MeshFilter))]
[AddComponentMenu("SuperSplines/Spline Mesh")]
public class SplineMesh : MonoBehaviour
{
public Spline spline; ///< Reference to the spline that defines the path.
public UpdateMode updateMode = UpdateMode.DontUpdate; ///< Specifies when the spline mesh will be updated.
public int deltaFrames = 1; ///< The number of frames that need to pass before the mesh will be updated again. (for UpdateMode.EveryXFrames)
public float deltaTime = 0.1f; ///< The amount of time that needs to pass before the mesh will be updated again. (for UpdateMode.EveryXSeconds)
private int updateFrame = 0;
private float updateTime = 0f;
public Mesh startBaseMesh; ///< Reference to the base mesh that will be created around the spline.
public Mesh baseMesh; ///< Reference to the main base mesh that will be created around the spline
public Mesh endBaseMesh; ///< Reference to the base mesh that will be created around the spline.
public int segmentCount = 50; ///< Number of segments (base meshes) stringed together per generated mesh.
public UVMode uvMode = UVMode.InterpolateV; ///< Defines how UV coordinates will be calculated.
public Vector2 uvScale = Vector2.one; ///< Affects the scale of texture coordinates on the streched mesh
public Vector2 xyScale = Vector2.one; ///< Mesh scale in the local directions around the spline.
public bool highAccuracy = false; ///< If set to true, the component will sample the spline for every vertex seperately
public SplitMode splitMode = SplitMode.DontSplit; ///< Defines if and specifies which individual parts of the spline will exclusively be used for mesh generation.
public float segmentStart = 0; ///< Index of the spline segment that will be used as control path.
public float segmentEnd = 1; ///< Index of the spline segment that will be used as control path.
public int splineSegment = 0; ///< Index of the spline segment that will be used as control path.
private MeshData meshDataStart;// = new MeshData( null );
private MeshData meshDataBase;// = new MeshData( null );
private MeshData meshDataEnd;//= new MeshData( null );
private MeshData meshDataNew;
private Mesh bentMesh = null;
public Mesh BentMesh{ get{ return ReturnMeshReference( ); } } ///< Returns a reference to the generated mesh.
public bool IsSubSegment{ get{ return (splineSegment != -1); } } /// Returns true if the component only computes a part of the whole spline mesh.
void Start( )
{
if( spline != null )
spline.UpdateSpline( );
UpdateMesh( );
}
void OnEnable( )
{
if( spline != null )
spline.UpdateSpline( );
UpdateMesh( );
}
void LateUpdate( )
{
switch( updateMode )
{
case UpdateMode.DontUpdate:
break;
case UpdateMode.EveryXFrames:
if( Time.frameCount % deltaFrames == 0 )
goto case UpdateMode.EveryFrame;
break;
case UpdateMode.EveryXSeconds:
if( deltaTime < Time.realtimeSinceStartup - updateTime )
{
updateTime = Time.realtimeSinceStartup;
goto case UpdateMode.EveryFrame;
}
break;
case UpdateMode.WhenSplineChanged:
if( updateFrame != spline.UpdateFrame )
{
updateFrame = spline.UpdateFrame;
goto case UpdateMode.EveryFrame;
}
break;
case UpdateMode.EveryFrame:
UpdateMesh( );
break;
}
}
/// <summary>
/// This function updates the spline mesh. It is called automatically once in a while, if updateMode isn't set to DontUpdate.
/// </summary>
public void UpdateMesh( )
{
SetupMesh( );
bentMesh.Clear( );
if( baseMesh == null || spline == null || segmentCount <= 0 )
return;
SetupMeshBuffers( );
float startParam;
float endParam;
float deltaParam;
switch( splitMode )
{
case SplitMode.BySplineSegment:
SplineSegment[] splineSegments = spline.SplineSegments;
splineSegment = Mathf.Clamp( splineSegment, 0, splineSegments.Length-1 );
SplineSegment segment = splineSegments[splineSegment];
startParam = (float)segment.StartNode.Parameters[spline].position;
endParam = startParam + (float)segment.NormalizedLength;
break;
case SplitMode.BySplineParameter:
startParam = segmentStart;
endParam = segmentEnd;
break;
case SplitMode.DontSplit:
default:
startParam = 0;
endParam = 1;
break;
}
deltaParam = endParam - startParam;
float param0 = 0f;
float param1 = 0f;
SplineMeshModifier[] splineMeshModifiers = GetComponentsInChildren<SplineMeshModifier>( );
for( int segmentIdx = 0; segmentIdx < segmentCount; segmentIdx++ )
{
MeshData currentBaseMesh;
if( segmentIdx == 0 && startBaseMesh != null )
currentBaseMesh = meshDataStart;
else if( segmentIdx == segmentCount-1 && endBaseMesh != null )
currentBaseMesh = meshDataEnd;
else
currentBaseMesh = meshDataBase;
param0 = startParam + deltaParam * (float) (segmentIdx) / segmentCount;
param1 = startParam + deltaParam * (float) (segmentIdx+1) / segmentCount;
BendMesh( param0, param1, currentBaseMesh, meshDataNew, splineMeshModifiers );
}
meshDataNew.AssignToMesh( bentMesh );
}
private void BendMesh( float param0, float param1, MeshData meshDataBase, MeshData meshDataNew, SplineMeshModifier[] meshModiefiers )
{
float paramOffset = param1 - param0;
Vector3 targetPos;
Quaternion targetRot;
Vector3 pos0 = Vector3.zero;
Vector3 pos1 = Vector3.zero;
Quaternion rot0 = Quaternion.identity;
Quaternion rot1 = Quaternion.identity;
Quaternion inverseRotation = Quaternion.Inverse( spline.transform.rotation );
int firstVertexIndex = meshDataNew.currentVertexIndex;
if( !highAccuracy )
{
pos0 = spline.transform.InverseTransformPoint(spline.GetPositionOnSpline( param0 ));
pos1 = spline.transform.InverseTransformPoint(spline.GetPositionOnSpline( param1 ));
rot0 = spline.GetOrientationOnSpline( param0 ) * inverseRotation;
rot1 = spline.GetOrientationOnSpline( param1 ) * inverseRotation;
}
for( int i = 0; i < meshDataBase.VertexCount; i++, meshDataNew.currentVertexIndex++ )
{
Vector3 vertex = meshDataBase.vertices[i];
Vector2 uvCoord = meshDataBase.uvCoord[i];
float normalizedZPos = vertex.z + 0.5f;
float splineParam = param0 + paramOffset * normalizedZPos;
switch( uvMode )
{
case UVMode.InterpolateU:
uvCoord.x = splineParam;
break;
case UVMode.InterpolateV:
uvCoord.y = splineParam;
break;
}
uvCoord.x *= uvScale.x;
uvCoord.y *= uvScale.y;
if( highAccuracy )
{
targetRot = spline.GetOrientationOnSpline( splineParam ) * inverseRotation;
targetPos = spline.transform.InverseTransformPoint( spline.GetPositionOnSpline( splineParam ) );
}
else
{
targetRot = Quaternion.Lerp( rot0, rot1, normalizedZPos );
targetPos = new Vector3(
pos0.x + (pos1.x-pos0.x) * normalizedZPos,
pos0.y + (pos1.y-pos0.y) * normalizedZPos,
pos0.z + (pos1.z-pos0.z) * normalizedZPos );
}
vertex.x *= xyScale.x;
vertex.y *= xyScale.y;
vertex.z = 0;
foreach( SplineMeshModifier meshModifier in meshModiefiers )
vertex = meshModifier.ModifyVertex( this, vertex, splineParam );
meshDataNew.vertices[meshDataNew.currentVertexIndex] = FastRotation( targetRot, vertex ) + targetPos;
if( meshDataBase.HasNormals )
{
Vector3 normal = meshDataBase.normals[i];
foreach( SplineMeshModifier meshModifier in meshModiefiers )
normal = meshModifier.ModifyNormal( this, normal, splineParam );
meshDataNew.normals[meshDataNew.currentVertexIndex] = targetRot * normal;
}
if( meshDataBase.HasTangents )
{
Vector4 tangent = meshDataBase.tangents[i];
foreach( SplineMeshModifier meshModifier in meshModiefiers )
tangent = meshModifier.ModifyTangent( this, tangent, splineParam );
meshDataNew.tangents[meshDataNew.currentVertexIndex] = targetRot * tangent;
}
foreach( SplineMeshModifier meshModifier in meshModiefiers )
uvCoord = meshModifier.ModifyUV( this, uvCoord, splineParam );
meshDataNew.uvCoord[meshDataNew.currentVertexIndex] = uvCoord;
}
for( int i = 0; i < meshDataBase.TriangleCount; i++, meshDataNew.currentTriangleIndex++ )
meshDataNew.triangles[meshDataNew.currentTriangleIndex] = meshDataBase.triangles[i] + firstVertexIndex;
}
private Vector3 FastRotation( Quaternion rotation, Vector3 point )
{
float num = rotation.x * 2f;
float num2 = rotation.y * 2f;
float num3 = rotation.z * 2f;
float num4 = rotation.x * num;
float num5 = rotation.y * num2;
float num6 = rotation.z * num3;
float num7 = rotation.x * num2;
float num8 = rotation.x * num3;
float num9 = rotation.y * num3;
float num10 = rotation.w * num;
float num11 = rotation.w * num2;
float num12 = rotation.w * num3;
Vector3 result;
result.x = (1f - (num5 + num6)) * point.x + (num7 - num12) * point.y;
result.y = (num7 + num12) * point.x + (1f - (num4 + num6)) * point.y;
result.z = (num8 - num11) * point.x + (num9 + num10) * point.y;
return result;
}
private void SetupMesh( )
{
if( bentMesh == null )
{
bentMesh = new Mesh( );
bentMesh.name = "BentMesh";
bentMesh.hideFlags = HideFlags.HideAndDontSave;
}
MeshFilter meshFilter = GetComponent<MeshFilter>( );
if( meshFilter.sharedMesh != bentMesh )
meshFilter.sharedMesh = bentMesh;
MeshCollider meshCollider = GetComponent<MeshCollider>( );
if( meshCollider != null )
{
meshCollider.sharedMesh = null;
meshCollider.sharedMesh = bentMesh;
}
}
private void SetupMeshBuffers( )
{
if( meshDataStart == null ) meshDataStart = new MeshData( null );
if( meshDataBase == null ) meshDataBase = new MeshData( null );
if( meshDataEnd == null ) meshDataEnd = new MeshData( null );
if( meshDataNew == null ) meshDataNew = new MeshData( null );
if( !meshDataStart.ReferencesMesh( startBaseMesh ) )
meshDataStart = new MeshData( startBaseMesh );
if( !meshDataBase.ReferencesMesh( baseMesh ) )
meshDataBase = new MeshData( baseMesh );
if( !meshDataEnd.ReferencesMesh( endBaseMesh ) )
meshDataEnd = new MeshData( endBaseMesh );
MeshData[] capMeshes = new MeshData[] {meshDataStart, meshDataEnd};
int middleSegmentCount = segmentCount;
// if( IsSubSegment )
// {
// if( splineSegment != 0 )
// {
// capMeshes[0] = null;
// ++middleSegmentCount;
// }
//
// if( splineSegment != spline.SegmentCount - 1 )
// {
// capMeshes[1] = null;
// ++middleSegmentCount;
// }
// }
if( startBaseMesh != null )
--middleSegmentCount;
if( endBaseMesh != null )
--middleSegmentCount;
if( !meshDataNew.Suits( meshDataBase, middleSegmentCount, capMeshes ) )
meshDataNew = new MeshData( meshDataBase, middleSegmentCount, capMeshes );
else
meshDataNew.Reset( );
}
private Mesh ReturnMeshReference( )
{
return bentMesh;
}
private class MeshData
{
public Vector3[] vertices;
public Vector2[] uvCoord;
public Vector3[] normals;
public Vector4[] tangents;
public int[] triangles;
public Bounds bounds;
public int currentTriangleIndex;
public int currentVertexIndex;
public bool HasNormals;
public bool HasTangents;
public int VertexCount{ get{ return vertices.Length; } }
public int TriangleCount{ get{ return triangles.Length; } }
public Mesh referencedMesh = null;
public MeshData( Mesh mesh )
{
referencedMesh = mesh;
currentTriangleIndex = 0;
currentVertexIndex = 0;
if( mesh == null )
{
vertices = new Vector3[0];
normals = new Vector3[0];
tangents = new Vector4[0];
uvCoord = new Vector2[0];
triangles = new int[0];
bounds = new Bounds( Vector3.zero, Vector3.zero );
HasNormals = normals.Length > 0;
HasTangents = tangents.Length > 0;
return;
}
vertices = mesh.vertices;
normals = mesh.normals;
tangents = mesh.tangents;
uvCoord = mesh.uv;
triangles = mesh.triangles;
bounds = mesh.bounds;
HasNormals = normals.Length > 0;
HasTangents = tangents.Length > 0;
}
public MeshData( MeshData mData, int segmentCount, MeshData[] additionalMeshes )
{
int totalVertexCount = mData.vertices.Length * segmentCount;
int totalUVCount = mData.uvCoord.Length * segmentCount;
int totalNormalsCount = mData.normals.Length * segmentCount;
int totalTangentsCount = mData.tangents.Length * segmentCount;
int totalTrianglesCount = mData.triangles.Length * segmentCount;
foreach( MeshData meshData in additionalMeshes )
{
if( meshData == null )
continue;
totalVertexCount += meshData.vertices.Length;
totalUVCount += meshData.uvCoord.Length;
totalNormalsCount += meshData.normals.Length;
totalTangentsCount += meshData.tangents.Length;
totalTrianglesCount += meshData.triangles.Length;
}
vertices = new Vector3[totalVertexCount];
uvCoord = new Vector2[totalUVCount];
normals = new Vector3[totalNormalsCount];
tangents = new Vector4[totalTangentsCount];
triangles = new int[totalTrianglesCount];
HasNormals = normals.Length > 0;
HasTangents = tangents.Length > 0;
}
public bool Suits( MeshData mData, int segmentCount, MeshData[] additionalMeshes )
{
int totalVertexCount = mData.vertices.Length * segmentCount;
int totalUVCount = mData.uvCoord.Length * segmentCount;
int totalNormalsCount = mData.normals.Length * segmentCount;
int totalTangentsCount = mData.tangents.Length * segmentCount;
int totalTrianglesCount = mData.triangles.Length * segmentCount;
foreach( MeshData meshData in additionalMeshes )
{
if( meshData == null )
continue;
totalVertexCount += meshData.vertices.Length;
totalUVCount += meshData.uvCoord.Length;
totalNormalsCount += meshData.normals.Length;
totalTangentsCount += meshData.tangents.Length;
totalTrianglesCount += meshData.triangles.Length;
}
if( totalVertexCount != vertices.Length )
return false;
if( totalUVCount != uvCoord.Length )
return false;
if( totalNormalsCount != normals.Length )
return false;
if( totalTangentsCount != tangents.Length )
return false;
if( totalTrianglesCount != triangles.Length )
return false;
return true;
}
public bool ReferencesMesh( Mesh mesh )
{
return referencedMesh == mesh;
}
public void Reset( )
{
currentTriangleIndex = 0;
currentVertexIndex = 0;
}
public void AssignToMesh( Mesh mesh )
{
mesh.vertices = vertices;
mesh.uv = uvCoord;
if( HasNormals )
mesh.normals = normals;
if( HasTangents )
mesh.tangents = tangents;
mesh.triangles = triangles;
}
}
/// <summary>
/// Defines how the SplineMesh class will calculate UV-coordinates.
/// </summary>
public enum UVMode
{
InterpolateV, ///< UV coordinates will be interpolated on the V-axis
InterpolateU, ///< UV coordinates will be interpolated on the U-axis
DontInterpolate ///< UV coordinates will simply be copied from the base mesh and won't be altered.
}
/// <summary>
/// Defines if and specifies which individual parts of the spline will exclusively be used for mesh generation.
/// </summary>
public enum SplitMode
{
DontSplit,
BySplineSegment,
BySplineParameter
}
/// <summary>
/// Specifies when to update and recalculate an instance of SplineMesh.
/// </summary>
public enum UpdateMode
{
DontUpdate, ///< Keeps the spline static. It will only be updated when the component becomes enabled (OnEnable( )).
EveryFrame, ///< Updates the spline every frame.
EveryXFrames, ///< Updates the spline every x frames.
EveryXSeconds, ///< Updates the spline every x seconds.
WhenSplineChanged ///< Updates the spline mesh whenever its reference spline has been updated.
}
}
| |
using Codex.Import;
using Codex.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using NUnit.Framework;
using System;
using System.CodeDom.Compiler;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Codex.Analysis.Projects.BinLogProjectAnalyzer;
namespace Codex.Integration.Tests
{
[TestFixture]
class CodeGeneration
{
[Test]
public void GenerateAsync()
{
string binlogPath = @"E:\Code\Codex\msbuild.binlog";
AnalysisServices services = new AnalysisServices("test", new FileSystem());
var repo = services.CreateRepo("test");
SolutionInfoBuilder builder = new SolutionInfoBuilder(binlogPath, repo);
var solutionInfo = builder.Build(linkProjects: true);
var solution = builder.Workspace.AddSolution(solutionInfo);
}
public class GenerationContext : DiagnosticAnalyzer
{
public Solution Solution { get; init; }
public CodeGraph Graph { get; init; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray<DiagnosticDescriptor>.Empty;
public async Task GenerateAsync()
{
IEnumerable<IMethodSymbol> rootCallees = GetRootCallees();
IEnumerable<IMethodSymbol> topCallers = default;
// Collect call graphs for projects
foreach (var project in Solution.Projects)
{
CollectCallGraphAsync(project);
}
// Mark transitive closure from root callees
var rootCalleeClosure = Graph.Visit(rootCallees, dependencies: false);
// Mark transitive closure from top callers
var topCallerClosure = Graph.Visit(topCallers, dependencies: true);
// Intersect
rootCalleeClosure.IntersectWith(topCallerClosure);
var intersection = rootCalleeClosure;
// Make all impacted types partial
var impactedTypes = intersection.Select(m => m.ContainingType)
.ToHashSet<INamedTypeSymbol>(CodeGraph.SymbolComparer);
foreach (var type in impactedTypes)
{
MarkPartial(type);
}
// Asyncify all methods
foreach (var method in intersection)
{
CreateAsyncVariant(method);
}
}
private IEnumerable<IMethodSymbol> GetRootCallees()
{
var luceneNetProject = Solution.Projects.Where(p => p.AssemblyName == "Lucene.Net").First();
var compilation = luceneNetProject.GetCompilationAsync().GetAwaiter().GetResult();
var indexInput = compilation.GetTypeByMetadataName("Lucene.Net.Store.IndexInput");
throw new NotImplementedException();
}
private void CreateAsyncVariant(IMethodSymbol method)
{
throw new NotImplementedException();
}
private void MarkPartial(INamedTypeSymbol type)
{
throw new NotImplementedException();
}
public async Task CollectCallGraphAsync(Project project)
{
var compilation = (CSharpCompilation)await project.GetCompilationAsync();
var analysisCompilation = compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(this),
analysisOptions: new CompilationWithAnalyzersOptions(
new AnalyzerOptions(ImmutableArray<AdditionalText>.Empty),
null, true, true));
var result = await analysisCompilation.GetAnalysisResultAsync(CancellationToken.None);
}
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationBlockStartAction(OnOperationBlockStart);
context.RegisterOperationAction(OnOperation, OperationKind.MethodReference);
}
private void OnOperationBlockStart(OperationBlockStartAnalysisContext context)
{
if (context.OwningSymbol is IMethodSymbol method)
{
Graph.AddNode(method);
}
}
private void OnOperation(OperationAnalysisContext context)
{
if (context.ContainingSymbol is IMethodSymbol caller
&& context.Operation is IMethodReferenceOperation call)
{
Graph.AddEdge(caller, callee: call.Method);
}
}
}
public class CodeGraph
{
public static IEqualityComparer<ISymbol> SymbolComparer { get; } = EqualityComparer<ISymbol>.Default;
public ConcurrentDictionary<IMethodSymbol, HashSet<IMethodSymbol>> Dependents = new(SymbolComparer);
public ConcurrentDictionary<IMethodSymbol, HashSet<IMethodSymbol>> Dependencies = new(SymbolComparer);
public ConcurrentDictionary<IMethodSymbol, HashSet<IMethodSymbol>> Overrides = new(SymbolComparer);
private ConcurrentDictionary<IMethodSymbol, bool> Nodes = new(SymbolComparer);
public bool AddEdge(IMethodSymbol caller, IMethodSymbol callee)
{
caller = caller.OriginalDefinition;
callee = callee.OriginalDefinition;
var result = Add(Dependencies, caller, callee);
if (result)
{
Add(Dependents, callee, caller);
}
return result;
}
public HashSet<IMethodSymbol> Visit(
IEnumerable<IMethodSymbol> initial,
bool dependencies = false)
{
var empty = new HashSet<IMethodSymbol>();
var stack = new Stack<IMethodSymbol>(initial);
var visited = new HashSet<IMethodSymbol>(SymbolComparer);
var map = dependencies ? Dependencies : Dependents;
while (stack.Count != 0)
{
var item = stack.Pop();
if (visited.Add(item))
{
foreach (var next in map.GetOrDefault(item, defaultValue: empty))
{
if (visited.Add(next))
{
stack.Push(next);
}
}
}
}
return visited;
}
public bool AddNode(IMethodSymbol symbol)
{
symbol = symbol.OriginalDefinition;
if (Nodes.TryAdd(symbol, true))
{
if (symbol.OverriddenMethod != null)
{
AddEdge(symbol, symbol.OverriddenMethod);
Add(Overrides, symbol.OverriddenMethod.OriginalDefinition, symbol);
}
return true;
}
return false;
}
public bool Add(
ConcurrentDictionary<IMethodSymbol, HashSet<IMethodSymbol>> map,
IMethodSymbol key,
IMethodSymbol value)
{
return map.GetOrAdd(key, k => new HashSet<IMethodSymbol>(SymbolComparer)).Add(value);
}
}
}
}
| |
namespace FakeItEasy.Creation
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using FakeItEasy.Core;
internal class DummyValueResolver : IDummyValueResolver
{
private readonly ResolveStrategy[] strategies;
private readonly ConcurrentDictionary<Type, ResolveStrategy> strategyCache;
/// <summary>
/// Initializes a new instance of the <see cref="DummyValueResolver"/> class.
/// </summary>
/// <param name="dummyFactory">The dummy factory.</param>
/// <param name="fakeObjectCreator">The fake object creator.</param>
public DummyValueResolver(DynamicDummyFactory dummyFactory, IFakeObjectCreator fakeObjectCreator)
{
this.strategyCache = new ConcurrentDictionary<Type, ResolveStrategy>();
this.strategies = new ResolveStrategy[]
{
new ResolveFromDummyFactoryStrategy(dummyFactory),
new ResolveByCreatingTaskStrategy(),
new ResolveByCreatingLazyStrategy(),
new ResolveByCreatingTupleStrategy(),
new ResolveByActivatingValueTypeStrategy(),
new ResolveByCreatingFakeStrategy(fakeObjectCreator),
new ResolveByInstantiatingClassUsingDummyValuesAsConstructorArgumentsStrategy()
};
}
public CreationResult TryResolveDummyValue(Type typeOfDummy, LoopDetectingResolutionContext resolutionContext)
{
// Make sure we're not already resolving typeOfDummy. It may seem that we could skip this check when we have
// a cached resolution strategy in strategyCache, but it's necessary in case multiple threads are involved and
// typeOfDummy has a constructor that takes typeOfDummy as a parameter.
// In that situation, perhaps this thread starts trying to resolve a Dummy using the constructor that takes a
// typeOfDummy. Meanwhile another thread does the same thing, but gets more processing time and eventually fails to
// use that constructor, but then it succeeds in making a typeOfDummy using a different constructor. Then the strategy
// is cached. This thread sees the cached strategy, creates a typeOfDummy for the constructor parameter, and then
// uses it to make the "outer" typeOfDummy. Then we'd have Dummies created via two different constructors, which
// might have different behavior. This is essentially the problem that arose in issue 1639.
if (!resolutionContext.TryBeginToResolve(typeOfDummy))
{
return CreationResult.FailedToCreateDummy(typeOfDummy, "Recursive dependency detected. Already resolving " + typeOfDummy + '.');
}
try
{
return this.strategyCache.TryGetValue(typeOfDummy, out ResolveStrategy cachedStrategy)
? cachedStrategy.TryCreateDummyValue(typeOfDummy, this, resolutionContext)
: this.TryResolveDummyValueWithAllAvailableStrategies(typeOfDummy, resolutionContext);
}
finally
{
resolutionContext.EndResolve(typeOfDummy);
}
}
private CreationResult TryResolveDummyValueWithAllAvailableStrategies(
Type typeOfDummy,
LoopDetectingResolutionContext resolutionContext)
{
CreationResult creationResult = CreationResult.Untried;
foreach (var strategy in this.strategies)
{
var thisCreationResult = strategy.TryCreateDummyValue(typeOfDummy, this, resolutionContext);
if (thisCreationResult.WasSuccessful)
{
this.strategyCache.TryAdd(typeOfDummy, strategy);
return thisCreationResult;
}
creationResult = creationResult.MergeIntoDummyResult(thisCreationResult);
}
this.strategyCache.TryAdd(typeOfDummy, new UnableToResolveStrategy(creationResult));
return creationResult;
}
private class ResolveByActivatingValueTypeStrategy : ResolveStrategy
{
public override CreationResult TryCreateDummyValue(
Type typeOfDummy,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
if (typeOfDummy.GetTypeInfo().IsValueType && typeOfDummy != typeof(void))
{
return CreationResult.SuccessfullyCreated(Activator.CreateInstance(typeOfDummy));
}
return CreationResult.FailedToCreateDummy(typeOfDummy, "It is not a value type.");
}
}
private class ResolveByCreatingFakeStrategy : ResolveStrategy
{
public ResolveByCreatingFakeStrategy(IFakeObjectCreator fakeCreator)
{
this.FakeCreator = fakeCreator;
}
private IFakeObjectCreator FakeCreator { get; }
public override CreationResult TryCreateDummyValue(
Type typeOfDummy,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
return this.FakeCreator.CreateFakeWithoutLoopDetection(
typeOfDummy,
new ProxyOptions(),
resolver,
resolutionContext);
}
}
private class ResolveByCreatingTaskStrategy : ResolveStrategy
{
private static readonly MethodInfo GenericFromResultMethodDefinition = CreateGenericFromResultMethodDefinition();
public override CreationResult TryCreateDummyValue(
Type typeOfDummy,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
if (typeOfDummy == typeof(Task))
{
return CreationResult.SuccessfullyCreated(TaskHelper.FromResult(default(object)));
}
if (typeOfDummy.GetTypeInfo().IsGenericType && typeOfDummy.GetGenericTypeDefinition() == typeof(Task<>))
{
var typeOfTaskResult = typeOfDummy.GetGenericArguments()[0];
var creationResult = resolver.TryResolveDummyValue(typeOfTaskResult, resolutionContext);
object? taskResult = creationResult.WasSuccessful
? creationResult.Result
: typeOfTaskResult.GetDefaultValue();
var method = GenericFromResultMethodDefinition.MakeGenericMethod(typeOfTaskResult);
return CreationResult.SuccessfullyCreated(method.Invoke(null, new[] { taskResult }));
}
if (typeOfDummy.FullName == "System.Threading.Tasks.ValueTask")
{
return CreationResult.SuccessfullyCreated(typeOfDummy.GetDefaultValue());
}
if (typeOfDummy.GetTypeInfo().IsGenericType &&
!typeOfDummy.GetTypeInfo().IsGenericTypeDefinition &&
typeOfDummy.FullName.StartsWith("System.Threading.Tasks.ValueTask`", StringComparison.Ordinal))
{
var typeOfTaskResult = typeOfDummy.GetGenericArguments()[0];
var creationResult = resolver.TryResolveDummyValue(typeOfTaskResult, resolutionContext);
object? taskResult = creationResult.WasSuccessful
? creationResult.Result
: typeOfTaskResult.GetDefaultValue();
var ctor = typeOfDummy.GetConstructor(new[] { typeOfTaskResult });
return CreationResult.SuccessfullyCreated(ctor.Invoke(new[] { taskResult }));
}
return CreationResult.FailedToCreateDummy(typeOfDummy, "It is not a Task.");
}
private static MethodInfo CreateGenericFromResultMethodDefinition()
{
Expression<Action> templateExpression = () => TaskHelper.FromResult(new object());
var templateMethod = ((MethodCallExpression)templateExpression.Body).Method;
return templateMethod.GetGenericMethodDefinition();
}
}
private class ResolveByCreatingLazyStrategy : ResolveStrategy
{
private static readonly MethodInfo CreateLazyDummyGenericDefinition =
typeof(ResolveByCreatingLazyStrategy).GetMethod(
nameof(CreateLazyDummy),
BindingFlags.Static | BindingFlags.NonPublic);
public override CreationResult TryCreateDummyValue(
Type typeOfDummy,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
if (typeOfDummy.GetTypeInfo().IsGenericType && typeOfDummy.GetGenericTypeDefinition() == typeof(Lazy<>))
{
var typeOfLazyResult = typeOfDummy.GetGenericArguments()[0];
var method = CreateLazyDummyGenericDefinition.MakeGenericMethod(typeOfLazyResult);
var dummy = method.Invoke(null, new object[] { resolver });
return CreationResult.SuccessfullyCreated(dummy);
}
return CreationResult.FailedToCreateDummy(typeOfDummy, "It is not a Lazy.");
}
private static Lazy<T> CreateLazyDummy<T>(IDummyValueResolver resolver)
{
return new Lazy<T>(() =>
{
var creationResult = resolver.TryResolveDummyValue(typeof(T), new LoopDetectingResolutionContext());
return creationResult.WasSuccessful
? (T)creationResult.Result!
: default;
});
}
}
private class ResolveByCreatingTupleStrategy : ResolveStrategy
{
public override CreationResult TryCreateDummyValue(Type typeOfDummy, IDummyValueResolver resolver, LoopDetectingResolutionContext resolutionContext)
{
if (IsTuple(typeOfDummy))
{
var argTypes = typeOfDummy.GetTypeInfo().GetGenericArguments();
var args = new object?[argTypes.Length];
for (int i = 0; i < argTypes.Length; i++)
{
var argType = argTypes[i];
var creationResult = resolver.TryResolveDummyValue(argType, resolutionContext);
args[i] = creationResult.WasSuccessful
? creationResult.Result
: argType.GetDefaultValue();
}
var dummy = Activator.CreateInstance(typeOfDummy, args);
return CreationResult.SuccessfullyCreated(dummy);
}
return CreationResult.FailedToCreateDummy(typeOfDummy, "It is not a tuple.");
}
private static bool IsTuple(Type type) =>
type.GetTypeInfo().IsGenericType
&& !type.GetTypeInfo().IsGenericTypeDefinition
&& (type.FullName.StartsWith("System.Tuple`", StringComparison.Ordinal) ||
type.FullName.StartsWith("System.ValueTuple`", StringComparison.Ordinal));
}
private class ResolveByInstantiatingClassUsingDummyValuesAsConstructorArgumentsStrategy : ResolveStrategy
{
private readonly ConcurrentDictionary<Type, ConstructorInfo> cachedConstructors = new ConcurrentDictionary<Type, ConstructorInfo>();
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Appropriate in try method.")]
public override CreationResult TryCreateDummyValue(
Type typeOfDummy,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
if (typeof(Delegate).IsAssignableFrom(typeOfDummy))
{
return CreationResult.FailedToCreateDummy(typeOfDummy, "It is a Delegate.");
}
if (typeOfDummy.GetTypeInfo().IsAbstract)
{
return CreationResult.FailedToCreateDummy(typeOfDummy, "It is abstract.");
}
// Save the constructors as we try them. Avoids eager evaluation and double evaluation
// of constructors enumerable.
var consideredConstructors = new List<ResolvedConstructor>();
if (this.cachedConstructors.TryGetValue(typeOfDummy, out ConstructorInfo cachedConstructor))
{
var resolvedConstructor = new ResolvedConstructor(
cachedConstructor.GetParameters().Select(pi => pi.ParameterType),
resolver,
resolutionContext);
if (resolvedConstructor.WasSuccessfullyResolved)
{
if (TryCreateDummyValueUsingConstructor(cachedConstructor, resolvedConstructor, out object? result))
{
return CreationResult.SuccessfullyCreated(result);
}
consideredConstructors.Add(resolvedConstructor);
}
}
else
{
foreach (var constructor in GetConstructorsInOrder(typeOfDummy))
{
var resolvedConstructor = new ResolvedConstructor(
constructor.GetParameters().Select(pi => pi.ParameterType),
resolver,
resolutionContext);
if (resolvedConstructor.WasSuccessfullyResolved &&
TryCreateDummyValueUsingConstructor(constructor, resolvedConstructor, out object? result))
{
this.cachedConstructors.TryAdd(typeOfDummy, constructor);
return CreationResult.SuccessfullyCreated(result);
}
consideredConstructors.Add(resolvedConstructor);
}
}
if (consideredConstructors.Any())
{
return CreationResult.FailedToCreateDummy(typeOfDummy, consideredConstructors);
}
return CreationResult.FailedToCreateDummy(typeOfDummy, "It has no public constructors.");
}
private static IEnumerable<ConstructorInfo> GetConstructorsInOrder(Type type)
{
return type.GetConstructors().OrderBy(x => x.GetParameters().Length).Reverse();
}
private static bool TryCreateDummyValueUsingConstructor(ConstructorInfo constructor, ResolvedConstructor resolvedConstructor, out object? result)
{
try
{
result = constructor.Invoke(resolvedConstructor.Arguments.Select(a => a.ResolvedValue).ToArray());
return true;
}
catch (TargetInvocationException e)
{
result = default;
resolvedConstructor.ReasonForFailure = e.InnerException.Message;
return false;
}
}
}
private class ResolveFromDummyFactoryStrategy : ResolveStrategy
{
public ResolveFromDummyFactoryStrategy(DynamicDummyFactory dummyFactory)
{
this.DummyFactory = dummyFactory;
}
private DynamicDummyFactory DummyFactory { get; }
public override CreationResult TryCreateDummyValue(
Type typeOfDummy,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
var success = this.DummyFactory.TryCreateDummyObject(typeOfDummy, out object? result);
return success
? CreationResult.SuccessfullyCreated(result)
: CreationResult.FailedToCreateDummy(typeOfDummy, "No Dummy Factory produced a result.");
}
}
private abstract class ResolveStrategy
{
public abstract CreationResult TryCreateDummyValue(
Type typeOfDummy,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext);
}
private class UnableToResolveStrategy : ResolveStrategy
{
private readonly CreationResult creationResult;
public UnableToResolveStrategy(CreationResult creationResult)
{
this.creationResult = creationResult;
}
public override CreationResult TryCreateDummyValue(
Type typeOfDummy,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
return this.creationResult;
}
}
}
}
| |
using System;
namespace System.Globalization
{
internal static class SR
{
public static string Arg_HexStyleNotSupported
{
get { return Environment.GetResourceString("Arg_HexStyleNotSupported"); }
}
public static string Arg_InvalidHexStyle
{
get { return Environment.GetResourceString("Arg_InvalidHexStyle"); }
}
public static string ArgumentNull_Array
{
get { return Environment.GetResourceString("ArgumentNull_Array"); }
}
public static string ArgumentNull_ArrayValue
{
get { return Environment.GetResourceString("ArgumentNull_ArrayValue"); }
}
public static string ArgumentNull_Obj
{
get { return Environment.GetResourceString("ArgumentNull_Obj"); }
}
public static string ArgumentNull_String
{
get { return Environment.GetResourceString("ArgumentNull_String"); }
}
public static string ArgumentOutOfRange_AddValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_AddValue"); }
}
public static string ArgumentOutOfRange_BadHourMinuteSecond
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"); }
}
public static string ArgumentOutOfRange_BadYearMonthDay
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"); }
}
public static string ArgumentOutOfRange_Bounds_Lower_Upper
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"); }
}
public static string ArgumentOutOfRange_CalendarRange
{
get { return Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"); }
}
public static string ArgumentOutOfRange_Count
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Count"); }
}
public static string ArgumentOutOfRange_Day
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Day"); }
}
public static string ArgumentOutOfRange_Enum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Enum"); }
}
public static string ArgumentOutOfRange_Era
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Era"); }
}
public static string ArgumentOutOfRange_Index
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Index"); }
}
public static string ArgumentOutOfRange_InvalidEraValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"); }
}
public static string ArgumentOutOfRange_Month
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Month"); }
}
public static string ArgumentOutOfRange_NeedNonNegNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); }
}
public static string ArgumentOutOfRange_NeedPosNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"); }
}
public static string Arg_ArgumentOutOfRangeException
{
get { return Environment.GetResourceString("Arg_ArgumentOutOfRangeException"); }
}
public static string ArgumentOutOfRange_OffsetLength
{
get { return Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"); }
}
public static string ArgumentOutOfRange_Range
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Range"); }
}
public static string Argument_CompareOptionOrdinal
{
get { return Environment.GetResourceString("Argument_CompareOptionOrdinal"); }
}
public static string Argument_ConflictingDateTimeRoundtripStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeRoundtripStyles"); }
}
public static string Argument_ConflictingDateTimeStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeStyles"); }
}
public static string Argument_CultureInvalidIdentifier
{
get { return Environment.GetResourceString("Argument_CultureInvalidIdentifier"); }
}
public static string Argument_CultureNotSupported
{
get { return Environment.GetResourceString("Argument_CultureNotSupported"); }
}
public static string Argument_EmptyDecString
{
get { return Environment.GetResourceString("Argument_EmptyDecString"); }
}
public static string Argument_InvalidArrayLength
{
get { return Environment.GetResourceString("Argument_InvalidArrayLength"); }
}
public static string Argument_InvalidCalendar
{
get { return Environment.GetResourceString("Argument_InvalidCalendar"); }
}
public static string Argument_InvalidCultureName
{
get { return Environment.GetResourceString("Argument_InvalidCultureName"); }
}
public static string Argument_InvalidDateTimeStyles
{
get { return Environment.GetResourceString("Argument_InvalidDateTimeStyles"); }
}
public static string Argument_InvalidFlag
{
get { return Environment.GetResourceString("Argument_InvalidFlag"); }
}
public static string Argument_InvalidGroupSize
{
get { return Environment.GetResourceString("Argument_InvalidGroupSize"); }
}
public static string Argument_InvalidNeutralRegionName
{
get { return Environment.GetResourceString("Argument_InvalidNeutralRegionName"); }
}
public static string Argument_InvalidNumberStyles
{
get { return Environment.GetResourceString("Argument_InvalidNumberStyles"); }
}
public static string Argument_InvalidResourceCultureName
{
get { return Environment.GetResourceString("Argument_InvalidResourceCultureName"); }
}
public static string Argument_NoEra
{
get { return Environment.GetResourceString("Argument_NoEra"); }
}
public static string Argument_NoRegionInvariantCulture
{
get { return Environment.GetResourceString("Argument_NoRegionInvariantCulture"); }
}
public static string Argument_ResultCalendarRange
{
get { return Environment.GetResourceString("Argument_ResultCalendarRange"); }
}
public static string Format_BadFormatSpecifier
{
get { return Environment.GetResourceString("Format_BadFormatSpecifier"); }
}
public static string InvalidOperation_DateTimeParsing
{
get { return Environment.GetResourceString("InvalidOperation_DateTimeParsing"); }
}
public static string InvalidOperation_EnumEnded
{
get { return Environment.GetResourceString("InvalidOperation_EnumEnded"); }
}
public static string InvalidOperation_EnumNotStarted
{
get { return Environment.GetResourceString("InvalidOperation_EnumNotStarted"); }
}
public static string InvalidOperation_ReadOnly
{
get { return Environment.GetResourceString("InvalidOperation_ReadOnly"); }
}
public static string Overflow_TimeSpanTooLong
{
get { return Environment.GetResourceString("Overflow_TimeSpanTooLong"); }
}
public static string Serialization_MemberOutOfRange
{
get { return Environment.GetResourceString("Serialization_MemberOutOfRange"); }
}
public static string Format(string formatString, params object[] args)
{
return string.Format(CultureInfo.CurrentCulture, formatString, args);
}
}
}
| |
// 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.Reflection;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Runtime.Serialization;
namespace System.Text
{
// Our input file data structures look like:
//
// Header structure looks like:
// struct NLSPlusHeader
// {
// WORD[16] filename; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3, 2, 0, 0
// WORD count; // 2 bytes = 42 // Number of code page indexes that will follow
// }
//
// Each code page section looks like:
// struct NLSCodePageIndex
// {
// WORD[16] codePageName; // 32 bytes
// WORD codePage; // +2 bytes = 34
// WORD byteCount; // +2 bytes = 36
// DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE.
// }
//
// Each code page then has its own header
// struct NLSCodePage
// {
// WORD[16] codePageName; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3.2.0.0
// WORD codePage; // 2 bytes = 42
// WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS)
// WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character
// WORD byteReplace; // 2 bytes = 48 // default replacement byte(s)
// BYTE[] data; // data section
// }
internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable
{
internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";
protected int dataTableCodePage;
// Variables to help us allocate/mark our memory section correctly
protected int iExtraBytes = 0;
// Our private unicode-to-bytes best-fit-array, and vice versa.
protected char[] arrayUnicodeBestFit = null;
protected char[] arrayBytesBestFit = null;
internal BaseCodePageEncoding(int codepage)
: this(codepage, codepage)
{
}
internal BaseCodePageEncoding(int codepage, int dataCodePage)
: base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null))
{
SetFallbackEncoding();
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec)
: base(codepage, enc, dec)
{
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
// Just a helper as we cannot use 'this' when calling 'base(...)'
private void SetFallbackEncoding()
{
(EncoderFallback as InternalEncoderBestFitFallback).encoding = this;
(DecoderFallback as InternalDecoderBestFitFallback).encoding = this;
}
//
// This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME.
//
// Explicit layout is used here since a syntax like char[16] can not be used in sequential layout.
[StructLayout(LayoutKind.Explicit)]
internal struct CodePageDataFileHeader
{
[FieldOffset(0)]
internal char TableName; // WORD[16]
[FieldOffset(0x20)]
internal ushort Version; // WORD[4]
[FieldOffset(0x28)]
internal short CodePageCount; // WORD
[FieldOffset(0x2A)]
internal short unused1; // Add an unused WORD so that CodePages is aligned with DWORD boundary.
}
private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44;
[StructLayout(LayoutKind.Explicit, Pack = 2)]
internal unsafe struct CodePageIndex
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal short CodePage; // WORD
[FieldOffset(0x22)]
internal short ByteCount; // WORD
[FieldOffset(0x24)]
internal int Offset; // DWORD
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageHeader
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal ushort VersionMajor; // WORD
[FieldOffset(0x22)]
internal ushort VersionMinor; // WORD
[FieldOffset(0x24)]
internal ushort VersionRevision;// WORD
[FieldOffset(0x26)]
internal ushort VersionBuild; // WORD
[FieldOffset(0x28)]
internal short CodePage; // WORD
[FieldOffset(0x2a)]
internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS)
[FieldOffset(0x2c)]
internal char UnicodeReplace; // WORD // default replacement unicode character
[FieldOffset(0x2e)]
internal ushort ByteReplace; // WORD // default replacement bytes
}
private const int CODEPAGE_HEADER_SIZE = 48;
// Initialize our global stuff
private static byte[] s_codePagesDataHeader = new byte[CODEPAGE_DATA_FILE_HEADER_SIZE];
protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream(CODE_PAGE_DATA_FILE_NAME);
protected static readonly Object s_streamLock = new Object(); // this lock used when reading from s_codePagesEncodingDataStream
// Real variables
protected byte[] m_codePageHeader = new byte[CODEPAGE_HEADER_SIZE];
protected int m_firstDataWordOffset;
protected int m_dataSize;
// Safe handle wrapper around section map view
protected SafeAllocHHandle safeNativeMemoryHandle = null;
internal static Stream GetEncodingDataStream(String tableName)
{
Debug.Assert(tableName != null, "table name can not be null");
// NOTE: We must reflect on a public type that is exposed in the contract here
// (i.e. CodePagesEncodingProvider), otherwise we will not get a reference to
// the right assembly.
Stream stream = typeof(CodePagesEncodingProvider).GetTypeInfo().Assembly.GetManifestResourceStream(tableName);
if (stream == null)
{
// We can not continue if we can't get the resource.
throw new InvalidOperationException();
}
// Read the header
stream.Read(s_codePagesDataHeader, 0, s_codePagesDataHeader.Length);
return stream;
}
// We need to load tables for our code page
private unsafe void LoadCodePageTables()
{
if (!FindCodePage(dataTableCodePage))
{
// Didn't have one
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
}
// We had it, so load it
LoadManagedCodePage();
}
// Look up the code page pointer
private unsafe bool FindCodePage(int codePage)
{
Debug.Assert(m_codePageHeader != null && m_codePageHeader.Length == CODEPAGE_HEADER_SIZE, "m_codePageHeader expected to match in size the struct CodePageHeader");
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = &s_codePagesDataHeader[0])
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = &codePageIndex[0])
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
// Found it!
long position = s_codePagesEncodingDataStream.Position;
s_codePagesEncodingDataStream.Seek((long)pCodePageIndex->Offset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(m_codePageHeader, 0, m_codePageHeader.Length);
m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; // stream now pointing to the codepage data
if (i == codePagesCount - 1) // last codepage
{
m_dataSize = (int)(s_codePagesEncodingDataStream.Length - pCodePageIndex->Offset - m_codePageHeader.Length);
}
else
{
// Read Next codepage data to get the offset and then calculate the size
s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin);
int currentOffset = pCodePageIndex->Offset;
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
m_dataSize = pCodePageIndex->Offset - currentOffset - m_codePageHeader.Length;
}
return true;
}
}
}
}
// Couldn't find it
return false;
}
// Get our code page byte count
internal static unsafe int GetCodePageByteSize(int codePage)
{
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = &s_codePagesDataHeader[0])
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = &codePageIndex[0])
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
Debug.Assert(pCodePageIndex->ByteCount == 1 || pCodePageIndex->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePageIndex->ByteCount + ") in table");
// Return what it says for byte count
return pCodePageIndex->ByteCount;
}
}
}
}
// Couldn't find it
return 0;
}
// We have a managed code page entry, so load our tables
protected abstract unsafe void LoadManagedCodePage();
// Allocate memory to load our code page
protected unsafe byte* GetNativeMemory(int iSize)
{
if (safeNativeMemoryHandle == null)
{
byte* pNativeMemory = (byte*)Marshal.AllocHGlobal(iSize);
Debug.Assert(pNativeMemory != null);
safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)pNativeMemory);
}
return (byte*)safeNativeMemoryHandle.DangerousGetHandle();
}
protected abstract unsafe void ReadBestFitTable();
internal char[] GetBestFitUnicodeToBytesData()
{
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
return arrayUnicodeBestFit;
}
internal char[] GetBestFitBytesToUnicodeData()
{
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
return arrayBytesBestFit;
}
// During the AppDomain shutdown the Encoding class may have already finalized, making the memory section
// invalid. We detect that by validating the memory section handle then re-initializing the memory
// section by calling LoadManagedCodePage() method and eventually the mapped file handle and
// the memory section pointer will get finalized one more time.
internal unsafe void CheckMemorySection()
{
if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero)
{
LoadManagedCodePage();
}
}
}
}
| |
//
// NSData.cs:
// Author:
// Miguel de Icaza
//
// Copyright 2011, Novell, Inc.
// Copyright 2011, 2012 Xamarin Inc
//
// 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 MonoMac.ObjCRuntime;
using System;
namespace MonoMac.Foundation {
public enum NSFileType {
Directory, Regular, SymbolicLink, Socket, CharacterSpecial, BlockSpecial, Unknown
}
public class NSFileAttributes {
public NSFileAttributes () {}
public bool? AppendOnly { get; set; }
public bool? Busy { get; set; }
public bool? FileExtensionHidden { get; set; }
public NSDate CreationDate { get; set; }
public string OwnerAccountName { get; set; }
public uint? DeviceIdentifier { get; set; }
public uint? FileGroupOwnerAccountID { get; set; }
public bool? Immutable { get; set; }
public NSDate ModificationDate { get; set; }
public uint? FileOwnerAccountID { get; set; }
public uint? HfsTypeCode { get; set; }
public uint? PosixPermissions { get; set; }
public uint? FileReferenceCount { get; set; }
public uint? FileSystemFileNumber { get; set; }
public ulong? FileSize { get; set; }
public NSFileType? FileType { get; set; }
//public bool? ProtectedFile { get; set; }
internal NSDictionary ToDictionary ()
{
var dict = new NSMutableDictionary ();
if (AppendOnly.HasValue)
dict.SetObject (NSNumber.FromBoolean (AppendOnly.Value), NSFileManager.AppendOnly);
if (Busy.HasValue)
dict.SetObject (NSNumber.FromBoolean (Busy.Value), NSFileManager.Busy);
if (CreationDate != null)
dict.SetObject (CreationDate, NSFileManager.CreationDate);
if (ModificationDate != null)
dict.SetObject (ModificationDate, NSFileManager.ModificationDate);
if (OwnerAccountName != null)
dict.SetObject (new NSString (OwnerAccountName), NSFileManager.OwnerAccountName);
if (DeviceIdentifier.HasValue)
dict.SetObject (NSNumber.FromUInt32 (DeviceIdentifier.Value), NSFileManager.DeviceIdentifier);
if (FileExtensionHidden.HasValue)
dict.SetObject (NSNumber.FromBoolean (FileExtensionHidden.Value), NSFileManager.ExtensionHidden);
if (FileGroupOwnerAccountID.HasValue)
dict.SetObject (NSNumber.FromUInt32 (FileGroupOwnerAccountID.Value), NSFileManager.GroupOwnerAccountID);
if (FileOwnerAccountID.HasValue)
dict.SetObject (NSNumber.FromUInt32 (FileOwnerAccountID.Value), NSFileManager.OwnerAccountID);
if (HfsTypeCode.HasValue)
dict.SetObject (NSNumber.FromUInt32 (HfsTypeCode.Value), NSFileManager.HfsTypeCode);
if (PosixPermissions.HasValue)
dict.SetObject (NSNumber.FromUInt32 (PosixPermissions.Value), NSFileManager.PosixPermissions);
if (FileReferenceCount.HasValue)
dict.SetObject (NSNumber.FromUInt32 (FileReferenceCount.Value), NSFileManager.ReferenceCount);
if (FileSystemFileNumber.HasValue)
dict.SetObject (NSNumber.FromUInt32 (FileSystemFileNumber.Value), NSFileManager.SystemFileNumber);
if (FileSize.HasValue)
dict.SetObject (NSNumber.FromUInt64 (FileSize.Value), NSFileManager.Size);
if (Immutable.HasValue)
dict.SetObject (NSNumber.FromBoolean (Immutable.Value), NSFileManager.Immutable);
//if (ProtectedFile.HasValue)
//dict.SetObject (NSNumber.FromBoolean (ProtectedFile.Value), NSFileManager.ProtectedFile);
if (FileType.HasValue){
NSString v = null;
switch (FileType.Value){
case NSFileType.Directory:
v = NSFileManager.TypeDirectory; break;
case NSFileType.Regular:
v = NSFileManager.TypeRegular; break;
case NSFileType.SymbolicLink:
v = NSFileManager.TypeSymbolicLink; break;
case NSFileType.Socket:
v = NSFileManager.TypeSocket; break;
case NSFileType.CharacterSpecial:
v = NSFileManager.TypeCharacterSpecial; break;
case NSFileType.BlockSpecial:
v = NSFileManager.TypeBlockSpecial; break;
default:
v = NSFileManager.TypeUnknown; break;
}
dict.SetObject (v, NSFileManager.NSFileType);
}
return dict;
}
internal static bool fetch (NSDictionary dict, NSString key, ref bool b)
{
var k = dict.ObjectForKey (key) as NSNumber;
if (k == null)
return false;
b = k.BoolValue;
return true;
}
internal static bool fetch (NSDictionary dict, NSString key, ref uint b)
{
var k = dict.ObjectForKey (key) as NSNumber;
if (k == null)
return false;
b = k.UInt32Value;
return true;
}
internal static bool fetch (NSDictionary dict, NSString key, ref ulong b)
{
var k = dict.ObjectForKey (key) as NSNumber;
if (k == null)
return false;
b = k.UInt64Value;
return true;
}
public static NSFileAttributes FromDict (NSDictionary dict)
{
if (dict == null)
return null;
var ret = new NSFileAttributes ();
bool b = false;
if (fetch (dict, NSFileManager.AppendOnly, ref b))
ret.AppendOnly = b;
if (fetch (dict, NSFileManager.Busy, ref b))
ret.Busy = b;
if (fetch (dict, NSFileManager.Immutable, ref b))
ret.Immutable = b;
//if (fetch (dict, NSFileManager.ProtectedFile, ref b))
//ret.ProtectedFile = b;
if (fetch (dict, NSFileManager.ExtensionHidden, ref b))
ret.FileExtensionHidden = b;
var date = dict.ObjectForKey (NSFileManager.CreationDate) as NSDate;
if (date != null)
ret.CreationDate = date;
date = dict.ObjectForKey (NSFileManager.ModificationDate) as NSDate;
if (date != null)
ret.ModificationDate = date;
var name = dict.ObjectForKey (NSFileManager.OwnerAccountName) as NSString;
if (name != null)
ret.OwnerAccountName = name.ToString ();
uint u = 0;
if (fetch (dict, NSFileManager.DeviceIdentifier, ref u))
ret.DeviceIdentifier = u;
if (fetch (dict, NSFileManager.GroupOwnerAccountID, ref u))
ret.FileGroupOwnerAccountID = u;
if (fetch (dict, NSFileManager.OwnerAccountID, ref u))
ret.FileOwnerAccountID = u;
if (fetch (dict, NSFileManager.HfsTypeCode, ref u))
ret.HfsTypeCode = u;
if (fetch (dict, NSFileManager.PosixPermissions, ref u))
ret.PosixPermissions = u;
if (fetch (dict, NSFileManager.ReferenceCount, ref u))
ret.FileReferenceCount = u;
if (fetch (dict, NSFileManager.SystemFileNumber, ref u))
ret.FileSystemFileNumber = u;
ulong l = 0;
if (fetch (dict, NSFileManager.Size, ref l))
ret.FileSize = l;
return ret;
}
}
public class NSFileSystemAttributes {
NSDictionary dict;
internal NSFileSystemAttributes (NSDictionary dict)
{
this.dict = dict;
}
public ulong Size { get; internal set; }
public ulong FreeSize { get; internal set; }
public long Nodes { get; internal set; }
public long FreeNodes { get; internal set; }
public uint Number { get; internal set; }
internal static NSFileSystemAttributes FromDict (NSDictionary dict)
{
if (dict == null)
return null;
var ret = new NSFileSystemAttributes (dict);
ulong l = 0;
uint i = 0;
ret.Size = NSFileAttributes.fetch (dict, NSFileManager.SystemSize, ref l) ? l : 0;
ret.FreeSize = NSFileAttributes.fetch (dict, NSFileManager.SystemFreeSize, ref l) ? l : 0;
ret.Nodes = NSFileAttributes.fetch (dict, NSFileManager.SystemNodes, ref l) ? (long) l : 0;
ret.FreeNodes= NSFileAttributes.fetch (dict, NSFileManager.SystemFreeNodes, ref l) ? (long) l : 0;
ret.Number = NSFileAttributes.fetch (dict, NSFileManager.SystemFreeNodes, ref i) ? i : 0;
return ret;
}
// For source code compatibility with users that had done manual NSDictionary lookups before
public static implicit operator NSDictionary (NSFileSystemAttributes attr)
{
return attr.dict;
}
}
public partial class NSFileManager {
public bool SetAttributes (NSFileAttributes attributes, string path, out NSError error)
{
if (attributes == null)
throw new ArgumentNullException ("attributes");
return SetAttributes (attributes.ToDictionary (), path, out error);
}
public bool SetAttributes (NSFileAttributes attributes, string path)
{
NSError ignore;
if (attributes == null)
throw new ArgumentNullException ("attributes");
return SetAttributes (attributes.ToDictionary (), path, out ignore);
}
public bool CreateDirectory (string path, bool createIntermediates, NSFileAttributes attributes, out NSError error)
{
var dict = attributes == null ? null : attributes.ToDictionary ();
return CreateDirectory (path, createIntermediates, dict, out error);
}
public bool CreateDirectory (string path, bool createIntermediates, NSFileAttributes attributes)
{
NSError error;
var dict = attributes == null ? null : attributes.ToDictionary ();
return CreateDirectory (path, createIntermediates, dict, out error);
}
public bool CreateFile (string path, NSData data, NSFileAttributes attributes)
{
var dict = attributes == null ? null : attributes.ToDictionary ();
return CreateFile (path, data, dict);
}
public NSFileAttributes GetAttributes (string path, out NSError error)
{
return NSFileAttributes.FromDict (_GetAttributes (path, out error));
}
public NSFileAttributes GetAttributes (string path)
{
NSError error;
return NSFileAttributes.FromDict (_GetAttributes (path, out error));
}
public NSFileSystemAttributes GetFileSystemAttributes (string path)
{
NSError error;
return NSFileSystemAttributes.FromDict (_GetFileSystemAttributes (path, out error));
}
public NSFileSystemAttributes GetFileSystemAttributes (string path, out NSError error)
{
return NSFileSystemAttributes.FromDict (_GetFileSystemAttributes (path, out error));
}
public string CurrentDirectory {
get { return GetCurrentDirectory (); }
// ignore boolean return value
set { ChangeCurrentDirectory (value); }
}
}
}
| |
// Copyright 2015, 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.
// Author: Chris Seeley
using Google.Api.Ads.Common.Lib;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Google.Api.Ads.Dfp.Lib {
/// <summary>
/// Lists all the services available through this library.
/// </summary>
public partial class DfpService : AdsService {
/// <summary>
/// All the services available in v201411.
/// </summary>
public class v201411 {
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ActivityGroupService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityGroupService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ActivityService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/AdExclusionRuleService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AdExclusionRuleService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/AdRuleService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AdRuleService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/BaseRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature BaseRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ContactService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContactService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/AudienceSegmentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AudienceSegmentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/CompanyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature CompanyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ContentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ContentMetadataKeyHierarchyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentMetadataKeyHierarchyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/CreativeService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/CreativeSetService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeSetService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/CreativeTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/CreativeWrapperService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeWrapperService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/CustomFieldService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomFieldService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/CustomTargetingService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomTargetingService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ExchangeRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ExchangeRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ForecastService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ForecastService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/InventoryService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature InventoryService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/LabelService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LabelService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/LineItemTemplateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/LineItemService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/LineItemCreativeAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemCreativeAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/LiveStreamEventService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LiveStreamEventService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/NetworkService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature NetworkService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/OrderService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature OrderService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/PlacementService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PlacementService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/PremiumRateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PremiumRateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ProductService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ProductTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductTemplateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ProposalService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ProposalLineItemService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalLineItemService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/PublisherQueryLanguageService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PublisherQueryLanguageService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/RateCardService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature RateCardService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ReconciliationOrderReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationOrderReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ReconciliationReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ReconciliationReportRowService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportRowService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/ReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/SharedAdUnitService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature SharedAdUnitService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/SuggestedAdUnitService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature SuggestedAdUnitService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/TeamService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature TeamService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/UserService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/UserTeamAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserTeamAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201411/WorkflowRequestService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature WorkflowRequestService;
/// <summary>
/// Factory type for v201411 services.
/// </summary>
public static readonly Type factoryType = typeof(DfpServiceFactory);
/// <summary>
/// Static constructor to initialize the service constants.
/// </summary>
static v201411() {
ActivityGroupService = DfpService.MakeServiceSignature("v201411", "ActivityGroupService");
ActivityService = DfpService.MakeServiceSignature("v201411", "ActivityService");
AdExclusionRuleService = DfpService.MakeServiceSignature("v201411", "AdExclusionRuleService");
AdRuleService = DfpService.MakeServiceSignature("v201411", "AdRuleService");
BaseRateService = DfpService.MakeServiceSignature("v201411", "BaseRateService");
ContactService = DfpService.MakeServiceSignature("v201411", "ContactService");
AudienceSegmentService = DfpService.MakeServiceSignature("v201411",
"AudienceSegmentService");
CompanyService = DfpService.MakeServiceSignature("v201411", "CompanyService");
ContentService = DfpService.MakeServiceSignature("v201411", "ContentService");
ContentMetadataKeyHierarchyService = DfpService.MakeServiceSignature("v201411",
"ContentMetadataKeyHierarchyService");
CreativeService = DfpService.MakeServiceSignature("v201411", "CreativeService");
CreativeSetService = DfpService.MakeServiceSignature("v201411", "CreativeSetService");
CreativeTemplateService = DfpService.MakeServiceSignature("v201411",
"CreativeTemplateService");
CreativeWrapperService = DfpService.MakeServiceSignature("v201411",
"CreativeWrapperService");
CustomTargetingService = DfpService.MakeServiceSignature("v201411",
"CustomTargetingService");
CustomFieldService = DfpService.MakeServiceSignature("v201411",
"CustomFieldService");
ExchangeRateService = DfpService.MakeServiceSignature("v201411", "ExchangeRateService");
ForecastService = DfpService.MakeServiceSignature("v201411", "ForecastService");
InventoryService = DfpService.MakeServiceSignature("v201411", "InventoryService");
LabelService = DfpService.MakeServiceSignature("v201411", "LabelService");
LineItemTemplateService = DfpService.MakeServiceSignature("v201411",
"LineItemTemplateService");
LineItemService = DfpService.MakeServiceSignature("v201411", "LineItemService");
LineItemCreativeAssociationService =
DfpService.MakeServiceSignature("v201411", "LineItemCreativeAssociationService");
LiveStreamEventService = DfpService.MakeServiceSignature("v201411",
"LiveStreamEventService");
NetworkService = DfpService.MakeServiceSignature("v201411", "NetworkService");
OrderService = DfpService.MakeServiceSignature("v201411", "OrderService");
PlacementService = DfpService.MakeServiceSignature("v201411", "PlacementService");
PremiumRateService = DfpService.MakeServiceSignature("v201411", "PremiumRateService");
ProductService = DfpService.MakeServiceSignature("v201411", "ProductService");
ProductTemplateService = DfpService.MakeServiceSignature("v201411",
"ProductTemplateService");
ProposalService = DfpService.MakeServiceSignature("v201411", "ProposalService");
ProposalLineItemService = DfpService.MakeServiceSignature("v201411",
"ProposalLineItemService");
PublisherQueryLanguageService = DfpService.MakeServiceSignature("v201411",
"PublisherQueryLanguageService");
RateCardService = DfpService.MakeServiceSignature("v201411", "RateCardService");
ReconciliationOrderReportService = DfpService.MakeServiceSignature("v201411",
"ReconciliationOrderReportService");
ReconciliationReportService = DfpService.MakeServiceSignature("v201411",
"ReconciliationReportService");
ReconciliationReportRowService = DfpService.MakeServiceSignature("v201411",
"ReconciliationReportRowService");
ReportService = DfpService.MakeServiceSignature("v201411", "ReportService");
SharedAdUnitService = DfpService.MakeServiceSignature("v201411",
"SharedAdUnitService");
SuggestedAdUnitService = DfpService.MakeServiceSignature("v201411",
"SuggestedAdUnitService");
TeamService = DfpService.MakeServiceSignature("v201411", "TeamService");
UserService = DfpService.MakeServiceSignature("v201411", "UserService");
UserTeamAssociationService = DfpService.MakeServiceSignature("v201411",
"UserTeamAssociationService");
WorkflowRequestService = DfpService.MakeServiceSignature("v201411",
"WorkflowRequestService");
}
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="InnerListColumn.Generated.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// <auto-generated>
// This code was generated by a tool. DO NOT EDIT
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// -----------------------------------------------------------------------
#region StyleCop Suppression - generated code
using System;
using System.ComponentModel;
using System.Windows;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// Derives and extends GridViewColumn to add concepts such as column visibility..
/// </summary>
[Localizability(LocalizationCategory.None)]
partial class InnerListColumn
{
//
// DataDescription dependency property
//
/// <summary>
/// Identifies the DataDescription dependency property.
/// </summary>
public static readonly DependencyProperty DataDescriptionProperty = DependencyProperty.Register( "DataDescription", typeof(UIPropertyGroupDescription), typeof(InnerListColumn), new PropertyMetadata( null, DataDescriptionProperty_PropertyChanged) );
/// <summary>
/// Gets or sets the data description.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets the data description.")]
[Localizability(LocalizationCategory.None)]
public UIPropertyGroupDescription DataDescription
{
get
{
return (UIPropertyGroupDescription) GetValue(DataDescriptionProperty);
}
set
{
SetValue(DataDescriptionProperty,value);
}
}
static private void DataDescriptionProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
InnerListColumn obj = (InnerListColumn) o;
obj.OnDataDescriptionChanged( new PropertyChangedEventArgs<UIPropertyGroupDescription>((UIPropertyGroupDescription)e.OldValue, (UIPropertyGroupDescription)e.NewValue) );
}
/// <summary>
/// Called when DataDescription property changes.
/// </summary>
protected virtual void OnDataDescriptionChanged(PropertyChangedEventArgs<UIPropertyGroupDescription> e)
{
OnDataDescriptionChangedImplementation(e);
this.OnPropertyChanged(new PropertyChangedEventArgs("DataDescription"));
}
partial void OnDataDescriptionChangedImplementation(PropertyChangedEventArgs<UIPropertyGroupDescription> e);
//
// MinWidth dependency property
//
/// <summary>
/// Identifies the MinWidth dependency property.
/// </summary>
public static readonly DependencyProperty MinWidthProperty = DependencyProperty.Register( "MinWidth", typeof(double), typeof(InnerListColumn), new PropertyMetadata( 20.0, MinWidthProperty_PropertyChanged), MinWidthProperty_ValidateProperty );
/// <summary>
/// Gets or sets a value that dictates the minimum allowable width of the column.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value that dictates the minimum allowable width of the column.")]
[Localizability(LocalizationCategory.None)]
public double MinWidth
{
get
{
return (double) GetValue(MinWidthProperty);
}
set
{
SetValue(MinWidthProperty,value);
}
}
static private void MinWidthProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
InnerListColumn obj = (InnerListColumn) o;
obj.OnMinWidthChanged( new PropertyChangedEventArgs<double>((double)e.OldValue, (double)e.NewValue) );
}
/// <summary>
/// Called when MinWidth property changes.
/// </summary>
protected virtual void OnMinWidthChanged(PropertyChangedEventArgs<double> e)
{
OnMinWidthChangedImplementation(e);
this.OnPropertyChanged(new PropertyChangedEventArgs("MinWidth"));
}
partial void OnMinWidthChangedImplementation(PropertyChangedEventArgs<double> e);
static private bool MinWidthProperty_ValidateProperty(object value)
{
bool isValid = false;
MinWidthProperty_ValidatePropertyImplementation((double) value, ref isValid);
return isValid;
}
static partial void MinWidthProperty_ValidatePropertyImplementation(double value, ref bool isValid);
//
// Required dependency property
//
/// <summary>
/// Identifies the Required dependency property.
/// </summary>
public static readonly DependencyProperty RequiredProperty = DependencyProperty.Register( "Required", typeof(bool), typeof(InnerListColumn), new PropertyMetadata( BooleanBoxes.FalseBox, RequiredProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether the column may not be removed.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether the column may not be removed.")]
[Localizability(LocalizationCategory.None)]
public bool Required
{
get
{
return (bool) GetValue(RequiredProperty);
}
set
{
SetValue(RequiredProperty,BooleanBoxes.Box(value));
}
}
static private void RequiredProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
InnerListColumn obj = (InnerListColumn) o;
obj.OnRequiredChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Called when Required property changes.
/// </summary>
protected virtual void OnRequiredChanged(PropertyChangedEventArgs<bool> e)
{
OnRequiredChangedImplementation(e);
this.OnPropertyChanged(new PropertyChangedEventArgs("Required"));
}
partial void OnRequiredChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// Visible dependency property
//
/// <summary>
/// Identifies the Visible dependency property.
/// </summary>
public static readonly DependencyProperty VisibleProperty = DependencyProperty.Register( "Visible", typeof(bool), typeof(InnerListColumn), new PropertyMetadata( BooleanBoxes.TrueBox, VisibleProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether the columns we want to have available in the list.
/// </summary>
/// <remarks>
/// Modifying the Visible property does not in itself make the column visible or not visible. This should always be kept in sync with the Columns property.
/// </remarks>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether the columns we want to have available in the list.")]
[Localizability(LocalizationCategory.None)]
public bool Visible
{
get
{
return (bool) GetValue(VisibleProperty);
}
set
{
SetValue(VisibleProperty,BooleanBoxes.Box(value));
}
}
static private void VisibleProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
InnerListColumn obj = (InnerListColumn) o;
obj.OnVisibleChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Called when Visible property changes.
/// </summary>
protected virtual void OnVisibleChanged(PropertyChangedEventArgs<bool> e)
{
OnVisibleChangedImplementation(e);
this.OnPropertyChanged(new PropertyChangedEventArgs("Visible"));
}
partial void OnVisibleChangedImplementation(PropertyChangedEventArgs<bool> e);
}
}
#endregion
| |
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
[CanEditMultipleObjects]
[CustomEditor (typeof(View))]
public class ViewEditor : Editor
{
static Color viewColor = Color.yellow;
protected SerializedProperty primaryAspectRatioProp;
protected SerializedProperty secondaryAspectRatioProp;
protected SerializedProperty viewSizeProp;
// Draw Views when they're not selected
#if UNITY_5_0
[DrawGizmo(GizmoType.NotSelected | GizmoType.SelectedOrChild)]
#else
[DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.InSelectionHierarchy)]
#endif
static void RenderCustomGizmo(Transform objectTransform, GizmoType gizmoType)
{
View view = objectTransform.gameObject.GetComponent<View>();
if (view != null)
{
DrawView(view, false);
}
}
protected virtual Vector2 LookupAspectRatio(int index)
{
switch (index)
{
default:
case 1:
return new Vector2(4, 3);
case 2:
return new Vector2(3, 2);
case 3:
return new Vector2(16, 10);
case 4:
return new Vector2(17, 10);
case 5:
return new Vector2(16, 9);
case 6:
return new Vector2(2, 1);
case 7:
return new Vector2(3, 4);
case 8:
return new Vector2(2, 3);
case 9:
return new Vector2(10, 16);
case 10:
return new Vector2(10, 17);
case 11:
return new Vector2(9, 16);
case 12:
return new Vector2(1, 2);
}
}
protected virtual void OnEnable()
{
primaryAspectRatioProp = serializedObject.FindProperty ("primaryAspectRatio");
secondaryAspectRatioProp = serializedObject.FindProperty ("secondaryAspectRatio");
viewSizeProp = serializedObject.FindProperty("viewSize");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(viewSizeProp);
string[] ratios = { "<None>", "Landscape / 4:3", "Landscape / 3:2", "Landscape / 16:10", "Landscape / 17:10", "Landscape / 16:9", "Landscape / 2:1", "Portrait / 3:4", "Portrait / 2:3", "Portrait / 10:16", "Portrait / 10:17", "Portrait / 9:16", "Portrait / 1:2" };
EditorGUILayout.PropertyField(primaryAspectRatioProp, new GUIContent("Primary Aspect Ratio", "Width and height values that define the primary aspect ratio (e.g. 4:3)"));
int primaryIndex = EditorGUILayout.Popup("Select Aspect Ratio", 0, ratios);
if (primaryIndex > 0)
{
primaryAspectRatioProp.vector2Value = LookupAspectRatio(primaryIndex);
}
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(secondaryAspectRatioProp, new GUIContent("Secondary Aspect Ratio", "Width and height values that define the primary aspect ratio (e.g. 4:3)"));
int secondaryIndex = EditorGUILayout.Popup("Select Aspect Ratio", 0, ratios);
if (secondaryIndex > 0)
{
secondaryAspectRatioProp.vector2Value = LookupAspectRatio(secondaryIndex);
}
EditorGUILayout.Separator();
if (EditorGUI.EndChangeCheck())
{
// Avoid divide by zero errors
if (primaryAspectRatioProp.vector2Value.y == 0)
{
primaryAspectRatioProp.vector2Value = new Vector2(primaryAspectRatioProp.vector2Value.x, 1f);
}
if (secondaryAspectRatioProp.vector2Value.y == 0)
{
secondaryAspectRatioProp.vector2Value = new Vector2(secondaryAspectRatioProp.vector2Value.x, 1f);
}
SceneView.RepaintAll();
}
serializedObject.ApplyModifiedProperties();
}
protected virtual void OnSceneGUI ()
{
View t = target as View;
if (t.enabled)
{
EditViewBounds();
}
}
protected virtual void EditViewBounds()
{
View view = target as View;
DrawView(view, true);
Vector3 pos = view.transform.position;
float viewSize = CalculateLocalViewSize(view);
Vector3[] handles = new Vector3[2];
handles[0] = view.transform.TransformPoint(new Vector3(0, -viewSize, 0));
handles[1] = view.transform.TransformPoint(new Vector3(0, viewSize, 0));
Handles.color = Color.white;
for (int i = 0; i < 2; ++i)
{
Vector3 newPos = Handles.FreeMoveHandle(handles[i],
Quaternion.identity,
HandleUtility.GetHandleSize(pos) * 0.1f,
Vector3.zero,
Handles.CubeCap);
if (newPos != handles[i])
{
Undo.RecordObject(view, "Set View Size");
view.viewSize = (newPos - pos).magnitude;
EditorUtility.SetDirty(view);
break;
}
}
}
public static void DrawView(View view, bool drawInterior)
{
float height = CalculateLocalViewSize(view);
float widthA = height * (view.primaryAspectRatio.x / view.primaryAspectRatio.y);
float widthB = height * (view.secondaryAspectRatio.x / view.secondaryAspectRatio.y);
Color transparent = new Color(1,1,1,0f);
Color fill = viewColor;
Color outline = viewColor;
bool highlight = Selection.activeGameObject == view.gameObject;
Flowchart flowchart = FlowchartWindow.GetFlowchart();
if (flowchart != null)
{
foreach (Command command in flowchart.selectedCommands)
{
MoveToView moveToViewCommand = command as MoveToView;
if (moveToViewCommand != null &&
moveToViewCommand.targetView == view)
{
highlight = true;
}
else
{
FadeToView fadeToViewCommand = command as FadeToView;
if (fadeToViewCommand != null &&
fadeToViewCommand.targetView == view)
{
highlight = true;
}
}
}
}
if (highlight)
{
fill = outline = Color.green;
fill.a = 0.1f;
outline.a = 1f;
}
else
{
fill.a = 0.1f;
outline.a = 0.5f;
}
if (drawInterior)
{
// Draw left box
{
Vector3[] verts = new Vector3[4];
verts[0] = view.transform.TransformPoint(new Vector3(-widthB, -height, 0));
verts[1] = view.transform.TransformPoint(new Vector3(-widthB, height, 0));
verts[2] = view.transform.TransformPoint(new Vector3(-widthA, height, 0));
verts[3] = view.transform.TransformPoint(new Vector3(-widthA, -height, 0));
Handles.DrawSolidRectangleWithOutline(verts, fill, transparent);
}
// Draw right box
{
Vector3[] verts = new Vector3[4];
verts[0] = view.transform.TransformPoint(new Vector3(widthA, -height, 0));
verts[1] = view.transform.TransformPoint(new Vector3(widthA, height, 0));
verts[2] = view.transform.TransformPoint(new Vector3(widthB, height, 0));
verts[3] = view.transform.TransformPoint(new Vector3(widthB, -height, 0));
Handles.DrawSolidRectangleWithOutline(verts, fill, transparent);
}
// Draw inner box
{
Vector3[] verts = new Vector3[4];
verts[0] = view.transform.TransformPoint(new Vector3(-widthA, -height, 0));
verts[1] = view.transform.TransformPoint(new Vector3(-widthA, height, 0));
verts[2] = view.transform.TransformPoint(new Vector3(widthA, height, 0));
verts[3] = view.transform.TransformPoint(new Vector3(widthA, -height, 0));
Handles.DrawSolidRectangleWithOutline(verts, transparent, outline );
}
}
// Draw outer box
{
Vector3[] verts = new Vector3[4];
verts[0] = view.transform.TransformPoint(new Vector3(-widthB, -height, 0));
verts[1] = view.transform.TransformPoint(new Vector3(-widthB, height, 0));
verts[2] = view.transform.TransformPoint(new Vector3(widthB, height, 0));
verts[3] = view.transform.TransformPoint(new Vector3(widthB, -height, 0));
Handles.DrawSolidRectangleWithOutline(verts, transparent, outline );
}
}
// Calculate view size in local coordinates
// Kinda expensive, but accurate and only called in editor.
static float CalculateLocalViewSize(View view)
{
return view.transform.InverseTransformPoint(view.transform.position + new Vector3(0, view.viewSize, 0)).magnitude;
}
}
}
| |
/**
* (C) Copyright IBM Corp. 2018, 2021.
*
* 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 IBM.Watson.TextToSpeech.v1.Model;
using IBM.Cloud.SDK.Core.Util;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using IBM.Cloud.SDK.Core;
namespace IBM.Watson.TextToSpeech.v1.IntegrationTests
{
[TestClass]
public class TextToSpeechServiceIntegrationTests
{
private static string apikey;
private static string endpoint;
private TextToSpeechService service;
private static string credentials = string.Empty;
private const string allisonVoice = "en-US_AllisonVoice";
private string synthesizeText = "Hello, welcome to the Watson dotnet SDK!";
private string voiceModelName = "dotnet-sdk-voice-model";
private string voiceModelUpdatedName = "dotnet-sdk-voice-model-updated";
private string voiceModelDescription = "Custom voice model for .NET SDK integration tests.";
private string voiceModelUpdatedDescription = "Custom voice model for .NET SDK integration tests. Updated.";
private string wavFile = @"Assets/test-audio.wav";
[TestInitialize]
public void Setup()
{
service = new TextToSpeechService();
}
#region Voices
[TestMethod]
public void Voices_Success()
{
service.WithHeader("X-Watson-Test", "1");
var listVoicesResult = service.ListVoices();
service.WithHeader("X-Watson-Test", "1");
var getVoiceResult = service.GetVoice(
voice: allisonVoice
);
Assert.IsNotNull(getVoiceResult);
Assert.IsTrue(!string.IsNullOrEmpty(getVoiceResult.Result.Name));
Assert.IsNotNull(listVoicesResult);
Assert.IsNotNull(listVoicesResult.Result._Voices);
}
#endregion
#region Synthesize
[TestMethod]
public void Synthesize_Success()
{
service.WithHeader("X-Watson-Test", "1");
var synthesizeResult = service.Synthesize(
text: synthesizeText,
accept: "audio/wav",
voice: allisonVoice
);
// Save file
using (FileStream fs = File.Create("synthesize.wav"))
{
synthesizeResult.Result.WriteTo(fs);
fs.Close();
synthesizeResult.Result.Close();
}
Assert.IsNotNull(synthesizeResult.Result);
}
#endregion
#region Pronunciation
[TestMethod]
public void Pronunciation_Success()
{
service.WithHeader("X-Watson-Test", "1");
var getPronunciationResult = service.GetPronunciation(
text: "IBM",
voice: allisonVoice,
format: "ipa"
);
Assert.IsNotNull(getPronunciationResult.Result);
Assert.IsNotNull(getPronunciationResult.Result._Pronunciation);
}
#endregion
#region Custom Voice Models
[TestMethod]
public void CustomVoiceModels_Success()
{
service.WithHeader("X-Watson-Test", "1");
var listVoiceModelsResult = service.ListCustomModels();
service.WithHeader("X-Watson-Test", "1");
var createVoiceModelResult = service.CreateCustomModel(
name: voiceModelName,
language: "en-US",
description: voiceModelDescription);
var customizationId = createVoiceModelResult.Result.CustomizationId;
service.WithHeader("X-Watson-Test", "1");
var getVoiceModelResult = service.GetCustomModel(
customizationId: customizationId
);
var words = new List<Word>()
{
new Word()
{
_Word = "hello",
Translation = "hullo"
},
new Word()
{
_Word = "goodbye",
Translation = "gbye"
},
new Word()
{
_Word = "hi",
Translation = "ohioooo"
}
};
service.WithHeader("X-Watson-Test", "1");
var updateVoiceModelResult = service.UpdateCustomModel(
customizationId: customizationId,
name: voiceModelUpdatedName,
description: voiceModelUpdatedDescription,
words: words
);
service.WithHeader("X-Watson-Test", "1");
var getVoiceModelResult2 = service.GetCustomModel(
customizationId: customizationId
);
service.WithHeader("X-Watson-Test", "1");
var deleteVoiceModelResult = service.DeleteCustomModel(
customizationId: customizationId
);
Assert.IsNotNull(deleteVoiceModelResult.StatusCode == 204);
Assert.IsNotNull(getVoiceModelResult2.Result);
Assert.IsTrue(getVoiceModelResult2.Result.Name == voiceModelUpdatedName);
Assert.IsTrue(getVoiceModelResult2.Result.Description == voiceModelUpdatedDescription);
Assert.IsTrue(getVoiceModelResult2.Result.Words.Count == 3);
Assert.IsNotNull(getVoiceModelResult.Result);
Assert.IsTrue(getVoiceModelResult.Result.Name == voiceModelName);
Assert.IsTrue(getVoiceModelResult.Result.Description == voiceModelDescription);
Assert.IsNotNull(createVoiceModelResult.Result);
Assert.IsNotNull(listVoiceModelsResult.Result);
Assert.IsNotNull(listVoiceModelsResult.Result.Customizations);
}
#endregion
#region Words
[TestMethod]
public void Words_Success()
{
service.WithHeader("X-Watson-Test", "1");
var createVoiceModelResult = service.CreateCustomModel(
name: voiceModelName,
language: "en-US",
description: voiceModelDescription
);
var customizationId = createVoiceModelResult.Result.CustomizationId;
var words = new List<Word>()
{
new Word()
{
_Word = "hello",
Translation = "hullo"
},
new Word()
{
_Word = "goodbye",
Translation = "gbye"
},
new Word()
{
_Word = "hi",
Translation = "ohioooo"
}
};
service.WithHeader("X-Watson-Test", "1");
var addWordsResult = service.AddWords(
customizationId: customizationId,
words: words
);
service.WithHeader("X-Watson-Test", "1");
var listWordsResult = service.ListWords(
customizationId: customizationId
);
service.WithHeader("X-Watson-Test", "1");
var getWordResult = service.GetWord(
customizationId: customizationId,
word: "hello"
);
service.WithHeader("X-Watson-Test", "1");
var addWordResult = service.AddWord(
customizationId: customizationId,
word: "IBM",
translation: "eye bee m",
partOfSpeech: "noun"
);
service.WithHeader("X-Watson-Test", "1");
var checkAddWordResult = service.ListWords(
customizationId: customizationId
);
service.WithHeader("X-Watson-Test", "1");
var deleteWordResult = service.DeleteWord(
customizationId: customizationId,
word: "hi"
);
service.WithHeader("X-Watson-Test", "1");
var checkDeleteWordResult = service.ListWords(
customizationId: customizationId
);
service.WithHeader("X-Watson-Test", "1");
var deleteVoiceModelResult = service.DeleteCustomModel(
customizationId: customizationId
);
Assert.IsNotNull(checkDeleteWordResult.Result);
Assert.IsNotNull(checkDeleteWordResult.Result._Words);
Assert.IsTrue(checkDeleteWordResult.Result._Words.Count == 3);
Assert.IsNotNull(checkAddWordResult.Result);
Assert.IsNotNull(checkAddWordResult.Result._Words);
Assert.IsTrue(checkAddWordResult.Result._Words.Count == 4);
Assert.IsNotNull(getWordResult.Result);
Assert.IsTrue(getWordResult.Result._Translation == "hullo");
Assert.IsNotNull(listWordsResult.Result);
Assert.IsNotNull(listWordsResult.Result._Words);
Assert.IsTrue(listWordsResult.Result._Words.Count == 3);
Assert.IsNotNull(addWordsResult.Result);
}
#endregion
#region Miscellaneous
[TestMethod]
public void testListCustomPrompts()
{
service.WithHeader("X-Watson-Test", "1");
var customModel = service.CreateCustomModel(
description: "testString",
name: "testString",
language: TextToSpeechService.ListCustomModelsEnums.LanguageValue.EN_US
);
var customizationId = customModel.Result.CustomizationId;
var prompts = service.ListCustomPrompts(
customizationId: customizationId
);
Assert.IsNotNull(prompts.Result._Prompts);
service.DeleteCustomModel(
customizationId: customizationId
);
}
[TestMethod]
public void testAddCustomPrompts()
{
service.WithHeader("X-Watson-Test", "1");
string customizationId = "";
try
{
var customModel = service.CreateCustomModel(
description: "testString",
name: "testString",
language: TextToSpeechService.ListCustomModelsEnums.LanguageValue.EN_US
);
customizationId = customModel.Result.CustomizationId;
var promptMetadata = new PromptMetadata()
{
PromptText = "promptText"
};
MemoryStream file = new MemoryStream();
var prompt = service.AddCustomPrompt(
customizationId: customizationId,
promptId: "testId",
metadata: promptMetadata,
file: file
);
Assert.IsNotNull(prompt.Result.Status);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
service.DeleteCustomModel(
customizationId: customizationId
);
}
}
[TestMethod]
public void testGetCustomPrompts()
{
service.WithHeader("X-Watson-Test", "1");
string customizationId = "";
try
{
var customModel = service.CreateCustomModel(
description: "testString",
name: "testString",
language: TextToSpeechService.ListCustomModelsEnums.LanguageValue.EN_US
);
customizationId = customModel.Result.CustomizationId;
var promptMetadata = new PromptMetadata()
{
PromptText = "promptText"
};
MemoryStream file = new MemoryStream();
var prompt = service.AddCustomPrompt(
customizationId: customizationId,
promptId: "testId",
metadata: promptMetadata,
file: file
);
Assert.IsNotNull(prompt.Result.Status);
var prompt1 = service.GetCustomPrompt(
customizationId: customizationId,
promptId: "testId"
);
Assert.IsNotNull(prompt1.Result.Status);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
service.DeleteCustomModel(
customizationId: customizationId
);
}
}
[TestMethod]
public void testDeleteCustomPrompts()
{
service.WithHeader("X-Watson-Test", "1");
string customizationId = "";
try
{
var customModel = service.CreateCustomModel(
description: "testString",
name: "testString",
language: TextToSpeechService.ListCustomModelsEnums.LanguageValue.EN_US
);
customizationId = customModel.Result.CustomizationId;
var promptMetadata = new PromptMetadata()
{
PromptText = "promptText"
};
MemoryStream file = new MemoryStream();
var prompt = service.AddCustomPrompt(
customizationId: customizationId,
promptId: "testId",
metadata: promptMetadata,
file: file
);
Assert.IsNotNull(prompt.Result.Status);
var response = service.DeleteCustomPrompt(
customizationId: customizationId,
promptId: prompt.Result.PromptId
);
Assert.IsNotNull(response.Result);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
service.DeleteCustomModel(
customizationId: customizationId
);
}
}
[TestMethod]
public void testCreateSpeakerModel()
{
service.WithHeader("X-Watson-Test", "1");
string speakerId = "";
try
{
MemoryStream ms = new MemoryStream();
FileStream fs = File.OpenRead(wavFile);
fs.CopyTo(ms);
var speakerModel = service.CreateSpeakerModel(
speakerName: "speakerNameDotNet",
audio: ms
);
speakerId = speakerModel.Result.SpeakerId;
Assert.IsNotNull(speakerModel.Result.SpeakerId);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
service.DeleteSpeakerModel(
speakerId: speakerId
);
}
}
[TestMethod]
public void testListSpeakerModel()
{
service.WithHeader("X-Watson-Test", "1");
string speakerId = "";
try
{
MemoryStream ms = new MemoryStream();
FileStream fs = File.OpenRead(wavFile);
fs.CopyTo(ms);
var speakerModel = service.CreateSpeakerModel(
speakerName: "speakerNameDotNet",
audio: ms
);
speakerId = speakerModel.Result.SpeakerId;
Assert.IsNotNull(speakerModel.Result.SpeakerId);
var speakers = service.ListSpeakerModels();
Assert.IsNotNull(speakers.Result._Speakers);
Assert.IsTrue(speakers.Result._Speakers.Count > 0);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
service.DeleteSpeakerModel(
speakerId: speakerId
);
}
}
[TestMethod]
public void testGetSpeakerModel()
{
service.WithHeader("X-Watson-Test", "1");
string speakerId = "";
try
{
MemoryStream ms = new MemoryStream();
FileStream fs = File.OpenRead(wavFile);
fs.CopyTo(ms);
var speakerModel = service.CreateSpeakerModel(
speakerName: "speakerNameDotNet",
audio: ms
);
speakerId = speakerModel.Result.SpeakerId;
Assert.IsNotNull(speakerModel.Result.SpeakerId);
var response = service.GetSpeakerModel(
speakerId: speakerId
);
Assert.IsNotNull(response.Result.Customizations);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
service.DeleteSpeakerModel(
speakerId: speakerId
);
}
}
[TestMethod]
public void testDeleteSpeakerModel()
{
service.WithHeader("X-Watson-Test", "1");
MemoryStream ms = new MemoryStream();
FileStream fs = File.OpenRead(wavFile);
fs.CopyTo(ms);
var speakerModel = service.CreateSpeakerModel(
speakerName: "speakerNameDotNet",
audio: ms
);
string speakerId = speakerModel.Result.SpeakerId;
Assert.IsNotNull(speakerModel.Result.SpeakerId);
var response = service.GetSpeakerModel(
speakerId: speakerId
);
Assert.IsNotNull(response.Result.Customizations);
service.DeleteSpeakerModel(
speakerId: speakerId
);
}
#endregion
}
}
| |
// Copyright 2020 The Tilt Brush 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 UnityEngine;
using System.Collections.Generic;
namespace TiltBrush {
public class ColorTable : MonoBehaviour {
[SerializeField] private float m_SecretDistance = 1.0f;
// From http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/colors/ColorTable.htm
// Some names changed to paint-based description for clarity, string length, and to remove
// a surprising amount of insensitive names.
private Dictionary<Color32, string> m_Colors = new Dictionary<Color32, string> {
{ new Color32(240, 248, 255, 255), "Cool White" },
{ new Color32(250, 235, 215, 255), "Antique White" },
{ new Color32(127, 255, 212, 255), "Light Cyan" },
{ new Color32(240, 255, 255, 255), "White" },
{ new Color32(245, 245, 220, 255), "Beige" },
{ new Color32(255, 228, 196, 255), "Bisque" },
{ new Color32(0, 0, 0, 255), "Black" },
{ new Color32(141, 141, 141, 255), "Middle Grey" },
{ new Color32(255, 235, 205, 255), "Bone White" },
{ new Color32(0, 0, 255, 255), "Blue" },
{ new Color32(138, 43, 226, 255), "Blue Violet" },
{ new Color32(165, 42, 42, 255), "Brown" },
{ new Color32(222, 184, 135, 255), "Deep Beige" },
{ new Color32(95, 158, 160, 255), "Ash Blue" },
{ new Color32(127, 255, 0, 255), "Chartreuse" },
{ new Color32(210, 105, 30, 255), "Raw Sienna" },
{ new Color32(100, 149, 237, 255), "Cornflower Blue" },
{ new Color32(255, 248, 220, 255), "Cornsilk" },
{ new Color32(220, 20, 60, 255), "Crimson" },
{ new Color32(0, 255, 255, 255), "Cyan" },
{ new Color32(0, 0, 139, 255), "Dark Blue" },
{ new Color32(0, 139, 139, 255), "Dark Teal" },
{ new Color32(184, 134, 11, 255), "Dark Ochre" },
{ new Color32(0, 100, 0, 255), "Dark Green" },
{ new Color32(189, 183, 107, 255), "Dark Khaki" },
{ new Color32(139, 0, 139, 255), "Dark Magenta" },
{ new Color32(85, 107, 47, 255), "Dark Olive Green" },
{ new Color32(255, 140, 0, 255), "Dark Orange" },
{ new Color32(153, 50, 204, 255), "Dark Orchid" },
{ new Color32(139, 0, 0, 255), "Dark Red" },
{ new Color32(233, 150, 122, 255), "Dark Salmon" },
{ new Color32(143, 188, 139, 255), "Dark Sea Green" },
{ new Color32(72, 61, 139, 255), "Dark Slate Blue" },
{ new Color32(47, 79, 79, 255), "Neutral Grey" },
{ new Color32(0, 206, 209, 255), "Dark Turquoise" },
{ new Color32(148, 0, 211, 255), "Dark Violet" },
{ new Color32(255, 20, 147, 255), "Deep Pink" },
{ new Color32(0, 191, 255, 255), "Deep Sky Blue" },
{ new Color32(105, 105, 105, 255), "Dim Grey" },
{ new Color32(30, 144, 255, 255), "Cerulean Blue" },
{ new Color32(178, 34, 34, 255), "Carmine" },
{ new Color32(255, 250, 240, 255), "Floral White" },
{ new Color32(34, 139, 34, 255), "Forest Green" },
{ new Color32(220, 220, 220, 255), "Silver" },
{ new Color32(248, 248, 255, 255), "Ghost White" },
{ new Color32(255, 215, 0, 255), "Cadmium Yellow" },
{ new Color32(218, 165, 32, 255), "Ochre" },
{ new Color32(128, 128, 128, 255), "Grey" },
{ new Color32(0, 128, 0, 255), "Green" },
{ new Color32(173, 255, 47, 255), "Green Yellow" },
{ new Color32(240, 255, 240, 255), "Honeydew" },
{ new Color32(255, 105, 180, 255), "Hot Pink" },
{ new Color32(205, 92, 92, 255), "Red Oxide" },
{ new Color32(75, 0, 130, 255), "Indigo" },
{ new Color32(255, 255, 240, 255), "Ivory" },
{ new Color32(240, 230, 140, 255), "Khaki" },
{ new Color32(230, 230, 250, 255), "Lavender" },
{ new Color32(255, 240, 245, 255), "Pale Lavender" },
{ new Color32(124, 252, 0, 255), "Luminous Green" },
{ new Color32(255, 250, 205, 255), "Pale Lemon" },
{ new Color32(173, 216, 230, 255), "Light Blue" },
{ new Color32(240, 128, 128, 255), "Light Coral" },
{ new Color32(224, 255, 255, 255), "Light Cyan" },
{ new Color32(250, 250, 210, 255), "Pale Lime" },
{ new Color32(144, 238, 144, 255), "Light Green" },
{ new Color32(211, 211, 211, 255), "Light Grey" },
{ new Color32(255, 182, 193, 255), "Light Pink" },
{ new Color32(255, 160, 122, 255), "Light Salmon" },
{ new Color32(32, 178, 170, 255), "Light Sea Green" },
{ new Color32(135, 206, 250, 255), "Light Sky Blue" },
{ new Color32(119, 136, 153, 255), "Light Ash Blue" },
{ new Color32(176, 196, 222, 255), "Light Steel Blue" },
{ new Color32(255, 255, 224, 255), "Light Yellow" },
{ new Color32(0, 255, 0, 255), "Lime" },
{ new Color32(50, 205, 50, 255), "Lime Green" },
{ new Color32(250, 240, 230, 255), "Linen" },
{ new Color32(255, 0, 255, 255), "Magenta" },
{ new Color32(128, 0, 0, 255), "Maroon" },
{ new Color32(102, 205, 170, 255), "Medium Aquamarine" },
{ new Color32(0, 0, 205, 255), "Ultramarine" },
{ new Color32(186, 85, 211, 255), "Medium Orchid" },
{ new Color32(147, 112, 219, 255), "Medium Purple" },
{ new Color32(60, 179, 113, 255), "Medium Sea Green" },
{ new Color32(123, 104, 238, 255), "Medium Slate Blue" },
{ new Color32(0, 250, 154, 255), "Medium Spring Green" },
{ new Color32(72, 209, 204, 255), "Medium Turquoise" },
{ new Color32(199, 21, 133, 255), "Rose Voilet" },
{ new Color32(25, 25, 112, 255), "Midnight Blue" },
{ new Color32(245, 255, 250, 255), "Mint Cream" },
{ new Color32(255, 228, 225, 255), "Misty Rose" },
{ new Color32(255, 228, 181, 255), "Naples Yellow" },
{ new Color32(255, 222, 173, 255), "Titan Buff" },
{ new Color32(0, 0, 128, 255), "Navy" },
{ new Color32(253, 245, 230, 255), "Old Lace" },
{ new Color32(128, 128, 0, 255), "Olive" },
{ new Color32(107, 142, 35, 255), "Moss Green" },
{ new Color32(255, 165, 0, 255), "Orange Yellow" },
{ new Color32(255, 69, 0, 255), "Scarlet" },
{ new Color32(218, 112, 214, 255), "Orchid" },
{ new Color32(238, 232, 170, 255), "Pale Ochre" },
{ new Color32(152, 251, 152, 255), "Pale Green" },
{ new Color32(175, 238, 238, 255), "Pale Turquoise" },
{ new Color32(219, 112, 147, 255), "Pale Violet Red" },
{ new Color32(255, 239, 213, 255), "Papaya Whip" },
{ new Color32(255, 218, 185, 255), "Peach Puff" },
{ new Color32(205, 133, 63, 255), "Raw Sienna" },
{ new Color32(255, 192, 203, 255), "Pink" },
{ new Color32(221, 160, 221, 255), "Lilac" },
{ new Color32(176, 224, 230, 255), "Powder Blue" },
{ new Color32(95, 0, 128, 255), "Purple" },
{ new Color32(255, 0, 0, 255), "Red" },
{ new Color32(188, 143, 143, 255), "Rosy Brown" },
{ new Color32(65, 105, 225, 255), "Royal Blue" },
{ new Color32(139, 69, 19, 255), "Burnt Umber" },
{ new Color32(250, 128, 114, 255), "Salmon" },
{ new Color32(244, 164, 96, 255), "Sandy Brown" },
{ new Color32(46, 139, 87, 255), "Sea Green" },
{ new Color32(255, 245, 238, 255), "Seashell" },
{ new Color32(160, 82, 45, 255), "Sienna" },
{ new Color32(192, 192, 192, 255), "Silver" },
{ new Color32(135, 206, 235, 255), "Sky Blue" },
{ new Color32(106, 90, 205, 255), "Slate Blue" },
{ new Color32(112, 128, 144, 255), "Slate Grey" },
{ new Color32(255, 250, 250, 255), "Snow" },
{ new Color32(0, 255, 127, 255), "Spring Green" },
{ new Color32(70, 130, 180, 255), "Steel Blue" },
{ new Color32(210, 180, 140, 255), "Tan" },
{ new Color32(0, 128, 128, 255), "Teal" },
{ new Color32(216, 191, 216, 255), "Pale Lilac" },
{ new Color32(255, 99, 71, 255), "Tomato" },
{ new Color32(64, 224, 208, 255), "Turquoise" },
{ new Color32(238, 130, 238, 255), "Violet" },
{ new Color32(245, 222, 179, 255), "Titan" },
{ new Color32(255, 255, 255, 255), "Bright White" },
{ new Color32(245, 245, 245, 255), "White" },
{ new Color32(255, 255, 0, 255), "Yellow" },
{ new Color32(154, 205, 50, 255), "Leaf Green" },
{ new Color32(201, 104, 0, 255), "Orange" },
};
private Dictionary<Color32, string> m_SecretColors = new Dictionary<Color32, string> {
{ new Color32(27, 15, 253, 255), "Patrick's Favorite Color" },
{ new Color32(72, 9, 12, 255), "Mach's Favorite Color" },
{ new Color32(126, 71, 143, 255), "Joyce's Favorite Color" },
{ new Color32(66, 113, 120, 255), "Tim's Favorite Color" },
{ new Color32(14, 81, 53, 255), "Drew's Favorite Color" },
{ new Color32(255, 220, 202, 255), "Jeremy's Favorite Color" },
{ new Color32(16, 100, 173, 255), "Elisabeth's Favorite Color" },
{ new Color32(217, 255, 109, 255), "Ashley's Favorite Color" },
{ new Color32(255, 241, 27, 255), "Tory's Favorite Color" },
{ new Color32(29, 59, 93, 255), "Paul's Favorite Color" },
{ new Color32(238, 70, 153, 255), "Izzy's Favorite Color" },
{ new Color32(255, 127, 80, 255), "Jon's Favorite Color" },
{ new Color32(176, 25, 126, 255), "Gottlieb's Favorite Color" },
{ new Color32(11, 28, 92, 255), "Coco's Favorite Color" },
};
public static ColorTable m_Instance;
float ColorDistance(Color32 colorA, Color32 colorB) {
// From https://en.wikipedia.org/wiki/Color_difference
float deltaR = (float)(colorA.r - colorB.r);
float deltaG = (float)(colorA.g - colorB.g);
float deltaB = (float)(colorA.b - colorB.b);
float avgR = (float)(colorA.r + colorB.r) / 2.0f;
float r = (2.0f + avgR / 256.0f) * deltaR * deltaR;
float g = 4.0f * deltaG * deltaG;
float b = (2.0f + (255.0f - avgR) / 256.0f) * deltaB * deltaB;
return Mathf.Sqrt(r + g + b);
}
void Awake() {
m_Instance = this;
}
public string NearestColorTo(Color color) {
float dist = float.MaxValue;
Color32? nearestColor = null;
foreach (var col in m_SecretColors.Keys) {
float newDist = ColorDistance(col, color);
if (newDist < m_SecretDistance) {
return m_SecretColors[col];
}
}
foreach (var col in m_Colors.Keys) {
float newDist = ColorDistance(col, color);
if (newDist < dist) {
dist = newDist;
nearestColor = col;
}
}
return m_Colors[nearestColor.Value];
}
}
} // namespace TiltBrush
| |
//
// Log.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2007 Novell, Inc.
//
// 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.Text;
using System.Collections.Generic;
using System.Threading;
namespace Hyena
{
public delegate void LogNotifyHandler (LogNotifyArgs args);
public class LogNotifyArgs : EventArgs
{
private LogEntry entry;
public LogNotifyArgs (LogEntry entry)
{
this.entry = entry;
}
public LogEntry Entry {
get { return entry; }
}
}
public enum LogEntryType
{
Debug,
Warning,
Error,
Information
}
public class LogEntry
{
private LogEntryType type;
private string message;
private string details;
private DateTime timestamp;
internal LogEntry (LogEntryType type, string message, string details)
{
this.type = type;
this.message = message;
this.details = details;
this.timestamp = DateTime.Now;
}
public LogEntryType Type {
get { return type; }
}
public string Message {
get { return message; }
}
public string Details {
get { return details; }
}
public DateTime TimeStamp {
get { return timestamp; }
}
}
public static class Log
{
static Log ()
{
// On Windows, if running uninstalled, leave STDOUT alone so it's visible in the IDE,
// otherwise write it to a file so it's not lost.
if (PlatformDetection.IsWindows && !ApplicationContext.CommandLine.Contains ("uninstalled")) {
var log_path = Paths.Combine (Paths.ApplicationData, "banshee.log");
Console.WriteLine ("Logging to {0}", log_path);
try {
var log_writer = new System.IO.StreamWriter (log_path, false);
log_writer.AutoFlush = true;
Console.SetOut (log_writer);
} catch (Exception ex) {
Console.Error.WriteLine ("Unable to log to {0}: {1}", log_path, ex);
}
}
}
public static event LogNotifyHandler Notify;
private static Dictionary<uint, DateTime> timers = new Dictionary<uint, DateTime> ();
private static uint next_timer_id = 1;
private static bool debugging = false;
public static bool Debugging {
get { return debugging; }
set { debugging = value; }
}
public static void Commit (LogEntryType type, string message, string details, bool showUser)
{
if (type == LogEntryType.Debug && !Debugging) {
return;
}
if (type != LogEntryType.Information || (type == LogEntryType.Information && !showUser)) {
switch (type) {
case LogEntryType.Error: ConsoleCrayon.ForegroundColor = ConsoleColor.Red; break;
case LogEntryType.Warning: ConsoleCrayon.ForegroundColor = ConsoleColor.DarkYellow; break;
case LogEntryType.Information: ConsoleCrayon.ForegroundColor = ConsoleColor.Green; break;
case LogEntryType.Debug: ConsoleCrayon.ForegroundColor = ConsoleColor.Blue; break;
}
var thread_name = String.Empty;
if (Debugging) {
var thread = Thread.CurrentThread;
thread_name = String.Format ("{0} ", thread.ManagedThreadId);
}
Console.Write ("[{5}{0} {1:00}:{2:00}:{3:00}.{4:000}]", TypeString (type), DateTime.Now.Hour,
DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond, thread_name);
ConsoleCrayon.ResetColor ();
if (details != null) {
Console.WriteLine (" {0} - {1}", message, details);
} else {
Console.WriteLine (" {0}", message);
}
}
if (showUser) {
OnNotify (new LogEntry (type, message, details));
}
}
private static string TypeString (LogEntryType type)
{
switch (type) {
case LogEntryType.Debug: return "Debug";
case LogEntryType.Warning: return "Warn ";
case LogEntryType.Error: return "Error";
case LogEntryType.Information: return "Info ";
}
return null;
}
private static void OnNotify (LogEntry entry)
{
LogNotifyHandler handler = Notify;
if (handler != null) {
handler (new LogNotifyArgs (entry));
}
}
#region Timer Methods
public static uint DebugTimerStart (string message)
{
return TimerStart (message, false);
}
public static uint InformationTimerStart (string message)
{
return TimerStart (message, true);
}
private static uint TimerStart (string message, bool isInfo)
{
if (!Debugging && !isInfo) {
return 0;
}
if (isInfo) {
Information (message);
} else {
Debug (message);
}
return TimerStart (isInfo);
}
public static uint DebugTimerStart ()
{
return TimerStart (false);
}
public static uint InformationTimerStart ()
{
return TimerStart (true);
}
private static uint TimerStart (bool isInfo)
{
if (!Debugging && !isInfo) {
return 0;
}
uint timer_id = next_timer_id++;
timers.Add (timer_id, DateTime.Now);
return timer_id;
}
public static void DebugTimerPrint (uint id)
{
if (!Debugging) {
return;
}
TimerPrint (id, "Operation duration: {0}", false);
}
public static void DebugTimerPrint (uint id, string message)
{
if (!Debugging) {
return;
}
TimerPrint (id, message, false);
}
public static void InformationTimerPrint (uint id)
{
TimerPrint (id, "Operation duration: {0}", true);
}
public static void InformationTimerPrint (uint id, string message)
{
TimerPrint (id, message, true);
}
private static void TimerPrint (uint id, string message, bool isInfo)
{
if (!Debugging && !isInfo) {
return;
}
DateTime finish = DateTime.Now;
if (!timers.ContainsKey (id)) {
return;
}
TimeSpan duration = finish - timers[id];
string d_message;
if (duration.TotalSeconds < 60) {
d_message = duration.TotalSeconds.ToString ();
} else {
d_message = duration.ToString ();
}
if (isInfo) {
InformationFormat (message, d_message);
} else {
DebugFormat (message, d_message);
}
}
#endregion
#region Public Debug Methods
public static void Debug (string message, string details)
{
if (Debugging) {
Commit (LogEntryType.Debug, message, details, false);
}
}
public static void Debug (string message)
{
if (Debugging) {
Debug (message, null);
}
}
public static void DebugFormat (string format, params object [] args)
{
if (Debugging) {
Debug (String.Format (format, args));
}
}
#endregion
#region Public Information Methods
public static void Information (string message)
{
Information (message, null);
}
public static void Information (string message, string details)
{
Information (message, details, false);
}
public static void Information (string message, string details, bool showUser)
{
Commit (LogEntryType.Information, message, details, showUser);
}
public static void Information (string message, bool showUser)
{
Information (message, null, showUser);
}
public static void InformationFormat (string format, params object [] args)
{
Information (String.Format (format, args));
}
#endregion
#region Public Warning Methods
public static void Warning (string message)
{
Warning (message, null);
}
public static void Warning (string message, string details)
{
Warning (message, details, false);
}
public static void Warning (string message, string details, bool showUser)
{
Commit (LogEntryType.Warning, message, details, showUser);
}
public static void Warning (string message, bool showUser)
{
Warning (message, null, showUser);
}
public static void WarningFormat (string format, params object [] args)
{
Warning (String.Format (format, args));
}
#endregion
#region Public Error Methods
public static void Error (string message)
{
Error (message, null);
}
public static void Error (string message, string details)
{
Error (message, details, false);
}
public static void Error (string message, string details, bool showUser)
{
Commit (LogEntryType.Error, message, details, showUser);
}
public static void Error (string message, bool showUser)
{
Error (message, null, showUser);
}
public static void ErrorFormat (string format, params object [] args)
{
Error (String.Format (format, args));
}
#endregion
#region Public Exception Methods
public static void DebugException (Exception e)
{
if (Debugging) {
Exception (e);
}
}
public static void Exception (Exception e)
{
Exception (null, e);
}
public static void Exception (string message, Exception e)
{
Stack<Exception> exception_chain = new Stack<Exception> ();
StringBuilder builder = new StringBuilder ();
while (e != null) {
exception_chain.Push (e);
e = e.InnerException;
}
while (exception_chain.Count > 0) {
e = exception_chain.Pop ();
builder.AppendFormat ("{0}: {1} (in `{2}')", e.GetType (), e.Message, e.Source).AppendLine ();
builder.Append (e.StackTrace);
if (exception_chain.Count > 0) {
builder.AppendLine ();
}
}
Log.Warning (message ?? "Caught an exception", builder.ToString (), false);
}
#endregion
}
}
| |
/*
*
* 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 Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Queries;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Tests.Queries
{
public class CommonTermsQueryTest : LuceneTestCase
{
[Test]
public void TestBasics()
{
Directory dir = NewDirectory();
MockAnalyzer analyzer = new MockAnalyzer(Random);
RandomIndexWriter w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir, analyzer);
var docs = new string[]
{
@"this is the end of the world right", @"is this it or maybe not",
@"this is the end of the universe as we know it",
@"there is the famous restaurant at the end of the universe"
};
for (int i = 0; i < docs.Length; i++)
{
Document doc = new Document();
doc.Add(NewStringField(@"id", @"" + i, Field.Store.YES));
doc.Add(NewTextField(@"field", docs[i], Field.Store.NO));
w.AddDocument(doc);
}
IndexReader r = w.GetReader();
IndexSearcher s = NewSearcher(r);
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
query.Add(new Term("field", "universe"));
query.Add(new Term("field", "right"));
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 3);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
assertEquals(@"2", r.Document(search.ScoreDocs[1].Doc).Get(@"id"));
assertEquals(@"3", r.Document(search.ScoreDocs[2].Doc).Get(@"id"));
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 2);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
assertEquals(@"2", r.Document(search.ScoreDocs[1].Doc).Get(@"id"));
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.MUST, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 1);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.MUST, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "restaurant"));
query.Add(new Term("field", "universe"));
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 1);
assertEquals(@"3", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
}
r.Dispose();
w.Dispose();
dir.Dispose();
}
[Test]
public void TestEqualsHashCode()
{
CommonTermsQuery query = new CommonTermsQuery(RandomOccur(Random), RandomOccur(Random), Random.NextSingle(), Random.NextBoolean());
int terms = AtLeast(2);
for (int i = 0; i < terms; i++)
{
query.Add(new Term(TestUtil.RandomRealisticUnicodeString(Random), TestUtil.RandomRealisticUnicodeString(Random)));
}
QueryUtils.CheckHashEquals(query);
QueryUtils.CheckUnequal(new CommonTermsQuery(RandomOccur(Random), RandomOccur(Random), Random.NextSingle(), Random.NextBoolean()), query);
{
long seed = Random.NextInt64();
Random r = new Random((int)seed);
CommonTermsQuery left = new CommonTermsQuery(RandomOccur(r), RandomOccur(r), r.NextSingle(), r.NextBoolean());
int leftTerms = AtLeast(r, 2);
for (int i = 0; i < leftTerms; i++)
{
left.Add(new Term(TestUtil.RandomRealisticUnicodeString(r), TestUtil.RandomRealisticUnicodeString(r)));
}
left.HighFreqMinimumNumberShouldMatch = r.nextInt(4);
left.LowFreqMinimumNumberShouldMatch = r.nextInt(4);
r = new Random((int)seed);
CommonTermsQuery right = new CommonTermsQuery(RandomOccur(r), RandomOccur(r), r.NextSingle(), r.NextBoolean());
int rightTerms = AtLeast(r, 2);
for (int i = 0; i < rightTerms; i++)
{
right.Add(new Term(TestUtil.RandomRealisticUnicodeString(r), TestUtil.RandomRealisticUnicodeString(r)));
}
right.HighFreqMinimumNumberShouldMatch = r.nextInt(4);
right.LowFreqMinimumNumberShouldMatch = r.nextInt(4);
QueryUtils.CheckEqual(left, right);
}
}
private static Occur RandomOccur(Random random)
{
return random.NextBoolean() ? Occur.MUST : Occur.SHOULD;
}
[Test]
public void TestNullTerm()
{
Random random = Random;
CommonTermsQuery query = new CommonTermsQuery(RandomOccur(random), RandomOccur(random), Random.NextSingle());
try
{
query.Add(null);
Assert.Fail(@"null values are not supported");
}
#pragma warning disable 168
catch (ArgumentException ex)
#pragma warning restore 168
{
}
}
[Test]
public void TestMinShouldMatch()
{
Directory dir = NewDirectory();
MockAnalyzer analyzer = new MockAnalyzer(Random);
RandomIndexWriter w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir, analyzer);
string[] docs = new string[]
{
@"this is the end of the world right", @"is this it or maybe not",
@"this is the end of the universe as we know it",
@"there is the famous restaurant at the end of the universe"
};
for (int i = 0; i < docs.Length; i++)
{
Document doc = new Document();
doc.Add(NewStringField(@"id", @"" + i, Field.Store.YES));
doc.Add(NewTextField(@"field", docs[i], Field.Store.NO));
w.AddDocument(doc);
}
IndexReader r = w.GetReader();
IndexSearcher s = NewSearcher(r);
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
query.Add(new Term("field", "universe"));
query.Add(new Term("field", "right"));
query.LowFreqMinimumNumberShouldMatch = 0.5F;
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 1);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
query.Add(new Term("field", "universe"));
query.Add(new Term("field", "right"));
query.LowFreqMinimumNumberShouldMatch = 2F;
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 1);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
query.Add(new Term("field", "universe"));
query.Add(new Term("field", "right"));
query.LowFreqMinimumNumberShouldMatch = 0.49F;
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 3);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
assertEquals(@"2", r.Document(search.ScoreDocs[1].Doc).Get(@"id"));
assertEquals(@"3", r.Document(search.ScoreDocs[2].Doc).Get(@"id"));
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
query.Add(new Term("field", "universe"));
query.Add(new Term("field", "right"));
query.LowFreqMinimumNumberShouldMatch = 1F;
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 3);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
assertEquals(@"2", r.Document(search.ScoreDocs[1].Doc).Get(@"id"));
assertEquals(@"3", r.Document(search.ScoreDocs[2].Doc).Get(@"id"));
assertTrue(search.ScoreDocs[1].Score > search.ScoreDocs[2].Score);
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
query.Add(new Term("field", "universe"));
query.Add(new Term("field", "right"));
query.LowFreqMinimumNumberShouldMatch = 1F;
query.HighFreqMinimumNumberShouldMatch = 4F;
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 3);
assertEquals(search.ScoreDocs[1].Score, search.ScoreDocs[2].Score, 0F);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
assertEquals(
new JCG.HashSet<string> { @"2", @"3" },
new JCG.HashSet<string> { r.Document(search.ScoreDocs[1].Doc).Get(@"id"), r.Document(search.ScoreDocs[2].Doc).Get(@"id") },
aggressive: false);
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "the"));
query.LowFreqMinimumNumberShouldMatch = 1F;
query.HighFreqMinimumNumberShouldMatch = 2F;
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 4);
}
{
CommonTermsQuery query = new CommonTermsQuery(Occur.MUST, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "the"));
query.LowFreqMinimumNumberShouldMatch = 1F;
query.HighFreqMinimumNumberShouldMatch = 2F;
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 2);
assertEquals(
new JCG.HashSet<string> { @"0", @"2" },
new JCG.HashSet<string> { r.Document(search.ScoreDocs[0].Doc).Get(@"id"), r.Document(search.ScoreDocs[1].Doc).Get(@"id") },
aggressive: false);
}
r.Dispose();
w.Dispose();
dir.Dispose();
}
[Test]
public void TestIllegalOccur()
{
Random random = Random;
try
{
new CommonTermsQuery(Occur.MUST_NOT, RandomOccur(random), Random.NextSingle());
Assert.Fail(@"MUST_NOT is not supproted");
}
#pragma warning disable 168
catch (ArgumentException ex)
#pragma warning restore 168
{
}
try
{
new CommonTermsQuery(RandomOccur(random), Occur.MUST_NOT, Random.NextSingle());
Assert.Fail(@"MUST_NOT is not supproted");
}
#pragma warning disable 168
catch (ArgumentException ex)
#pragma warning restore 168
{
}
}
[Test]
public void TestExtend()
{
Directory dir = NewDirectory();
MockAnalyzer analyzer = new MockAnalyzer(Random);
RandomIndexWriter w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir, analyzer);
var docs = new string[]
{
@"this is the end of the world right", @"is this it or maybe not",
@"this is the end of the universe as we know it",
@"there is the famous restaurant at the end of the universe"
};
for (int i = 0; i < docs.Length; i++)
{
Document doc = new Document();
doc.Add(NewStringField(@"id", @"" + i, Field.Store.YES));
doc.Add(NewTextField(@"field", docs[i], Field.Store.NO));
w.AddDocument(doc);
}
IndexReader r = w.GetReader();
IndexSearcher s = NewSearcher(r);
{
CommonTermsQuery query = new CommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
query.Add(new Term("field", "universe"));
query.Add(new Term("field", "right"));
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 3);
assertEquals(@"0", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
assertEquals(@"2", r.Document(search.ScoreDocs[1].Doc).Get(@"id"));
assertEquals(@"3", r.Document(search.ScoreDocs[2].Doc).Get(@"id"));
}
{
CommonTermsQuery query = new ExtendedCommonTermsQuery(Occur.SHOULD, Occur.SHOULD, Random.NextBoolean() ? 2F : 0.5F);
query.Add(new Term("field", "is"));
query.Add(new Term("field", "this"));
query.Add(new Term("field", "end"));
query.Add(new Term("field", "world"));
query.Add(new Term("field", "universe"));
query.Add(new Term("field", "right"));
TopDocs search = s.Search(query, 10);
assertEquals(search.TotalHits, 3);
assertEquals(@"2", r.Document(search.ScoreDocs[0].Doc).Get(@"id"));
assertEquals(@"3", r.Document(search.ScoreDocs[1].Doc).Get(@"id"));
assertEquals(@"0", r.Document(search.ScoreDocs[2].Doc).Get(@"id"));
}
r.Dispose();
w.Dispose();
dir.Dispose();
}
[Test]
public void TestRandomIndex()
{
Directory dir = NewDirectory();
MockAnalyzer analyzer = new MockAnalyzer(Random);
analyzer.MaxTokenLength = TestUtil.NextInt32(Random, 1, IndexWriter.MAX_TERM_LENGTH);
RandomIndexWriter w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir, analyzer);
CreateRandomIndex(AtLeast(50), w, Random.NextInt64());
DirectoryReader reader = w.GetReader();
AtomicReader wrapper = SlowCompositeReaderWrapper.Wrap(reader);
string field = @"body";
Terms terms = wrapper.GetTerms(field);
var lowFreqQueue = new AnonymousPriorityQueue(this, 5);
Util.PriorityQueue<TermAndFreq> highFreqQueue = new AnonymousPriorityQueue1(this, 5);
try
{
TermsEnum iterator = terms.GetEnumerator();
while (iterator.MoveNext())
{
if (highFreqQueue.Count < 5)
{
highFreqQueue.Add(new TermAndFreq(BytesRef.DeepCopyOf(iterator.Term), iterator.DocFreq));
lowFreqQueue.Add(new TermAndFreq(BytesRef.DeepCopyOf(iterator.Term), iterator.DocFreq));
}
else
{
if (highFreqQueue.Top.freq < iterator.DocFreq)
{
highFreqQueue.Top.freq = iterator.DocFreq;
highFreqQueue.Top.term = BytesRef.DeepCopyOf(iterator.Term);
highFreqQueue.UpdateTop();
}
if (lowFreqQueue.Top.freq > iterator.DocFreq)
{
lowFreqQueue.Top.freq = iterator.DocFreq;
lowFreqQueue.Top.term = BytesRef.DeepCopyOf(iterator.Term);
lowFreqQueue.UpdateTop();
}
}
}
int lowFreq = lowFreqQueue.Top.freq;
int highFreq = highFreqQueue.Top.freq;
AssumeTrue(@"unlucky index", highFreq - 1 > lowFreq);
List<TermAndFreq> highTerms = QueueToList(highFreqQueue);
List<TermAndFreq> lowTerms = QueueToList(lowFreqQueue);
IndexSearcher searcher = NewSearcher(reader);
Occur lowFreqOccur = RandomOccur(Random);
BooleanQuery verifyQuery = new BooleanQuery();
CommonTermsQuery cq = new CommonTermsQuery(RandomOccur(Random), lowFreqOccur, highFreq - 1, Random.NextBoolean());
foreach (TermAndFreq termAndFreq in lowTerms)
{
cq.Add(new Term(field, termAndFreq.term));
verifyQuery.Add(new BooleanClause(new TermQuery(new Term(field, termAndFreq.term)), lowFreqOccur));
}
foreach (TermAndFreq termAndFreq in highTerms)
{
cq.Add(new Term(field, termAndFreq.term));
}
TopDocs cqSearch = searcher.Search(cq, reader.MaxDoc);
TopDocs verifySearch = searcher.Search(verifyQuery, reader.MaxDoc);
assertEquals(verifySearch.TotalHits, cqSearch.TotalHits);
var hits = new JCG.HashSet<int>();
foreach (ScoreDoc doc in verifySearch.ScoreDocs)
{
hits.Add(doc.Doc);
}
foreach (ScoreDoc doc in cqSearch.ScoreDocs)
{
assertTrue(hits.Remove(doc.Doc));
}
assertTrue(hits.Count == 0);
w.ForceMerge(1);
DirectoryReader reader2 = w.GetReader();
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, cq, NewSearcher(reader2));
reader2.Dispose();
}
finally
{
reader.Dispose();
wrapper.Dispose();
w.Dispose();
dir.Dispose();
}
}
private sealed class AnonymousPriorityQueue : Util.PriorityQueue<TermAndFreq>
{
public AnonymousPriorityQueue(CommonTermsQueryTest parent, int maxSize)
: base(maxSize)
{
this.parent = parent;
}
private readonly CommonTermsQueryTest parent;
protected internal override bool LessThan(TermAndFreq a, TermAndFreq b)
{
return a.freq > b.freq;
}
}
private sealed class AnonymousPriorityQueue1 : Util.PriorityQueue<TermAndFreq>
{
public AnonymousPriorityQueue1(CommonTermsQueryTest parent, int maxSize)
: base(maxSize)
{
this.parent = parent;
}
private readonly CommonTermsQueryTest parent;
protected internal override bool LessThan(TermAndFreq a, TermAndFreq b)
{
return a.freq < b.freq;
}
}
private static List<TermAndFreq> QueueToList(Util.PriorityQueue<TermAndFreq> queue)
{
var terms = new List<TermAndFreq>();
while (queue.Count > 0)
{
terms.Add(queue.Pop());
}
return terms;
}
private class TermAndFreq : IComparable<TermAndFreq>
{
public BytesRef term;
public int freq;
public TermAndFreq(BytesRef term, int freq)
{
this.term = term;
this.freq = freq;
}
public int CompareTo(TermAndFreq other)
{
return term.CompareTo(other.term) + freq.CompareTo(other.freq);
}
}
public static void CreateRandomIndex(int numdocs, RandomIndexWriter writer, long seed)
{
Random random = new Random((int)seed);
// primary source for our data is from linefiledocs, its realistic.
LineFileDocs lineFileDocs = new LineFileDocs(random, false); // no docvalues in 4x
for (int i = 0; i < numdocs; i++)
{
writer.AddDocument(lineFileDocs.NextDoc());
}
lineFileDocs.Dispose();
}
private sealed class ExtendedCommonTermsQuery : CommonTermsQuery
{
public ExtendedCommonTermsQuery(Occur highFreqOccur, Occur lowFreqOccur, float maxTermFrequency)
: base(highFreqOccur, lowFreqOccur, maxTermFrequency)
{
}
protected override Query NewTermQuery(Term term, TermContext context)
{
Query query = base.NewTermQuery(term, context);
if (term.Text().Equals(@"universe", StringComparison.Ordinal))
{
query.Boost = 100F;
}
return query;
}
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cassandra.MetadataHelpers
{
internal class NetworkTopologyStrategy : IReplicationStrategy, IEquatable<NetworkTopologyStrategy>
{
private readonly SortedSet<DatacenterReplicationFactor> _replicationFactorsSet;
private readonly IReadOnlyDictionary<string, ReplicationFactor> _replicationFactorsMap;
private readonly int _hashCode;
public NetworkTopologyStrategy(IReadOnlyDictionary<string, ReplicationFactor> replicationFactors)
{
_replicationFactorsSet = new SortedSet<DatacenterReplicationFactor>(
replicationFactors.Select(rf => new DatacenterReplicationFactor(rf.Key, rf.Value)));
_replicationFactorsMap = replicationFactors;
_hashCode = NetworkTopologyStrategy.ComputeHashCode(_replicationFactorsSet);
}
public Dictionary<IToken, ISet<Host>> ComputeTokenToReplicaMap(
IReadOnlyList<IToken> ring,
IReadOnlyDictionary<IToken, Host> primaryReplicas,
int numberOfHostsWithTokens,
IReadOnlyDictionary<string, DatacenterInfo> datacenters)
{
return ComputeTokenToReplicaNetwork(ring, primaryReplicas, datacenters);
}
public override bool Equals(object obj)
{
return Equals(obj as NetworkTopologyStrategy);
}
public bool Equals(IReplicationStrategy other)
{
return Equals(other as NetworkTopologyStrategy);
}
public bool Equals(NetworkTopologyStrategy other)
{
return other != null && _replicationFactorsSet.SetEquals(other._replicationFactorsSet);
}
private static int ComputeHashCode(IEnumerable<DatacenterReplicationFactor> replicationFactorsSet)
{
return Utils.CombineHashCode(replicationFactorsSet);
}
public override int GetHashCode()
{
return _hashCode;
}
private Dictionary<IToken, ISet<Host>> ComputeTokenToReplicaNetwork(
IReadOnlyList<IToken> ring,
IReadOnlyDictionary<IToken, Host> primaryReplicas,
IReadOnlyDictionary<string, DatacenterInfo> datacenters)
{
var replicas = new Dictionary<IToken, ISet<Host>>();
for (var i = 0; i < ring.Count; i++)
{
var token = ring[i];
replicas[token] = ComputeReplicasForToken(ring, primaryReplicas, datacenters, i);
}
return replicas;
}
private ISet<Host> ComputeReplicasForToken(
IReadOnlyList<IToken> ring,
IReadOnlyDictionary<IToken, Host> primaryReplicas,
IReadOnlyDictionary<string, DatacenterInfo> datacenters,
int i)
{
var context = new NetworkTopologyTokenMapContext(ring, primaryReplicas, datacenters);
for (var j = 0; j < ring.Count; j++)
{
// wrap around if necessary
var replicaIndex = (i + j) % ring.Count;
var replica = primaryReplicas[ring[replicaIndex]];
var dc = replica.Datacenter;
if (!_replicationFactorsMap.TryGetValue(dc, out var dcRfObj))
{
continue;
}
var dcRf = Math.Min(dcRfObj.FullReplicas, datacenters[dc].HostLength);
context.ReplicasByDc.TryGetValue(dc, out var dcAddedReplicas);
if (dcAddedReplicas >= dcRf)
{
// replication factor for the datacenter has already been satisfied
continue;
}
var racksAddedInDc = NetworkTopologyStrategy.GetAddedRacksInDatacenter(context, dc);
if (NetworkTopologyStrategy.ShouldSkipHost(context, replica, racksAddedInDc))
{
NetworkTopologyStrategy.TryAddToSkippedHostsCollection(context, replica, dcRf, dcAddedReplicas);
continue;
}
NetworkTopologyStrategy.AddReplica(context, replica, dcRf, dcAddedReplicas, racksAddedInDc);
if (NetworkTopologyStrategy.AreReplicationFactorsSatisfied(_replicationFactorsMap, context.ReplicasByDc, datacenters))
{
break;
}
}
return context.TokenReplicas;
}
/// <summary>
/// Get collection that contains the already added racks in the provided datacenter (<paramref name="dc"/>).
/// If there's no such collection for the specified datacenter, then create one.
/// </summary>
private static HashSet<string> GetAddedRacksInDatacenter(NetworkTopologyTokenMapContext context, string dc)
{
if (!context.RacksAdded.TryGetValue(dc, out var racksAddedInDc))
{
context.RacksAdded[dc] = racksAddedInDc = new HashSet<string>();
}
return racksAddedInDc;
}
/// <summary>
/// Checks whether the host <paramref name="h"/> should be skipped.
/// </summary>
private static bool ShouldSkipHost(NetworkTopologyTokenMapContext context, Host h, HashSet<string> racksPlacedInDc)
{
var replicaForRackAlreadySelected = h.Rack != null && racksPlacedInDc.Contains(h.Rack);
var racksMissing = racksPlacedInDc.Count < context.Datacenters[h.Datacenter].Racks.Count;
return replicaForRackAlreadySelected && racksMissing;
}
/// <summary>
/// This method doesn't guarantee that the host will be added to the skipped hosts collection.
/// It will depend on whether the collection already has enough hosts to satisfy the replication factor for the host's datacenter.
/// </summary>
private static void TryAddToSkippedHostsCollection(NetworkTopologyTokenMapContext context, Host h, int dcRf, int dcAddedReplicas)
{
// We already added a replica for this rack, skip until replicas in other racks are added
var remainingReplicasNeededToSatisfyRf = dcRf - dcAddedReplicas;
if (context.SkippedHosts.Count < remainingReplicasNeededToSatisfyRf)
{
// these replicas will be added in the end after a replica has been selected for every rack
context.SkippedHosts.Add(h);
}
}
/// <summary>
/// Adds replica (<paramref name="host"/>) to <see cref="NetworkTopologyTokenMapContext.TokenReplicas"/> of <paramref name="context"/>
/// and adds skipped hosts if a replica has been added to every rack in datacenter the host's datacenter.
/// </summary>
private static void AddReplica(NetworkTopologyTokenMapContext context, Host host, int dcRf, int dcAddedReplicas, HashSet<string> racksPlacedInDc)
{
var dc = host.Datacenter;
if (context.TokenReplicas.Add(host))
{
dcAddedReplicas++;
}
context.ReplicasByDc[dc] = dcAddedReplicas;
var rackAdded = host.Rack != null && racksPlacedInDc.Add(host.Rack);
var allRacksPlacedInDc = racksPlacedInDc.Count == context.Datacenters[dc].Racks.Count;
if (rackAdded && allRacksPlacedInDc)
{
// We finished placing all replicas for all racks in this dc, add the skipped hosts
context.ReplicasByDc[dc] += NetworkTopologyStrategy.AddSkippedHosts(context, dc, dcRf, dcAddedReplicas);
}
}
/// <summary>
/// Checks if <paramref name="replicasByDc"/> has enough replicas for each datacenter considering the datacenter's replication factor.
/// </summary>
internal static bool AreReplicationFactorsSatisfied(
IReadOnlyDictionary<string, ReplicationFactor> replicationFactors,
IDictionary<string, int> replicasByDc,
IReadOnlyDictionary<string, DatacenterInfo> datacenters)
{
foreach (var dcName in replicationFactors.Keys)
{
if (!datacenters.TryGetValue(dcName, out var dc))
{
// A DC is included in the RF but the DC does not exist in the topology
continue;
}
var rf = Math.Min(replicationFactors[dcName].FullReplicas, dc.HostLength);
if (rf > 0 && (!replicasByDc.ContainsKey(dcName) || replicasByDc[dcName] < rf))
{
return false;
}
}
return true;
}
/// <summary>
/// Add replicas that were skipped before to satisfy replication factor
/// </summary>
/// <returns>Number of replicas added to <see cref="NetworkTopologyTokenMapContext.TokenReplicas"/> of <paramref name="context"/></returns>
private static int AddSkippedHosts(NetworkTopologyTokenMapContext context, string dc, int dcRf, int dcReplicas)
{
var counter = 0;
var length = dcRf - dcReplicas;
foreach (var h in context.SkippedHosts.Where(h => h.Datacenter == dc))
{
context.TokenReplicas.Add(h);
if (++counter == length)
{
break;
}
}
return counter;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Orleans application configuration parameters.
/// </summary>
[Serializable]
public class ApplicationConfiguration
{
private readonly Dictionary<string, GrainTypeConfiguration> classSpecific;
private GrainTypeConfiguration defaults;
/// <summary>
/// The default time period used to collect in-active activations.
/// Applies to all grain types.
/// </summary>
public TimeSpan DefaultCollectionAgeLimit
{
get { return defaults.CollectionAgeLimit.HasValue ? defaults.CollectionAgeLimit.Value : GlobalConfiguration.DEFAULT_COLLECTION_AGE_LIMIT; }
}
internal TimeSpan ShortestCollectionAgeLimit
{
get
{
TimeSpan shortest = DefaultCollectionAgeLimit;
foreach (var typeConfig in ClassSpecific)
{
TimeSpan curr = typeConfig.CollectionAgeLimit.Value;
if (curr < shortest)
{
shortest = curr;
}
}
return shortest;
}
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="defaultCollectionAgeLimit">The default time period used to collect in-active activations.</param>
public ApplicationConfiguration(TimeSpan? defaultCollectionAgeLimit = null)
{
classSpecific = new Dictionary<string, GrainTypeConfiguration>();
defaults = new GrainTypeConfiguration(null, defaultCollectionAgeLimit);
}
/// <summary>
/// IEnumerable of all configurations for different grain types.
/// </summary>
public IEnumerable<GrainTypeConfiguration> ClassSpecific { get { return classSpecific.Values; } }
/// <summary>
/// Load this configuratin from xml element.
/// </summary>
/// <param name="xmlElement"></param>
public void Load(XmlElement xmlElement)
{
bool found = false;
foreach (XmlNode node in xmlElement.ChildNodes)
{
found = true;
var config = GrainTypeConfiguration.Load((XmlElement)node);
if (null == config) continue;
if (config.AreDefaults)
{
defaults = config;
}
else
{
if (classSpecific.ContainsKey(config.FullTypeName))
{
throw new InvalidOperationException(string.Format("duplicate type {0} in configuration", config.FullTypeName));
}
classSpecific.Add(config.FullTypeName, config);
}
}
if (!found)
{
throw new InvalidOperationException("empty GrainTypeConfiguration element");
}
}
/// <summary>
/// Returns the time period used to collect in-active activations of a given type.
/// </summary>
/// <param name="type">Grain type.</param>
/// <returns></returns>
public TimeSpan GetCollectionAgeLimit(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
return GetCollectionAgeLimit(type.FullName);
}
/// <summary>
/// Returns the time period used to collect in-active activations of a given type.
/// </summary>
/// <param name="grainTypeFullName">Grain type full name.</param>
/// <returns></returns>
public TimeSpan GetCollectionAgeLimit(string grainTypeFullName)
{
if (String.IsNullOrEmpty(grainTypeFullName))
{
throw new ArgumentNullException("grainTypeFullName");
}
GrainTypeConfiguration config;
return classSpecific.TryGetValue(grainTypeFullName, out config) && config.CollectionAgeLimit.HasValue ?
config.CollectionAgeLimit.Value : DefaultCollectionAgeLimit;
}
/// <summary>
/// Sets the time period to collect in-active activations for a given type.
/// </summary>
/// <param name="type">Grain type full name.</param>
/// <param name="ageLimit">The age limit to use.</param>
public void SetCollectionAgeLimit(Type type, TimeSpan ageLimit)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
SetCollectionAgeLimit(type.FullName, ageLimit);
}
/// <summary>
/// Sets the time period to collect in-active activations for a given type.
/// </summary>
/// <param name="grainTypeFullName">Grain type full name string.</param>
/// <param name="ageLimit">The age limit to use.</param>
public void SetCollectionAgeLimit(string grainTypeFullName, TimeSpan ageLimit)
{
if (String.IsNullOrEmpty(grainTypeFullName))
{
throw new ArgumentNullException("grainTypeFullName");
}
ThrowIfLessThanZero(ageLimit, "ageLimit");
GrainTypeConfiguration config;
if (!classSpecific.TryGetValue(grainTypeFullName, out config))
{
config = new GrainTypeConfiguration(grainTypeFullName);
classSpecific[grainTypeFullName] = config;
}
config.SetCollectionAgeLimit(ageLimit);
}
/// <summary>
/// Resets the time period to collect in-active activations for a given type to a default value.
/// </summary>
/// <param name="type">Grain type full name.</param>
public void ResetCollectionAgeLimitToDefault(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
ResetCollectionAgeLimitToDefault(type.FullName);
}
/// <summary>
/// Resets the time period to collect in-active activations for a given type to a default value.
/// </summary>
/// <param name="grainTypeFullName">Grain type full name.</param>
public void ResetCollectionAgeLimitToDefault(string grainTypeFullName)
{
if (String.IsNullOrEmpty(grainTypeFullName))
{
throw new ArgumentNullException(nameof(grainTypeFullName));
}
GrainTypeConfiguration config;
if (!classSpecific.TryGetValue(grainTypeFullName, out config)) return;
config.SetCollectionAgeLimit(null);
}
/// <summary>
/// Sets the default time period to collect in-active activations for all grain type.
/// </summary>
/// <param name="ageLimit">The age limit to use.</param>
public void SetDefaultCollectionAgeLimit(TimeSpan ageLimit)
{
ThrowIfLessThanZero(ageLimit, "ageLimit");
defaults.SetCollectionAgeLimit(ageLimit);
}
private static void ThrowIfLessThanZero(TimeSpan timeSpan, string paramName)
{
if (timeSpan < TimeSpan.Zero) throw new ArgumentOutOfRangeException(paramName);
}
internal void ValidateConfiguration(Logger logger)
{
foreach (GrainTypeConfiguration config in classSpecific.Values)
{
config.ValidateConfiguration(logger);
}
}
/// <summary>
/// Prints the current application configuration.
/// </summary>
/// <returns></returns>
public override string ToString()
{
var result = new StringBuilder();
result.AppendFormat(" Application:").AppendLine();
result.AppendFormat(" Defaults:").AppendLine();
result.AppendFormat(" Deactivate if idle for: {0}", DefaultCollectionAgeLimit)
.AppendLine();
foreach (GrainTypeConfiguration config in classSpecific.Values)
{
if (!config.CollectionAgeLimit.HasValue) continue;
result.AppendFormat(" GrainType Type=\"{0}\":", config.FullTypeName)
.AppendLine();
result.AppendFormat(" Deactivate if idle for: {0} seconds", (long)config.CollectionAgeLimit.Value.TotalSeconds)
.AppendLine();
}
return result.ToString();
}
}
/// <summary>
/// Grain type specific application configuration.
/// </summary>
[Serializable]
public class GrainTypeConfiguration
{
/// <summary>
/// The type of the grain of this configuration.
/// </summary>
public string FullTypeName { get; private set; }
/// <summary>
/// Whether this is a defualt configuration that applies to all grain types.
/// </summary>
public bool AreDefaults { get { return FullTypeName == null; } }
/// <summary>
/// The time period used to collect in-active activations of this type.
/// </summary>
public TimeSpan? CollectionAgeLimit { get { return collectionAgeLimit; } }
private TimeSpan? collectionAgeLimit;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">Grain type of this configuration.</param>
public GrainTypeConfiguration(string type)
{
FullTypeName = type;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">Grain type of this configuration.</param>
/// <param name="ageLimit">Age limit for this type.</param>
public GrainTypeConfiguration(string type, TimeSpan? ageLimit)
{
FullTypeName = type;
SetCollectionAgeLimit(ageLimit);
}
/// <summary>Sets a custom collection age limit for a grain type.</summary>
/// <param name="ageLimit">Age limit for this type.</param>
public void SetCollectionAgeLimit(TimeSpan? ageLimit)
{
if (ageLimit == null)
{
collectionAgeLimit = null;
}
TimeSpan minAgeLimit = GlobalConfiguration.DEFAULT_COLLECTION_QUANTUM;
if (ageLimit < minAgeLimit)
{
if (GlobalConfiguration.ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT)
{
throw new ArgumentOutOfRangeException($"The AgeLimit attribute is required to be at least {minAgeLimit}.");
}
}
collectionAgeLimit = ageLimit;
}
/// <summary>
/// Load this configuration from xml element.
/// </summary>
/// <param name="xmlElement"></param>
public static GrainTypeConfiguration Load(XmlElement xmlElement)
{
string fullTypeName = null;
bool areDefaults = xmlElement.LocalName == "Defaults";
foreach (XmlAttribute attribute in xmlElement.Attributes)
{
if (!areDefaults && attribute.LocalName == "Type")
{
fullTypeName = attribute.Value.Trim();
}
else
{
throw new InvalidOperationException(string.Format("unrecognized attribute {0}", attribute.LocalName));
}
}
if (!areDefaults)
{
if (fullTypeName == null) throw new InvalidOperationException("Type attribute not specified");
}
bool found = false;
TimeSpan? collectionAgeLimit = null;
foreach (XmlNode node in xmlElement.ChildNodes)
{
var child = (XmlElement)node;
switch (child.LocalName)
{
default:
throw new InvalidOperationException(string.Format("unrecognized XML element {0}", child.LocalName));
case "Deactivation":
found = true;
collectionAgeLimit = ConfigUtilities.ParseCollectionAgeLimit(child);
break;
}
}
if (found) return new GrainTypeConfiguration(fullTypeName, collectionAgeLimit);
throw new InvalidOperationException(string.Format("empty GrainTypeConfiguration for {0}", fullTypeName == null ? "defaults" : fullTypeName));
}
internal void ValidateConfiguration(Logger logger)
{
if (AreDefaults) return;
Type type = null;
try
{
type = new CachedTypeResolver().ResolveType(FullTypeName);
}
catch (Exception exception)
{
string errStr = String.Format("Unable to find grain class type {0} specified in configuration; Failing silo startup.", FullTypeName);
logger.Error(ErrorCode.Loader_TypeLoadError, errStr, exception);
throw new OrleansException(errStr, exception);
}
if (type == null)
{
string errStr = String.Format("Unable to find grain class type {0} specified in configuration; Failing silo startup.", FullTypeName);
logger.Error(ErrorCode.Loader_TypeLoadError_2, errStr);
throw new OrleansException(errStr);
}
var typeInfo = type.GetTypeInfo();
// postcondition: returned type must implement IGrain.
if (!typeof(IGrain).IsAssignableFrom(type))
{
string errStr = String.Format("Type {0} must implement IGrain to be used Application configuration context.",type.FullName);
logger.Error(ErrorCode.Loader_TypeLoadError_3, errStr);
throw new OrleansException(errStr);
}
// postcondition: returned type must either be an interface or a class.
if (!typeInfo.IsInterface && !typeInfo.IsClass)
{
string errStr = String.Format("Type {0} must either be an interface or class used Application configuration context.",type.FullName);
logger.Error(ErrorCode.Loader_TypeLoadError_4, errStr);
throw new OrleansException(errStr);
}
}
}
}
| |
// 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.InteropServices;
using System.Runtime.Serialization;
namespace System
{
// Implements the Decimal data type. The Decimal data type can
// represent values ranging from -79,228,162,514,264,337,593,543,950,335 to
// 79,228,162,514,264,337,593,543,950,335 with 28 significant digits. The
// Decimal data type is ideally suited to financial calculations that
// require a large number of significant digits and no round-off errors.
//
// The finite set of values of type Decimal are of the form m
// / 10e, where m is an integer such that
// -296 <; m <; 296, and e is an integer
// between 0 and 28 inclusive.
//
// Contrary to the float and double data types, decimal
// fractional numbers such as 0.1 can be represented exactly in the
// Decimal representation. In the float and double
// representations, such numbers are often infinite fractions, making those
// representations more prone to round-off errors.
//
// The Decimal class implements widening conversions from the
// ubyte, char, short, int, and long types
// to Decimal. These widening conversions never loose any information
// and never throw exceptions. The Decimal class also implements
// narrowing conversions from Decimal to ubyte, char,
// short, int, and long. These narrowing conversions round
// the Decimal value towards zero to the nearest integer, and then
// converts that integer to the destination type. An OverflowException
// is thrown if the result is not within the range of the destination type.
//
// The Decimal class provides a widening conversion from
// Currency to Decimal. This widening conversion never loses any
// information and never throws exceptions. The Currency class provides
// a narrowing conversion from Decimal to Currency. This
// narrowing conversion rounds the Decimal to four decimals and then
// converts that number to a Currency. An OverflowException
// is thrown if the result is not within the range of the Currency type.
//
// The Decimal class provides narrowing conversions to and from the
// float and double types. A conversion from Decimal to
// float or double may loose precision, but will not loose
// information about the overall magnitude of the numeric value, and will never
// throw an exception. A conversion from float or double to
// Decimal throws an OverflowException if the value is not within
// the range of the Decimal type.
[Serializable]
[StructLayout(LayoutKind.Explicit)]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable<Decimal>, IEquatable<Decimal>, IDeserializationCallback
{
// Sign mask for the flags field. A value of zero in this bit indicates a
// positive Decimal value, and a value of one in this bit indicates a
// negative Decimal value.
//
// Look at OleAut's DECIMAL_NEG constant to check for negative values
// in native code.
private const uint SignMask = 0x80000000;
// Scale mask for the flags field. This byte in the flags field contains
// the power of 10 to divide the Decimal value by. The scale byte must
// contain a value between 0 and 28 inclusive.
private const uint ScaleMask = 0x00FF0000;
// Number of bits scale is shifted by.
private const int ScaleShift = 16;
// Constant representing the Decimal value 0.
public const Decimal Zero = 0m;
// Constant representing the Decimal value 1.
public const Decimal One = 1m;
// Constant representing the Decimal value -1.
public const Decimal MinusOne = -1m;
// Constant representing the largest possible Decimal value. The value of
// this constant is 79,228,162,514,264,337,593,543,950,335.
public const Decimal MaxValue = 79228162514264337593543950335m;
// Constant representing the smallest possible Decimal value. The value of
// this constant is -79,228,162,514,264,337,593,543,950,335.
public const Decimal MinValue = -79228162514264337593543950335m;
private const int CurrencyScale = 4; // Divide the "Int64" representation by 1E4 to get the "true" value of the Currency.
// The lo, mid, hi, and flags fields contain the representation of the
// Decimal value. The lo, mid, and hi fields contain the 96-bit integer
// part of the Decimal. Bits 0-15 (the lower word) of the flags field are
// unused and must be zero; bits 16-23 contain must contain a value between
// 0 and 28, indicating the power of 10 to divide the 96-bit integer part
// by to produce the Decimal value; bits 24-30 are unused and must be zero;
// and finally bit 31 indicates the sign of the Decimal value, 0 meaning
// positive and 1 meaning negative.
//
// NOTE: Do not change the offsets of these fields. This structure maps to the OleAut DECIMAL structure
// and can be passed as such in P/Invokes.
[FieldOffset(0)]
private int flags; // Do not rename (binary serialization)
[FieldOffset(4)]
private int hi; // Do not rename (binary serialization)
[FieldOffset(8)]
private int lo; // Do not rename (binary serialization)
[FieldOffset(12)]
private int mid; // Do not rename (binary serialization)
// NOTE: This set of fields overlay the ones exposed to serialization (which have to be signed ints for serialization compat.)
// The code inside Decimal was ported from C++ and expect unsigned values.
[FieldOffset(0), NonSerialized]
private uint uflags;
[FieldOffset(4), NonSerialized]
private uint uhi;
[FieldOffset(8), NonSerialized]
private uint ulo;
[FieldOffset(12), NonSerialized]
private uint umid;
/// <summary>
/// The low and mid fields combined in little-endian order
/// </summary>
[FieldOffset(8), NonSerialized]
private ulong ulomidLE;
// Constructs a Decimal from an integer value.
//
public Decimal(int value)
{
// JIT today can't inline methods that contains "starg" opcode.
// For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg".
int value_copy = value;
if (value_copy >= 0)
{
uflags = 0;
}
else
{
uflags = SignMask;
value_copy = -value_copy;
}
lo = value_copy;
mid = 0;
hi = 0;
}
// Constructs a Decimal from an unsigned integer value.
//
[CLSCompliant(false)]
public Decimal(uint value)
{
uflags = 0;
ulo = value;
umid = 0;
uhi = 0;
}
// Constructs a Decimal from a long value.
//
public Decimal(long value)
{
// JIT today can't inline methods that contains "starg" opcode.
// For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg".
long value_copy = value;
if (value_copy >= 0)
{
uflags = 0;
}
else
{
uflags = SignMask;
value_copy = -value_copy;
}
Low64 = (ulong)value_copy;
uhi = 0;
}
// Constructs a Decimal from an unsigned long value.
//
[CLSCompliant(false)]
public Decimal(ulong value)
{
uflags = 0;
Low64 = value;
uhi = 0;
}
// Constructs a Decimal from a float value.
//
public Decimal(float value)
{
DecCalc.VarDecFromR4(value, out this);
}
// Constructs a Decimal from a double value.
//
public Decimal(double value)
{
DecCalc.VarDecFromR8(value, out this);
}
//
// Decimal <==> Currency conversion.
//
// A Currency represents a positive or negative decimal value with 4 digits past the decimal point. The actual Int64 representation used by these methods
// is the currency value multiplied by 10,000. For example, a currency value of $12.99 would be represented by the Int64 value 129,900.
//
public static Decimal FromOACurrency(long cy)
{
Decimal d = default(Decimal);
ulong absoluteCy; // has to be ulong to accommodate the case where cy == long.MinValue.
if (cy < 0)
{
d.IsNegative = true;
absoluteCy = (ulong)(-cy);
}
else
{
absoluteCy = (ulong)cy;
}
// In most cases, FromOACurrency() produces a Decimal with Scale set to 4. Unless, that is, some of the trailing digits past the decimal point are zero,
// in which case, for compatibility with .Net, we reduce the Scale by the number of zeros. While the result is still numerically equivalent, the scale does
// affect the ToString() value. In particular, it prevents a converted currency value of $12.95 from printing uglily as "12.9500".
int scale = CurrencyScale;
if (absoluteCy != 0) // For compatibility, a currency of 0 emits the Decimal "0.0000" (scale set to 4).
{
while (scale != 0 && ((absoluteCy % 10) == 0))
{
scale--;
absoluteCy /= 10;
}
}
// No need to set d.Hi32 - a currency will never go high enough for it to be anything other than zero.
d.Low64 = absoluteCy;
d.Scale = scale;
return d;
}
public static long ToOACurrency(Decimal value)
{
long cy;
DecCalc.VarCyFromDec(ref value, out cy);
return cy;
}
private static bool IsValid(uint flags) => (flags & ~(SignMask | ScaleMask)) == 0 && ((flags & ScaleMask) <= (28 << 16));
// Constructs a Decimal from an integer array containing a binary
// representation. The bits argument must be a non-null integer
// array with four elements. bits[0], bits[1], and
// bits[2] contain the low, middle, and high 32 bits of the 96-bit
// integer part of the Decimal. bits[3] contains the scale factor
// and sign of the Decimal: bits 0-15 (the lower word) are unused and must
// be zero; bits 16-23 must contain a value between 0 and 28, indicating
// the power of 10 to divide the 96-bit integer part by to produce the
// Decimal value; bits 24-30 are unused and must be zero; and finally bit
// 31 indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
// Note that there are several possible binary representations for the
// same numeric value. For example, the value 1 can be represented as {1,
// 0, 0, 0} (integer value 1 with a scale factor of 0) and equally well as
// {1000, 0, 0, 0x30000} (integer value 1000 with a scale factor of 3).
// The possible binary representations of a particular value are all
// equally valid, and all are numerically equivalent.
//
public Decimal(int[] bits)
{
SetBits(bits);
}
private void SetBits(int[] bits)
{
if (bits == null)
throw new ArgumentNullException(nameof(bits));
if (bits.Length == 4)
{
uint f = (uint)bits[3];
if (IsValid(f))
{
lo = bits[0];
mid = bits[1];
hi = bits[2];
uflags = f;
return;
}
}
throw new ArgumentException(SR.Arg_DecBitCtor);
}
// Constructs a Decimal from its constituent parts.
//
public Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
{
if (scale > 28)
throw new ArgumentOutOfRangeException(nameof(scale), SR.ArgumentOutOfRange_DecimalScale);
this.lo = lo;
this.mid = mid;
this.hi = hi;
uflags = ((uint)scale) << 16;
if (isNegative)
uflags |= SignMask;
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
// OnDeserialization is called after each instance of this class is deserialized.
// This callback method performs decimal validation after being deserialized.
try
{
SetBits(GetBits(this));
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Overflow_Decimal, e);
}
}
// Constructs a Decimal from its constituent parts.
private Decimal(int lo, int mid, int hi, int flags)
{
if ((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16))
{
this.lo = lo;
this.mid = mid;
this.hi = hi;
this.flags = flags;
return;
}
throw new ArgumentException(SR.Arg_DecBitCtor);
}
// Returns the absolute value of the given Decimal. If d is
// positive, the result is d. If d is negative, the result
// is -d.
//
internal static Decimal Abs(Decimal d)
{
return new Decimal(d.lo, d.mid, d.hi, (int)(d.uflags & ~SignMask));
}
// Adds two Decimal values.
//
public static Decimal Add(Decimal d1, Decimal d2)
{
DecCalc.VarDecAdd(ref d1, ref d2);
return d1;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards positive infinity.
public static Decimal Ceiling(Decimal d)
{
return (-(Decimal.Floor(-d)));
}
// Compares two Decimal values, returning an integer that indicates their
// relationship.
//
public static int Compare(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2);
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Decimal, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
return 1;
if (!(value is Decimal))
throw new ArgumentException(SR.Arg_MustBeDecimal);
Decimal other = (Decimal)value;
return DecCalc.VarDecCmp(ref this, ref other);
}
public int CompareTo(Decimal value)
{
return DecCalc.VarDecCmp(ref this, ref value);
}
// Divides two Decimal values.
//
public static Decimal Divide(Decimal d1, Decimal d2)
{
DecCalc.VarDecDiv(ref d1, ref d2);
return d1;
}
// Checks if this Decimal is equal to a given object. Returns true
// if the given object is a boxed Decimal and its value is equal to the
// value of this Decimal. Returns false otherwise.
//
public override bool Equals(Object value)
{
if (value is Decimal)
{
Decimal other = (Decimal)value;
return DecCalc.VarDecCmp(ref this, ref other) == 0;
}
return false;
}
public bool Equals(Decimal value)
{
return DecCalc.VarDecCmp(ref this, ref value) == 0;
}
// Returns the hash code for this Decimal.
//
public unsafe override int GetHashCode()
{
double dbl = DecCalc.VarR8FromDec(ref this);
if (dbl == 0.0)
// Ensure 0 and -0 have the same hash code
return 0;
// conversion to double is lossy and produces rounding errors so we mask off the lowest 4 bits
//
// For example these two numerically equal decimals with different internal representations produce
// slightly different results when converted to double:
//
// decimal a = new decimal(new int[] { 0x76969696, 0x2fdd49fa, 0x409783ff, 0x00160000 });
// => (decimal)1999021.176470588235294117647000000000 => (double)1999021.176470588
// decimal b = new decimal(new int[] { 0x3f0f0f0f, 0x1e62edcc, 0x06758d33, 0x00150000 });
// => (decimal)1999021.176470588235294117647000000000 => (double)1999021.1764705882
//
return (int)(((((uint*)&dbl)[0]) & 0xFFFFFFF0) ^ ((uint*)&dbl)[1]);
}
// Compares two Decimal values for equality. Returns true if the two
// Decimal values are equal, or false if they are not equal.
//
public static bool Equals(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) == 0;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards negative infinity.
//
public static Decimal Floor(Decimal d)
{
DecCalc.VarDecInt(ref d);
return d;
}
// Converts this Decimal to a string. The resulting string consists of an
// optional minus sign ("-") followed to a sequence of digits ("0" - "9"),
// optionally followed by a decimal point (".") and another sequence of
// digits.
//
public override String ToString()
{
return Number.FormatDecimal(this, null, null);
}
public String ToString(String format)
{
return Number.FormatDecimal(this, format, null);
}
public String ToString(IFormatProvider provider)
{
return Number.FormatDecimal(this, null, provider);
}
public String ToString(String format, IFormatProvider provider)
{
return Number.FormatDecimal(this, format, provider);
}
// Converts a string to a Decimal. The string must consist of an optional
// minus sign ("-") followed by a sequence of digits ("0" - "9"). The
// sequence of digits may optionally contain a single decimal point (".")
// character. Leading and trailing whitespace characters are allowed.
// Parse also allows a currency symbol, a trailing negative sign, and
// parentheses in the number.
//
public static Decimal Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDecimal(s.AsReadOnlySpan(), NumberStyles.Number, null);
}
internal const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
throw new ArgumentException(SR.Arg_HexStyleNotSupported);
}
}
public static Decimal Parse(String s, NumberStyles style)
{
ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDecimal(s.AsReadOnlySpan(), style, null);
}
public static Decimal Parse(String s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDecimal(s.AsReadOnlySpan(), NumberStyles.Number, provider);
}
public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider)
{
ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDecimal(s.AsReadOnlySpan(), style, provider);
}
public static Decimal Parse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider)
{
ValidateParseStyleFloatingPoint(style);
return Number.ParseDecimal(s, style, provider);
}
public static Boolean TryParse(String s, out Decimal result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseDecimal(s.AsReadOnlySpan(), NumberStyles.Number, null, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Decimal result)
{
ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseDecimal(s.AsReadOnlySpan(), style, provider, out result);
}
public static Boolean TryParse(ReadOnlySpan<char> s, out Decimal result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
ValidateParseStyleFloatingPoint(style);
return Number.TryParseDecimal(s, style, provider, out result);
}
// Returns a binary representation of a Decimal. The return value is an
// integer array with four elements. Elements 0, 1, and 2 contain the low,
// middle, and high 32 bits of the 96-bit integer part of the Decimal.
// Element 3 contains the scale factor and sign of the Decimal: bits 0-15
// (the lower word) are unused; bits 16-23 contain a value between 0 and
// 28, indicating the power of 10 to divide the 96-bit integer part by to
// produce the Decimal value; bits 24-30 are unused; and finally bit 31
// indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
public static int[] GetBits(Decimal d)
{
return new int[] { d.lo, d.mid, d.hi, d.flags };
}
internal static void GetBytes(Decimal d, byte[] buffer)
{
Debug.Assert((buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16");
buffer[0] = (byte)d.lo;
buffer[1] = (byte)(d.lo >> 8);
buffer[2] = (byte)(d.lo >> 16);
buffer[3] = (byte)(d.lo >> 24);
buffer[4] = (byte)d.mid;
buffer[5] = (byte)(d.mid >> 8);
buffer[6] = (byte)(d.mid >> 16);
buffer[7] = (byte)(d.mid >> 24);
buffer[8] = (byte)d.hi;
buffer[9] = (byte)(d.hi >> 8);
buffer[10] = (byte)(d.hi >> 16);
buffer[11] = (byte)(d.hi >> 24);
buffer[12] = (byte)d.flags;
buffer[13] = (byte)(d.flags >> 8);
buffer[14] = (byte)(d.flags >> 16);
buffer[15] = (byte)(d.flags >> 24);
}
// Returns the larger of two Decimal values.
//
internal static Decimal Max(Decimal d1, Decimal d2)
{
return Compare(d1, d2) >= 0 ? d1 : d2;
}
// Returns the smaller of two Decimal values.
//
internal static Decimal Min(Decimal d1, Decimal d2)
{
return Compare(d1, d2) < 0 ? d1 : d2;
}
public static Decimal Remainder(Decimal d1, Decimal d2)
{
return DecCalc.VarDecMod(ref d1, ref d2);
}
// Multiplies two Decimal values.
//
public static Decimal Multiply(Decimal d1, Decimal d2)
{
DecCalc.VarDecMul(ref d1, ref d2);
return d1;
}
// Returns the negated value of the given Decimal. If d is non-zero,
// the result is -d. If d is zero, the result is zero.
//
public static Decimal Negate(Decimal d)
{
return new Decimal(d.lo, d.mid, d.hi, (int)(d.uflags ^ SignMask));
}
// Rounds a Decimal value to a given number of decimal places. The value
// given by d is rounded to the number of decimal places given by
// decimals. The decimals argument must be an integer between
// 0 and 28 inclusive.
//
// By default a mid-point value is rounded to the nearest even number. If the mode is
// passed in, it can also round away from zero.
public static Decimal Round(Decimal d)
{
return Round(d, 0);
}
public static Decimal Round(Decimal d, int decimals)
{
Decimal result = new Decimal();
if (decimals < 0 || decimals > 28)
throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
DecCalc.VarDecRound(ref d, decimals, ref result);
d = result;
return d;
}
public static Decimal Round(Decimal d, MidpointRounding mode)
{
return Round(d, 0, mode);
}
public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
{
if (decimals < 0 || decimals > 28)
throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), nameof(mode));
if (mode == MidpointRounding.ToEven)
{
Decimal result = new Decimal();
DecCalc.VarDecRound(ref d, decimals, ref result);
d = result;
}
else
{
DecCalc.InternalRoundFromZero(ref d, decimals);
}
return d;
}
internal static int Sign(ref decimal d) => (d.lo | d.mid | d.hi) == 0 ? 0 : (d.flags >> 31) | 1;
// Subtracts two Decimal values.
//
public static Decimal Subtract(Decimal d1, Decimal d2)
{
DecCalc.VarDecSub(ref d1, ref d2);
return d1;
}
// Converts a Decimal to an unsigned byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
public static byte ToByte(Decimal value)
{
uint temp;
try
{
temp = ToUInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Byte, e);
}
if (temp < Byte.MinValue || temp > Byte.MaxValue) throw new OverflowException(SR.Overflow_Byte);
return (byte)temp;
}
// Converts a Decimal to a signed byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
[CLSCompliant(false)]
public static sbyte ToSByte(Decimal value)
{
int temp;
try
{
temp = ToInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_SByte, e);
}
if (temp < SByte.MinValue || temp > SByte.MaxValue) throw new OverflowException(SR.Overflow_SByte);
return (sbyte)temp;
}
// Converts a Decimal to a short. The Decimal value is
// rounded towards zero to the nearest integer value, and the result of
// this operation is returned as a short.
//
public static short ToInt16(Decimal value)
{
int temp;
try
{
temp = ToInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Int16, e);
}
if (temp < Int16.MinValue || temp > Int16.MaxValue) throw new OverflowException(SR.Overflow_Int16);
return (short)temp;
}
// Converts a Decimal to a double. Since a double has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
public static double ToDouble(Decimal d)
{
return DecCalc.VarR8FromDec(ref d);
}
// Converts a Decimal to an integer. The Decimal value is rounded towards
// zero to the nearest integer value, and the result of this operation is
// returned as an integer.
//
public static int ToInt32(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d.hi == 0 && d.mid == 0)
{
int i = d.lo;
if (!d.IsNegative)
{
if (i >= 0) return i;
}
else
{
i = -i;
if (i <= 0) return i;
}
}
throw new OverflowException(SR.Overflow_Int32);
}
// Converts a Decimal to a long. The Decimal value is rounded towards zero
// to the nearest integer value, and the result of this operation is
// returned as a long.
//
public static long ToInt64(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d.uhi == 0)
{
long l = d.ulo | (long)(int)d.umid << 32;
if (!d.IsNegative)
{
if (l >= 0) return l;
}
else
{
l = -l;
if (l <= 0) return l;
}
}
throw new OverflowException(SR.Overflow_Int64);
}
// Converts a Decimal to an ushort. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(Decimal value)
{
uint temp;
try
{
temp = ToUInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_UInt16, e);
}
if (temp < UInt16.MinValue || temp > UInt16.MaxValue) throw new OverflowException(SR.Overflow_UInt16);
return (ushort)temp;
}
// Converts a Decimal to an unsigned integer. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an unsigned integer.
//
[CLSCompliant(false)]
public static uint ToUInt32(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d.uhi == 0 && d.umid == 0)
{
if (!d.IsNegative || d.ulo == 0)
return d.ulo;
}
throw new OverflowException(SR.Overflow_UInt32);
}
// Converts a Decimal to an unsigned long. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as a long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d.uhi == 0)
{
ulong l = (ulong)d.ulo | ((ulong)d.umid << 32);
if (!d.IsNegative || l == 0)
return l;
}
throw new OverflowException(SR.Overflow_UInt64);
}
// Converts a Decimal to a float. Since a float has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
public static float ToSingle(Decimal d)
{
return DecCalc.VarR4FromDec(ref d);
}
// Truncates a Decimal to an integer value. The Decimal argument is rounded
// towards zero to the nearest integer value, corresponding to removing all
// digits after the decimal point.
//
public static Decimal Truncate(Decimal d)
{
DecCalc.VarDecFix(ref d);
return d;
}
public static implicit operator Decimal(byte value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(sbyte value)
{
return new Decimal(value);
}
public static implicit operator Decimal(short value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(ushort value)
{
return new Decimal(value);
}
public static implicit operator Decimal(char value)
{
return new Decimal(value);
}
public static implicit operator Decimal(int value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(uint value)
{
return new Decimal(value);
}
public static implicit operator Decimal(long value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(ulong value)
{
return new Decimal(value);
}
public static explicit operator Decimal(float value)
{
return new Decimal(value);
}
public static explicit operator Decimal(double value)
{
return new Decimal(value);
}
public static explicit operator byte(Decimal value)
{
return ToByte(value);
}
[CLSCompliant(false)]
public static explicit operator sbyte(Decimal value)
{
return ToSByte(value);
}
public static explicit operator char(Decimal value)
{
UInt16 temp;
try
{
temp = ToUInt16(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Char, e);
}
return (char)temp;
}
public static explicit operator short(Decimal value)
{
return ToInt16(value);
}
[CLSCompliant(false)]
public static explicit operator ushort(Decimal value)
{
return ToUInt16(value);
}
public static explicit operator int(Decimal value)
{
return ToInt32(value);
}
[CLSCompliant(false)]
public static explicit operator uint(Decimal value)
{
return ToUInt32(value);
}
public static explicit operator long(Decimal value)
{
return ToInt64(value);
}
[CLSCompliant(false)]
public static explicit operator ulong(Decimal value)
{
return ToUInt64(value);
}
public static explicit operator float(Decimal value)
{
return ToSingle(value);
}
public static explicit operator double(Decimal value)
{
return ToDouble(value);
}
public static Decimal operator +(Decimal d)
{
return d;
}
public static Decimal operator -(Decimal d)
{
return Negate(d);
}
public static Decimal operator ++(Decimal d)
{
return Add(d, One);
}
public static Decimal operator --(Decimal d)
{
return Subtract(d, One);
}
public static Decimal operator +(Decimal d1, Decimal d2)
{
return Add(d1, d2);
}
public static Decimal operator -(Decimal d1, Decimal d2)
{
return Subtract(d1, d2);
}
public static Decimal operator *(Decimal d1, Decimal d2)
{
return Multiply(d1, d2);
}
public static Decimal operator /(Decimal d1, Decimal d2)
{
return Divide(d1, d2);
}
public static Decimal operator %(Decimal d1, Decimal d2)
{
return Remainder(d1, d2);
}
public static bool operator ==(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) == 0;
}
public static bool operator !=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) != 0;
}
public static bool operator <(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) < 0;
}
public static bool operator <=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) <= 0;
}
public static bool operator >(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) > 0;
}
public static bool operator >=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) >= 0;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Decimal;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(this);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(this);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(this);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(this);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(this);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(this);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(this);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(this);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(this);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(this);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(this);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return this;
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Transforms;
using osu.Framework.Graphics.Visualisation;
using osu.Framework.Utils;
using osu.Framework.Timing;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Drawables
{
public class TestSceneTransformRewinding : FrameworkTestScene
{
private const double interval = 250;
private const int interval_count = 4;
private static double intervalAt(int sequence) => interval * sequence;
private ManualClock manualClock;
private FramedClock manualFramedClock;
[SetUp]
public void SetUp() => Schedule(() =>
{
Clear();
manualClock = new ManualClock();
manualFramedClock = new FramedClock(manualClock);
});
[Test]
public void BasicScale()
{
boxTest(box =>
{
box.Scale = Vector2.One;
box.ScaleTo(0, interval * 4);
});
checkAtTime(250, box => Precision.AlmostEquals(box.Scale.X, 0.75f));
checkAtTime(500, box => Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(750, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(1000, box => Precision.AlmostEquals(box.Scale.X, 0f));
checkAtTime(500, box => Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(250, box => Precision.AlmostEquals(box.Scale.X, 0.75f));
AddAssert("check transform count", () => box.Transforms.Count() == 1);
}
[Test]
public void ScaleSequence()
{
boxTest(box =>
{
box.Scale = Vector2.One;
box.ScaleTo(0.75f, interval).Then()
.ScaleTo(0.5f, interval).Then()
.ScaleTo(0.25f, interval).Then()
.ScaleTo(0, interval);
});
int i = 0;
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.75f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0f));
checkAtTime(interval * (i -= 2), box => Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.75f));
AddAssert("check transform count", () => box.Transforms.Count() == 4);
}
[Test]
public void BasicMovement()
{
boxTest(box =>
{
box.Scale = new Vector2(0.25f);
box.Anchor = Anchor.TopLeft;
box.Origin = Anchor.TopLeft;
box.MoveTo(new Vector2(0.75f, 0), interval).Then()
.MoveTo(new Vector2(0.75f, 0.75f), interval).Then()
.MoveTo(new Vector2(0, 0.75f), interval).Then()
.MoveTo(new Vector2(0), interval);
});
int i = 0;
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0.75f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0.75f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0f));
checkAtTime(interval * (i -= 2), box => Precision.AlmostEquals(box.Y, 0.75f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.X, 0.75f));
AddAssert("check transform count", () => box.Transforms.Count() == 4);
}
[Test]
public void MoveSequence()
{
boxTest(box =>
{
box.Scale = new Vector2(0.25f);
box.Anchor = Anchor.TopLeft;
box.Origin = Anchor.TopLeft;
box.ScaleTo(0.5f, interval).MoveTo(new Vector2(0.5f), interval).Then()
.ScaleTo(0.1f, interval).MoveTo(new Vector2(0, 0.75f), interval).Then()
.ScaleTo(1f, interval).MoveTo(new Vector2(0, 0), interval).Then()
.FadeTo(0, interval);
});
int i = 0;
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0.5f) && Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0.75f) && Precision.AlmostEquals(box.Scale.X, 0.1f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0f));
checkAtTime(interval * (i += 2), box => Precision.AlmostEquals(box.Alpha, 0f));
checkAtTime(interval * (i - 2), box => Precision.AlmostEquals(box.Alpha, 1f));
AddAssert("check transform count", () => box.Transforms.Count() == 7);
}
[Test]
public void MoveCancelSequence()
{
boxTest(box =>
{
box.Scale = new Vector2(0.25f);
box.Anchor = Anchor.TopLeft;
box.Origin = Anchor.TopLeft;
box.ScaleTo(0.5f, interval).Then().ScaleTo(1, interval);
Scheduler.AddDelayed(() => { box.ScaleTo(new Vector2(0.1f), interval); }, interval / 2);
});
int i = 0;
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(interval * ++i, box => !Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.1f));
AddAssert("check transform count", () => box.Transforms.Count() == 2);
}
[Test]
public void SameTypeInType()
{
boxTest(box =>
{
box.ScaleTo(0.5f, interval * 4);
box.Delay(interval * 2).ScaleTo(1, interval);
});
int i = 0;
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.3125f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.375f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.375f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.3125f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
AddAssert("check transform count", () => box.Transforms.Count() == 2);
}
[Test]
public void SameTypeInPartialOverlap()
{
boxTest(box =>
{
box.ScaleTo(0.5f, interval * 2);
box.Delay(interval).ScaleTo(1, interval * 2);
});
int i = 0;
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.375f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.6875f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 1));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.6875f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.375f));
AddAssert("check transform count", () => box.Transforms.Count() == 2);
}
[Test]
public void StartInMiddleOfSequence()
{
boxTest(box =>
{
box.Alpha = 0;
box.Delay(interval * 2).FadeInFromZero(interval);
box.ScaleTo(0.9f, interval * 4);
}, 750);
checkAtTime(interval * 3, box => Precision.AlmostEquals(box.Alpha, 1));
checkAtTime(interval * 4, box => Precision.AlmostEquals(box.Alpha, 1) && Precision.AlmostEquals(box.Scale.X, 0.9f));
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0) && Precision.AlmostEquals(box.Scale.X, 0.575f));
AddAssert("check transform count", () => box.Transforms.Count() == 3);
}
[Test]
public void RewindBetweenDisparateValues()
{
boxTest(box =>
{
box.Alpha = 0;
});
// move forward to future point in time before adding transforms.
checkAtTime(interval * 4, _ => true);
AddStep("add transforms", () =>
{
using (box.BeginAbsoluteSequence(0))
{
box.FadeOutFromOne(interval);
box.Delay(interval * 3).FadeOutFromOne(interval);
// FadeOutFromOne adds extra transforms which disallow testing this scenario, so we remove them.
box.RemoveTransform(box.Transforms.ElementAt(2));
box.RemoveTransform(box.Transforms.ElementAt(0));
}
});
checkAtTime(0, box => Precision.AlmostEquals(box.Alpha, 1));
checkAtTime(interval * 1, box => Precision.AlmostEquals(box.Alpha, 0));
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0));
checkAtTime(interval * 3, box => Precision.AlmostEquals(box.Alpha, 1));
checkAtTime(interval * 4, box => Precision.AlmostEquals(box.Alpha, 0));
// importantly, this should be 0 not 1, reading from the EndValue of the first FadeOutFromOne transform.
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0));
}
[Test]
public void AddPastTransformFromFutureWhenNotInHierarchy()
{
AddStep("seek clock to 1000", () => manualClock.CurrentTime = interval * 4);
AddStep("create box", () =>
{
box = createBox();
box.Clock = manualFramedClock;
box.RemoveCompletedTransforms = false;
manualFramedClock.ProcessFrame();
using (box.BeginAbsoluteSequence(0))
box.Delay(interval * 2).FadeOut(interval);
});
AddStep("seek clock to 0", () => manualClock.CurrentTime = 0);
AddStep("add box", () =>
{
Add(new AnimationContainer
{
Child = box,
ExaminableDrawable = box,
});
});
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 1));
checkAtTime(interval * 3, box => Precision.AlmostEquals(box.Alpha, 0));
}
[Test]
public void AddPastTransformFromFuture()
{
boxTest(box =>
{
box.Alpha = 0;
});
// move forward to future point in time before adding transforms.
checkAtTime(interval * 4, _ => true);
AddStep("add transforms", () =>
{
using (box.BeginAbsoluteSequence(0))
{
box.FadeOutFromOne(interval);
box.Delay(interval * 3).FadeInFromZero(interval);
// FadeOutFromOne adds extra transforms which disallow testing this scenario, so we remove them.
box.RemoveTransform(box.Transforms.ElementAt(2));
box.RemoveTransform(box.Transforms.ElementAt(0));
}
});
AddStep("add one more transform in the middle", () =>
{
using (box.BeginAbsoluteSequence(interval * 2))
box.FadeIn(interval * 0.5);
});
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0));
checkAtTime(interval * 2.5, box => Precision.AlmostEquals(box.Alpha, 1));
}
[Test]
public void LoopSequence()
{
boxTest(box => { box.RotateTo(0).RotateTo(90, interval).Loop(); });
const int count = 4;
for (int i = 0; i <= count; i++)
{
if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1));
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0));
}
AddAssert("check transform count", () => box.Transforms.Count() == 10);
for (int i = count; i >= 0; i--)
{
if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1));
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0));
}
}
[Test]
public void StartInMiddleOfLoopSequence()
{
boxTest(box => { box.RotateTo(0).RotateTo(90, interval).Loop(); }, 750);
checkAtTime(750, box => Precision.AlmostEquals(box.Rotation, 0f));
AddAssert("check transform count", () => box.Transforms.Count() == 8);
const int count = 4;
for (int i = 0; i <= count; i++)
{
if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1));
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0));
}
AddAssert("check transform count", () => box.Transforms.Count() == 10);
for (int i = count; i >= 0; i--)
{
if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1));
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0));
}
}
[Test]
public void TestSimultaneousTransformsOutOfOrder()
{
boxTest(box =>
{
using (box.BeginAbsoluteSequence(0))
{
box.MoveToX(0.5f, 4 * interval);
box.Delay(interval).MoveToY(0.5f, 2 * interval);
}
});
checkAtTime(0, box => Precision.AlmostEquals(box.Position, new Vector2(0)));
checkAtTime(interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.125f, 0)));
checkAtTime(2 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.25f, 0.25f)));
checkAtTime(3 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.375f, 0.5f)));
checkAtTime(4 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.5f)));
checkAtTime(3 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.375f, 0.5f)));
checkAtTime(2 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.25f, 0.25f)));
checkAtTime(interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.125f, 0)));
checkAtTime(0, box => Precision.AlmostEquals(box.Position, new Vector2(0)));
}
[Test]
public void TestMultipleTransformTargets()
{
boxTest(box =>
{
box.Delay(500).MoveTo(new Vector2(0, 0.25f), 500);
box.MoveToY(0.5f, 250);
});
checkAtTime(double.MinValue, box => box.Y == 0);
checkAtTime(0, box => box.Y == 0);
checkAtTime(250, box => box.Y == 0.5f);
checkAtTime(750, box => box.Y == 0.375f);
checkAtTime(1000, box => box.Y == 0.25f);
checkAtTime(1500, box => box.Y == 0.25f);
checkAtTime(1250, box => box.Y == 0.25f);
checkAtTime(750, box => box.Y == 0.375f);
}
[Test]
public void TestMoveToOffsetRespectsRelevantTransforms()
{
boxTest(box =>
{
box.MoveToY(0.25f, 250);
box.Delay(500).MoveToOffset(new Vector2(0, 0.25f), 250);
});
checkAtTime(0, box => box.Y == 0);
checkAtTime(250, box => box.Y == 0.25f);
checkAtTime(500, box => box.Y == 0.25f);
checkAtTime(750, box => box.Y == 0.5f);
}
[Test]
public void TestMoveToOffsetRespectsTransformsOrder()
{
boxTest(box =>
{
box.Delay(500).MoveToOffset(new Vector2(0, 0.25f), 250);
box.MoveToY(0.25f, 250);
});
checkAtTime(0, box => box.Y == 0);
checkAtTime(250, box => box.Y == 0.25f);
checkAtTime(500, box => box.Y == 0.25f);
checkAtTime(750, box => box.Y == 0.5f);
}
private Box box;
private void checkAtTime(double time, Func<Box, bool> assert)
{
AddAssert($"check at time {time}", () =>
{
manualClock.CurrentTime = time;
box.Clock = manualFramedClock;
box.UpdateSubTree();
return assert(box);
});
}
private void boxTest(Action<Box> action, int startTime = 0)
{
AddStep("add box", () =>
{
Add(new AnimationContainer(startTime)
{
Child = box = createBox(),
ExaminableDrawable = box,
});
action(box);
});
}
private static Box createBox()
{
return new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
RelativePositionAxes = Axes.Both,
Scale = new Vector2(0.25f),
};
}
private class AnimationContainer : Container
{
public override bool RemoveCompletedTransforms => false;
protected override Container<Drawable> Content => content;
private readonly Container content;
private readonly SpriteText minTimeText;
private readonly SpriteText currentTimeText;
private readonly SpriteText maxTimeText;
private readonly Tick seekingTick;
private readonly WrappingTimeContainer wrapping;
public Box ExaminableDrawable;
private readonly FlowContainer<DrawableTransform> transforms;
public AnimationContainer(int startTime = 0)
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
InternalChild = wrapping = new WrappingTimeContainer(startTime)
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Container
{
FillMode = FillMode.Fit,
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(0.6f),
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.DarkGray,
},
content = new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
},
}
},
transforms = new FillFlowContainer<DrawableTransform>
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Spacing = Vector2.One,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Width = 0.2f,
},
new Container
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.8f, 0.1f),
Children = new Drawable[]
{
minTimeText = new SpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.TopLeft,
},
currentTimeText = new SpriteText
{
RelativePositionAxes = Axes.X,
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomCentre,
Y = -10,
},
maxTimeText = new SpriteText
{
Anchor = Anchor.BottomRight,
Origin = Anchor.TopRight,
},
seekingTick = new Tick(0, false),
new Tick(0),
new Tick(1),
new Tick(2),
new Tick(3),
new Tick(4),
}
}
}
};
}
private List<Transform> displayedTransforms;
protected override void Update()
{
base.Update();
double time = wrapping.Time.Current;
minTimeText.Text = wrapping.MinTime.ToString("n0");
currentTimeText.Text = time.ToString("n0");
seekingTick.X = currentTimeText.X = (float)(time / (wrapping.MaxTime - wrapping.MinTime));
maxTimeText.Text = wrapping.MaxTime.ToString("n0");
maxTimeText.Colour = time > wrapping.MaxTime ? Color4.Gray : wrapping.Time.Elapsed > 0 ? Color4.Blue : Color4.Red;
minTimeText.Colour = time < wrapping.MinTime ? Color4.Gray : content.Time.Elapsed > 0 ? Color4.Blue : Color4.Red;
if (displayedTransforms == null || !ExaminableDrawable.Transforms.SequenceEqual(displayedTransforms))
{
transforms.Clear();
foreach (var t in ExaminableDrawable.Transforms)
transforms.Add(new DrawableTransform(t, 15));
displayedTransforms = new List<Transform>(ExaminableDrawable.Transforms);
}
}
private class Tick : Box
{
private readonly int tick;
private readonly bool colouring;
public Tick(int tick, bool colouring = true)
{
this.tick = tick;
this.colouring = colouring;
Anchor = Anchor.BottomLeft;
Origin = Anchor.BottomCentre;
Size = new Vector2(1, 10);
Colour = Color4.White;
RelativePositionAxes = Axes.X;
X = (float)tick / interval_count;
}
protected override void Update()
{
base.Update();
if (colouring)
Colour = Time.Current > tick * interval ? Color4.Yellow : Color4.White;
}
}
}
private class WrappingTimeContainer : Container
{
// Padding, in milliseconds, at each end of maxima of the clock time
private const double time_padding = 50;
public double MinTime => clock.MinTime + time_padding;
public double MaxTime => clock.MaxTime - time_padding;
private readonly ReversibleClock clock;
public WrappingTimeContainer(double startTime)
{
clock = new ReversibleClock(startTime);
}
[BackgroundDependencyLoader]
private void load()
{
// Replace the game clock, but keep it as a reference
clock.SetSource(Clock);
Clock = clock;
}
protected override void LoadComplete()
{
base.LoadComplete();
clock.MinTime = -time_padding;
clock.MaxTime = intervalAt(interval_count) + time_padding;
}
private class ReversibleClock : IFrameBasedClock
{
private readonly double startTime;
public double MinTime;
public double MaxTime = 1000;
private OffsetClock offsetClock;
private IFrameBasedClock trackingClock;
private bool reversed;
public ReversibleClock(double startTime)
{
this.startTime = startTime;
}
public void SetSource(IFrameBasedClock trackingClock)
{
this.trackingClock = trackingClock;
offsetClock = new OffsetClock(trackingClock) { Offset = -trackingClock.CurrentTime + startTime };
}
public double CurrentTime { get; private set; }
public double Rate => offsetClock.Rate;
public bool IsRunning => offsetClock.IsRunning;
public double ElapsedFrameTime => (reversed ? -1 : 1) * trackingClock.ElapsedFrameTime;
public double FramesPerSecond => trackingClock.FramesPerSecond;
public FrameTimeInfo TimeInfo => new FrameTimeInfo { Current = CurrentTime, Elapsed = ElapsedFrameTime };
public void ProcessFrame()
{
// There are two iterations, when iteration % 2 == 0 : not reversed
int iteration = (int)(offsetClock.CurrentTime / (MaxTime - MinTime));
reversed = iteration % 2 == 1;
double iterationTime = offsetClock.CurrentTime % (MaxTime - MinTime);
if (reversed)
CurrentTime = MaxTime - iterationTime;
else
CurrentTime = MinTime + iterationTime;
}
}
}
}
}
| |
using ATL.Logging;
using System;
using System.IO;
using static ATL.AudioData.AudioDataManager;
using Commons;
using System.Collections.Generic;
using static ATL.ChannelsArrangements;
namespace ATL.AudioData.IO
{
/// <summary>
/// Class for PCM (uncompressed audio) files manipulation (extension : .WAV)
///
/// Implementation notes
///
/// 1. BEXT metadata - UMID field
///
/// UMID field is decoded "as is" using the hex notation. No additional interpretation has been done so far.
///
/// </summary>
class WAV : MetaDataIO, IAudioDataIO, IMetaDataEmbedder
{
// Format type names
public const String WAV_FORMAT_UNKNOWN = "Unknown";
public const String WAV_FORMAT_PCM = "Windows PCM";
public const String WAV_FORMAT_ADPCM = "Microsoft ADPCM";
public const String WAV_FORMAT_ALAW = "A-LAW";
public const String WAV_FORMAT_MULAW = "MU-LAW";
public const String WAV_FORMAT_DVI_IMA_ADPCM = "DVI/IMA ADPCM";
public const String WAV_FORMAT_MP3 = "MPEG Layer III";
private const string HEADER_RIFF = "RIFF";
private const string HEADER_RIFX = "RIFX";
private const string FORMAT_WAVE = "WAVE";
// Standard sub-chunks
private const String CHUNK_FORMAT = "fmt ";
private const String CHUNK_FACT = "fact";
private const String CHUNK_DATA = "data";
// Broadcast Wave metadata sub-chunk
private const String CHUNK_BEXT = BextTag.CHUNK_BEXT;
private const String CHUNK_INFO = InfoTag.CHUNK_LIST;
private const String CHUNK_IXML = IXmlTag.CHUNK_IXML;
private const String CHUNK_ID3 = "id3 ";
// private ushort formatID;
private ChannelsArrangement channelsArrangement;
private uint sampleRate;
private uint bytesPerSecond;
// private ushort blockAlign;
private ushort bitsPerSample;
private int sampleNumber;
private uint headerSize;
private double bitrate;
private double duration;
private SizeInfo sizeInfo;
private readonly string filePath;
private bool _isLittleEndian;
private long id3v2Offset;
private FileStructureHelper id3v2StructureHelper = new FileStructureHelper(false);
private static IDictionary<string, byte> frameMapping; // Mapping between WAV frame codes and ATL frame codes
/* Unused for now
public ushort FormatID // Format type code
{
get { return this.formatID; }
}
public ushort BlockAlign // Block alignment
{
get { return this.blockAlign; }
}
*/
// ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES
// IAudioDataIO
public int SampleRate
{
get { return (int)this.sampleRate; }
}
public bool IsVBR
{
get { return false; }
}
public int CodecFamily
{
get { return AudioDataIOFactory.CF_LOSSLESS; }
}
public string FileName
{
get { return filePath; }
}
public double BitRate
{
get { return bitrate; }
}
public double Duration
{
get { return duration; }
}
public ChannelsArrangement ChannelsArrangement
{
get { return channelsArrangement; }
}
public bool IsMetaSupported(int metaDataType)
{
return (metaDataType == MetaDataIOFactory.TAG_ID3V1 || metaDataType == MetaDataIOFactory.TAG_ID3V2 || metaDataType == MetaDataIOFactory.TAG_NATIVE); // Native for bext, info and iXML chunks
}
// MetaDataIO
protected override int getDefaultTagOffset()
{
return TO_BUILTIN;
}
protected override int getImplementedTagType()
{
return MetaDataIOFactory.TAG_NATIVE;
}
protected override byte getFrameMapping(string zone, string ID, byte tagVersion)
{
byte supportedMetaId = 255;
// Finds the ATL field identifier
if (frameMapping.ContainsKey(ID)) supportedMetaId = frameMapping[ID];
return supportedMetaId;
}
protected override bool isLittleEndian
{
get { return _isLittleEndian; }
}
// IMetaDataEmbedder
public long HasEmbeddedID3v2
{
get { return id3v2Offset; }
}
public uint ID3v2EmbeddingHeaderSize
{
get { return 8; }
}
public FileStructureHelper.Zone Id3v2Zone
{
get { return id3v2StructureHelper.GetZone(CHUNK_ID3); }
}
// ---------- CONSTRUCTORS & INITIALIZERS
static WAV()
{
frameMapping = new Dictionary<string, byte>
{
{ "bext.description", TagData.TAG_FIELD_GENERAL_DESCRIPTION },
{ "info.INAM", TagData.TAG_FIELD_TITLE },
{ "info.TITL", TagData.TAG_FIELD_TITLE },
{ "info.IART", TagData.TAG_FIELD_ARTIST },
{ "info.ICOP", TagData.TAG_FIELD_COPYRIGHT },
{ "info.IGNR", TagData.TAG_FIELD_GENRE },
{ "info.IRTD", TagData.TAG_FIELD_RATING },
{ "info.YEAR", TagData.TAG_FIELD_RECORDING_YEAR },
{ "info.TRCK", TagData.TAG_FIELD_TRACK_NUMBER },
{ "info.ICMT", TagData.TAG_FIELD_COMMENT }
};
}
protected void resetData()
{
duration = 0;
bitrate = 0;
// formatID = 0;
// blockAlign = 0;
sampleRate = 0;
bytesPerSecond = 0;
bitsPerSample = 0;
sampleNumber = 0;
headerSize = 0;
id3v2Offset = -1;
id3v2StructureHelper.Clear();
ResetData();
}
public WAV(string filePath)
{
this.filePath = filePath;
resetData();
}
// ---------- SUPPORT METHODS
private bool readWAV(Stream source, ReadTagParams readTagParams)
{
bool result = true;
uint riffChunkSize;
long riffChunkSizePos;
byte[] data = new byte[4];
source.Seek(0, SeekOrigin.Begin);
// Read header
source.Read(data, 0, 4);
string str = Utils.Latin1Encoding.GetString(data);
if (str.Equals(HEADER_RIFF))
{
_isLittleEndian = true;
}
else if (str.Equals(HEADER_RIFX))
{
_isLittleEndian = false;
}
else
{
return false;
}
// Force creation of FileStructureHelper with detected endianness
structureHelper = new FileStructureHelper(isLittleEndian);
id3v2StructureHelper = new FileStructureHelper(isLittleEndian);
riffChunkSizePos = source.Position;
source.Read(data, 0, 4);
if (isLittleEndian) riffChunkSize = StreamUtils.DecodeUInt32(data); else riffChunkSize = StreamUtils.DecodeBEUInt32(data);
// Format code
source.Read(data, 0, 4);
str = Utils.Latin1Encoding.GetString(data);
if (!str.Equals(FORMAT_WAVE)) return false;
string subChunkId;
uint chunkSize;
long chunkDataPos;
bool foundBext = false;
bool foundInfo = false;
bool foundIXml = false;
// Sub-chunks loop
while (source.Position < riffChunkSize + 8)
{
// Chunk ID
source.Read(data, 0, 4);
if (0 == data[0]) // Sometimes data segment ends with a parasite null byte
{
source.Seek(-3, SeekOrigin.Current);
source.Read(data, 0, 4);
}
subChunkId = Utils.Latin1Encoding.GetString(data);
// Chunk size
source.Read(data, 0, 4);
if (isLittleEndian) chunkSize = StreamUtils.DecodeUInt32(data); else chunkSize = StreamUtils.DecodeBEUInt32(data);
chunkDataPos = source.Position;
if (subChunkId.Equals(CHUNK_FORMAT))
{
source.Seek(2, SeekOrigin.Current); // FormatId
source.Read(data, 0, 2);
if (isLittleEndian) channelsArrangement = ChannelsArrangements.GuessFromChannelNumber(StreamUtils.DecodeUInt16(data));
else channelsArrangement = ChannelsArrangements.GuessFromChannelNumber(StreamUtils.DecodeBEUInt16(data));
source.Read(data, 0, 4);
if (isLittleEndian) sampleRate = StreamUtils.DecodeUInt32(data); else sampleRate = StreamUtils.DecodeBEUInt32(data);
source.Read(data, 0, 4);
if (isLittleEndian) bytesPerSecond = StreamUtils.DecodeUInt32(data); else bytesPerSecond = StreamUtils.DecodeBEUInt32(data);
source.Seek(2, SeekOrigin.Current); // BlockAlign
source.Read(data, 0, 2);
if (isLittleEndian) bitsPerSample = StreamUtils.DecodeUInt16(data); else bitsPerSample = StreamUtils.DecodeBEUInt16(data);
}
else if (subChunkId.Equals(CHUNK_DATA))
{
headerSize = riffChunkSize - chunkSize;
}
else if (subChunkId.Equals(CHUNK_FACT))
{
source.Read(data, 0, 4);
if (isLittleEndian) sampleNumber = StreamUtils.DecodeInt32(data); else sampleNumber = StreamUtils.DecodeBEInt32(data);
}
else if (subChunkId.Equals(CHUNK_BEXT))
{
structureHelper.AddZone(source.Position - 8, (int)(chunkSize + 8), subChunkId);
structureHelper.AddSize(riffChunkSizePos, riffChunkSize, subChunkId);
foundBext = true;
tagExists = true;
BextTag.FromStream(source, this, readTagParams);
}
else if (subChunkId.Equals(CHUNK_INFO))
{
// Purpose of the list should be INFO
source.Read(data, 0, 4);
string purpose = Utils.Latin1Encoding.GetString(data, 0, 4);
if (purpose.Equals(InfoTag.PURPOSE_INFO))
{
structureHelper.AddZone(source.Position - 12, (int)(chunkSize + 8), subChunkId);
structureHelper.AddSize(riffChunkSizePos, riffChunkSize, subChunkId);
foundInfo = true;
tagExists = true;
InfoTag.FromStream(source, this, readTagParams, chunkSize);
}
}
else if (subChunkId.Equals(CHUNK_IXML))
{
structureHelper.AddZone(source.Position - 8, (int)(chunkSize + 8), subChunkId);
structureHelper.AddSize(riffChunkSizePos, riffChunkSize, subChunkId);
foundIXml = true;
tagExists = true;
IXmlTag.FromStream(source, this, readTagParams, chunkSize);
}
else if (subChunkId.Equals(CHUNK_ID3))
{
id3v2Offset = source.Position;
// Zone is already added by Id3v2.Read
id3v2StructureHelper.AddZone(id3v2Offset - 8, (int)(chunkSize + 8), subChunkId);
id3v2StructureHelper.AddSize(riffChunkSizePos, riffChunkSize, subChunkId);
}
source.Seek(chunkDataPos + chunkSize, SeekOrigin.Begin);
}
if (-1 == id3v2Offset)
{
id3v2Offset = 0; // Switch status to "tried to read, but nothing found"
if (readTagParams.PrepareForWriting)
{
id3v2StructureHelper.AddZone(source.Position, 0, CHUNK_ID3);
id3v2StructureHelper.AddSize(riffChunkSizePos, riffChunkSize, CHUNK_ID3);
}
}
// Add zone placeholders for future tag writing
if (readTagParams.PrepareForWriting)
{
if (!foundBext)
{
structureHelper.AddZone(source.Position, 0, CHUNK_BEXT);
structureHelper.AddSize(riffChunkSizePos, riffChunkSize, CHUNK_BEXT);
}
if (!foundInfo)
{
structureHelper.AddZone(source.Position, 0, CHUNK_INFO);
structureHelper.AddSize(riffChunkSizePos, riffChunkSize, CHUNK_INFO);
}
if (!foundIXml)
{
structureHelper.AddZone(source.Position, 0, CHUNK_IXML);
structureHelper.AddSize(riffChunkSizePos, riffChunkSize, CHUNK_IXML);
}
}
return result;
}
/* Unused for now
private String getFormat()
{
// Get format type name
switch (formatID)
{
case 1: return WAV_FORMAT_PCM;
case 2: return WAV_FORMAT_ADPCM;
case 6: return WAV_FORMAT_ALAW;
case 7: return WAV_FORMAT_MULAW;
case 17: return WAV_FORMAT_DVI_IMA_ADPCM;
case 85: return WAV_FORMAT_MP3;
default : return "";
}
}
*/
private double getDuration()
{
// Get duration
double result = 0;
if ((sampleNumber == 0) && (bytesPerSecond > 0))
result = (double)(sizeInfo.FileSize - headerSize - sizeInfo.ID3v1Size) / bytesPerSecond;
if ((sampleNumber > 0) && (sampleRate > 0))
result = (double)(sampleNumber / sampleRate);
return result * 1000.0;
}
private double getBitrate()
{
return Math.Round((double)bitsPerSample / 1000.0 * sampleRate * channelsArrangement.NbChannels);
}
public bool Read(BinaryReader source, SizeInfo sizeInfo, ReadTagParams readTagParams)
{
this.sizeInfo = sizeInfo;
return read(source, readTagParams);
}
protected override bool read(BinaryReader source, ReadTagParams readTagParams)
{
resetData();
bool result = readWAV(source.BaseStream, readTagParams);
// Process data if loaded and header valid
if (result)
{
bitrate = getBitrate();
duration = getDuration();
}
return result;
}
protected override int write(TagData tag, BinaryWriter w, string zone)
{
int result = 0;
if (zone.Equals(CHUNK_BEXT) && BextTag.IsDataEligible(this)) result += BextTag.ToStream(w, isLittleEndian, this);
else if (zone.Equals(CHUNK_INFO) && InfoTag.IsDataEligible(this)) result += InfoTag.ToStream(w, isLittleEndian, this);
else if (zone.Equals(CHUNK_IXML) && IXmlTag.IsDataEligible(this)) result += IXmlTag.ToStream(w, isLittleEndian, this);
return result;
}
public void WriteID3v2EmbeddingHeader(BinaryWriter w, long tagSize)
{
w.Write(Utils.Latin1Encoding.GetBytes(CHUNK_ID3));
if (isLittleEndian)
{
w.Write((int)(tagSize));
}
else
{
w.Write(StreamUtils.EncodeBEInt32((int)(tagSize)));
}
}
}
}
| |
/*
* 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.Linq;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using pCampBot.Interfaces;
namespace pCampBot
{
/// <summary>
/// Thread/Bot manager for the application
/// </summary>
public class BotManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int DefaultLoginDelay = 5000;
/// <summary>
/// Is pCampbot in the process of connecting bots?
/// </summary>
public bool ConnectingBots { get; private set; }
/// <summary>
/// Is pCampbot in the process of disconnecting bots?
/// </summary>
public bool DisconnectingBots { get; private set; }
/// <summary>
/// Delay between logins of multiple bots.
/// </summary>
/// <remarks>TODO: This value needs to be configurable by a command line argument.</remarks>
public int LoginDelay { get; set; }
/// <summary>
/// Command console
/// </summary>
protected CommandConsole m_console;
/// <summary>
/// Controls whether bots start out sending agent updates on connection.
/// </summary>
public bool InitBotSendAgentUpdates { get; set; }
/// <summary>
/// Controls whether bots request textures for the object information they receive
/// </summary>
public bool InitBotRequestObjectTextures { get; set; }
/// <summary>
/// Created bots, whether active or inactive.
/// </summary>
protected List<Bot> m_bots;
/// <summary>
/// Random number generator.
/// </summary>
public Random Rng { get; private set; }
/// <summary>
/// Track the assets we have and have not received so we don't endlessly repeat requests.
/// </summary>
public Dictionary<UUID, bool> AssetsReceived { get; private set; }
/// <summary>
/// The regions that we know about.
/// </summary>
public Dictionary<ulong, GridRegion> RegionsKnown { get; private set; }
/// <summary>
/// First name for bots
/// </summary>
private string m_firstName;
/// <summary>
/// Last name stem for bots
/// </summary>
private string m_lastNameStem;
/// <summary>
/// Password for bots
/// </summary>
private string m_password;
/// <summary>
/// Login URI for bots.
/// </summary>
private string m_loginUri;
/// <summary>
/// Start location for bots.
/// </summary>
private string m_startUri;
/// <summary>
/// Postfix bot number at which bot sequence starts.
/// </summary>
private int m_fromBotNumber;
/// <summary>
/// Wear setting for bots.
/// </summary>
private string m_wearSetting;
/// <summary>
/// Behaviour switches for bots.
/// </summary>
private HashSet<string> m_defaultBehaviourSwitches = new HashSet<string>();
/// <summary>
/// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
/// </summary>
public BotManager()
{
InitBotSendAgentUpdates = true;
InitBotRequestObjectTextures = true;
LoginDelay = DefaultLoginDelay;
Rng = new Random(Environment.TickCount);
AssetsReceived = new Dictionary<UUID, bool>();
RegionsKnown = new Dictionary<ulong, GridRegion>();
m_console = CreateConsole();
MainConsole.Instance = m_console;
// Make log4net see the console
//
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
OpenSimAppender consoleAppender = null;
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
consoleAppender = (OpenSimAppender)appender;
consoleAppender.Console = m_console;
break;
}
}
m_console.Commands.AddCommand(
"bot", false, "shutdown", "shutdown", "Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand(
"bot", false, "quit", "quit", "Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand(
"bot", false, "connect", "connect [<n>]", "Connect bots",
"If an <n> is given, then the first <n> disconnected bots by postfix number are connected.\n"
+ "If no <n> is given, then all currently disconnected bots are connected.",
HandleConnect);
m_console.Commands.AddCommand(
"bot", false, "disconnect", "disconnect [<n>]", "Disconnect bots",
"Disconnecting bots will interupt any bot connection process, including connection on startup.\n"
+ "If an <n> is given, then the last <n> connected bots by postfix number are disconnected.\n"
+ "If no <n> is given, then all currently connected bots are disconnected.",
HandleDisconnect);
m_console.Commands.AddCommand(
"bot", false, "add behaviour", "add behaviour <abbreviated-name> [<bot-number>]",
"Add a behaviour to a bot",
"If no bot number is specified then behaviour is added to all bots.\n"
+ "Can be performed on connected or disconnected bots.",
HandleAddBehaviour);
m_console.Commands.AddCommand(
"bot", false, "remove behaviour", "remove behaviour <abbreviated-name> [<bot-number>]",
"Remove a behaviour from a bot",
"If no bot number is specified then behaviour is added to all bots.\n"
+ "Can be performed on connected or disconnected bots.",
HandleRemoveBehaviour);
m_console.Commands.AddCommand(
"bot", false, "sit", "sit", "Sit all bots on the ground.",
HandleSit);
m_console.Commands.AddCommand(
"bot", false, "stand", "stand", "Stand all bots.",
HandleStand);
m_console.Commands.AddCommand(
"bot", false, "set bots", "set bots <key> <value>", "Set a setting for all bots.", HandleSetBots);
m_console.Commands.AddCommand(
"bot", false, "show regions", "show regions", "Show regions known to bots", HandleShowRegions);
m_console.Commands.AddCommand(
"bot", false, "show bots", "show bots", "Shows the status of all bots", HandleShowBotsStatus);
m_console.Commands.AddCommand(
"bot", false, "show bot", "show bot <bot-number>",
"Shows the detailed status and settings of a particular bot.", HandleShowBotStatus);
m_bots = new List<Bot>();
}
/// <summary>
/// Startup number of bots specified in the starting arguments
/// </summary>
/// <param name="botcount">How many bots to start up</param>
/// <param name="cs">The configuration for the bots to use</param>
public void CreateBots(int botcount, IConfig startupConfig)
{
m_firstName = startupConfig.GetString("firstname");
m_lastNameStem = startupConfig.GetString("lastname");
m_password = startupConfig.GetString("password");
m_loginUri = startupConfig.GetString("loginuri");
m_fromBotNumber = startupConfig.GetInt("from", 0);
m_wearSetting = startupConfig.GetString("wear", "no");
m_startUri = ParseInputStartLocationToUri(startupConfig.GetString("start", "last"));
Array.ForEach<string>(
startupConfig.GetString("behaviours", "p").Split(new char[] { ',' }), b => m_defaultBehaviourSwitches.Add(b));
for (int i = 0; i < botcount; i++)
{
lock (m_bots)
{
string lastName = string.Format("{0}_{1}", m_lastNameStem, i + m_fromBotNumber);
CreateBot(
this,
CreateBehavioursFromAbbreviatedNames(m_defaultBehaviourSwitches),
m_firstName, lastName, m_password, m_loginUri, m_startUri, m_wearSetting);
}
}
}
private List<IBehaviour> CreateBehavioursFromAbbreviatedNames(HashSet<string> abbreviatedNames)
{
// We must give each bot its own list of instantiated behaviours since they store state.
List<IBehaviour> behaviours = new List<IBehaviour>();
// Hard-coded for now
foreach (string abName in abbreviatedNames)
{
IBehaviour newBehaviour = null;
if (abName == "c")
newBehaviour = new CrossBehaviour();
if (abName == "g")
newBehaviour = new GrabbingBehaviour();
if (abName == "n")
newBehaviour = new NoneBehaviour();
if (abName == "p")
newBehaviour = new PhysicsBehaviour();
if (abName == "t")
newBehaviour = new TeleportBehaviour();
if (newBehaviour != null)
{
behaviours.Add(newBehaviour);
}
else
{
MainConsole.Instance.OutputFormat("No behaviour with abbreviated name {0} found", abName);
}
}
return behaviours;
}
public void ConnectBots(int botcount)
{
ConnectingBots = true;
Thread connectBotThread = new Thread(o => ConnectBotsInternal(botcount));
connectBotThread.Name = "Bots connection thread";
connectBotThread.Start();
}
private void ConnectBotsInternal(int botCount)
{
MainConsole.Instance.OutputFormat(
"[BOT MANAGER]: Starting {0} bots connecting to {1}, location {2}, named {3} {4}_<n>",
botCount,
m_loginUri,
m_startUri,
m_firstName,
m_lastNameStem);
MainConsole.Instance.OutputFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
MainConsole.Instance.OutputFormat("[BOT MANAGER]: BotsSendAgentUpdates is {0}", InitBotSendAgentUpdates);
MainConsole.Instance.OutputFormat("[BOT MANAGER]: InitBotRequestObjectTextures is {0}", InitBotRequestObjectTextures);
int connectedBots = 0;
for (int i = 0; i < m_bots.Count; i++)
{
lock (m_bots)
{
if (DisconnectingBots)
{
MainConsole.Instance.Output(
"[BOT MANAGER]: Aborting bot connection due to user-initiated disconnection");
break;
}
if (m_bots[i].ConnectionState == ConnectionState.Disconnected)
{
m_bots[i].Connect();
connectedBots++;
if (connectedBots >= botCount)
break;
// Stagger logins
Thread.Sleep(LoginDelay);
}
}
}
ConnectingBots = false;
}
/// <summary>
/// Parses the command line start location to a start string/uri that the login mechanism will recognize.
/// </summary>
/// <returns>
/// The input start location to URI.
/// </returns>
/// <param name='startLocation'>
/// Start location.
/// </param>
private string ParseInputStartLocationToUri(string startLocation)
{
if (startLocation == "home" || startLocation == "last")
return startLocation;
string regionName;
// Just a region name or only one (!) extra component. Like a viewer, we will stick 128/128/0 on the end
Vector3 startPos = new Vector3(128, 128, 0);
string[] startLocationComponents = startLocation.Split('/');
regionName = startLocationComponents[0];
if (startLocationComponents.Length >= 2)
{
float.TryParse(startLocationComponents[1], out startPos.X);
if (startLocationComponents.Length >= 3)
{
float.TryParse(startLocationComponents[2], out startPos.Y);
if (startLocationComponents.Length >= 4)
float.TryParse(startLocationComponents[3], out startPos.Z);
}
}
return string.Format("uri:{0}&{1}&{2}&{3}", regionName, startPos.X, startPos.Y, startPos.Z);
}
/// <summary>
/// This creates a bot but does not start it.
/// </summary>
/// <param name="bm"></param>
/// <param name="behaviours">Behaviours for this bot to perform.</param>
/// <param name="firstName">First name</param>
/// <param name="lastName">Last name</param>
/// <param name="password">Password</param>
/// <param name="loginUri">Login URI</param>
/// <param name="startLocation">Location to start the bot. Can be "last", "home" or a specific sim name.</param>
/// <param name="wearSetting"></param>
public void CreateBot(
BotManager bm, List<IBehaviour> behaviours,
string firstName, string lastName, string password, string loginUri, string startLocation, string wearSetting)
{
MainConsole.Instance.OutputFormat(
"[BOT MANAGER]: Creating bot {0} {1}, behaviours are {2}",
firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
Bot pb = new Bot(bm, behaviours, firstName, lastName, password, startLocation, loginUri);
pb.wear = wearSetting;
pb.Client.Settings.SEND_AGENT_UPDATES = InitBotSendAgentUpdates;
pb.RequestObjectTextures = InitBotRequestObjectTextures;
pb.OnConnected += handlebotEvent;
pb.OnDisconnected += handlebotEvent;
m_bots.Add(pb);
}
/// <summary>
/// High level connnected/disconnected events so we can keep track of our threads by proxy
/// </summary>
/// <param name="callbot"></param>
/// <param name="eventt"></param>
private void handlebotEvent(Bot callbot, EventType eventt)
{
switch (eventt)
{
case EventType.CONNECTED:
{
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
break;
}
case EventType.DISCONNECTED:
{
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
break;
}
}
}
/// <summary>
/// Standard CreateConsole routine
/// </summary>
/// <returns></returns>
protected CommandConsole CreateConsole()
{
return new LocalConsole("pCampbot");
}
private void HandleConnect(string module, string[] cmd)
{
if (ConnectingBots)
{
MainConsole.Instance.Output("Still connecting bots. Please wait for previous process to complete.");
return;
}
lock (m_bots)
{
int botsToConnect;
int disconnectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Disconnected);
if (cmd.Length == 1)
{
botsToConnect = disconnectedBots;
}
else
{
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToConnect))
return;
botsToConnect = Math.Min(botsToConnect, disconnectedBots);
}
MainConsole.Instance.OutputFormat("Connecting {0} bots", botsToConnect);
ConnectBots(botsToConnect);
}
}
private void HandleAddBehaviour(string module, string[] cmd)
{
if (cmd.Length < 3 || cmd.Length > 4)
{
MainConsole.Instance.OutputFormat("Usage: add behaviour <abbreviated-behaviour> [<bot-number>]");
return;
}
string rawBehaviours = cmd[2];
List<Bot> botsToEffect = new List<Bot>();
if (cmd.Length == 3)
{
lock (m_bots)
botsToEffect.AddRange(m_bots);
}
else
{
int botNumber;
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
botsToEffect.Add(bot);
}
HashSet<string> rawAbbreviatedSwitchesToAdd = new HashSet<string>();
Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => rawAbbreviatedSwitchesToAdd.Add(b));
foreach (Bot bot in botsToEffect)
{
List<IBehaviour> behavioursAdded = new List<IBehaviour>();
foreach (IBehaviour behaviour in CreateBehavioursFromAbbreviatedNames(rawAbbreviatedSwitchesToAdd))
{
if (bot.AddBehaviour(behaviour))
behavioursAdded.Add(behaviour);
}
MainConsole.Instance.OutputFormat(
"Added behaviours {0} to bot {1}",
string.Join(", ", behavioursAdded.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
}
}
private void HandleRemoveBehaviour(string module, string[] cmd)
{
if (cmd.Length < 3 || cmd.Length > 4)
{
MainConsole.Instance.OutputFormat("Usage: remove behaviour <abbreviated-behaviour> [<bot-number>]");
return;
}
string rawBehaviours = cmd[2];
List<Bot> botsToEffect = new List<Bot>();
if (cmd.Length == 3)
{
lock (m_bots)
botsToEffect.AddRange(m_bots);
}
else
{
int botNumber;
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
botsToEffect.Add(bot);
}
HashSet<string> abbreviatedBehavioursToRemove = new HashSet<string>();
Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => abbreviatedBehavioursToRemove.Add(b));
foreach (Bot bot in botsToEffect)
{
List<IBehaviour> behavioursRemoved = new List<IBehaviour>();
foreach (string b in abbreviatedBehavioursToRemove)
{
IBehaviour behaviour;
if (bot.TryGetBehaviour(b, out behaviour))
{
bot.RemoveBehaviour(b);
behavioursRemoved.Add(behaviour);
}
}
MainConsole.Instance.OutputFormat(
"Removed behaviours {0} to bot {1}",
string.Join(", ", behavioursRemoved.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
}
}
private void HandleDisconnect(string module, string[] cmd)
{
lock (m_bots)
{
int botsToDisconnect;
int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
if (cmd.Length == 1)
{
botsToDisconnect = connectedBots;
}
else
{
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToDisconnect))
return;
botsToDisconnect = Math.Min(botsToDisconnect, connectedBots);
}
DisconnectingBots = true;
MainConsole.Instance.OutputFormat("Disconnecting {0} bots", botsToDisconnect);
int disconnectedBots = 0;
for (int i = m_bots.Count - 1; i >= 0; i--)
{
if (disconnectedBots >= botsToDisconnect)
break;
Bot thisBot = m_bots[i];
if (thisBot.ConnectionState == ConnectionState.Connected)
{
Util.FireAndForget(o => thisBot.Disconnect());
disconnectedBots++;
}
}
DisconnectingBots = false;
}
}
private void HandleSit(string module, string[] cmd)
{
lock (m_bots)
{
m_bots.ForEach(b => b.SitOnGround());
}
}
private void HandleStand(string module, string[] cmd)
{
lock (m_bots)
{
m_bots.ForEach(b => b.Stand());
}
}
private void HandleShutdown(string module, string[] cmd)
{
lock (m_bots)
{
int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
if (connectedBots > 0)
{
MainConsole.Instance.OutputFormat("Please disconnect {0} connected bots first", connectedBots);
return;
}
}
MainConsole.Instance.Output("Shutting down");
Environment.Exit(0);
}
private void HandleSetBots(string module, string[] cmd)
{
string key = cmd[2];
string rawValue = cmd[3];
if (key == "SEND_AGENT_UPDATES")
{
bool newSendAgentUpdatesSetting;
if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newSendAgentUpdatesSetting))
return;
MainConsole.Instance.OutputFormat(
"Setting SEND_AGENT_UPDATES to {0} for all bots", newSendAgentUpdatesSetting);
lock (m_bots)
m_bots.ForEach(b => b.Client.Settings.SEND_AGENT_UPDATES = newSendAgentUpdatesSetting);
}
else
{
MainConsole.Instance.Output("Error: Only setting currently available is SEND_AGENT_UPDATES");
}
}
private void HandleShowRegions(string module, string[] cmd)
{
string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
lock (RegionsKnown)
{
foreach (GridRegion region in RegionsKnown.Values)
{
MainConsole.Instance.OutputFormat(
outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
}
}
}
private void HandleShowBotsStatus(string module, string[] cmd)
{
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Name", 24);
cdt.AddColumn("Region", 24);
cdt.AddColumn("Status", 13);
cdt.AddColumn("Conns", 5);
cdt.AddColumn("Behaviours", 20);
Dictionary<ConnectionState, int> totals = new Dictionary<ConnectionState, int>();
foreach (object o in Enum.GetValues(typeof(ConnectionState)))
totals[(ConnectionState)o] = 0;
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
Simulator currentSim = bot.Client.Network.CurrentSim;
totals[bot.ConnectionState]++;
cdt.AddRow(
bot.Name,
currentSim != null ? currentSim.Name : "(none)",
bot.ConnectionState,
bot.SimulatorsCount,
string.Join(",", bot.Behaviours.Keys.ToArray()));
}
}
MainConsole.Instance.Output(cdt.ToString());
ConsoleDisplayList cdl = new ConsoleDisplayList();
foreach (KeyValuePair<ConnectionState, int> kvp in totals)
cdl.AddRow(kvp.Key, kvp.Value);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleShowBotStatus(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.Output("Usage: show bot <n>");
return;
}
int botNumber;
if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, cmd[2], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("Name", bot.Name);
cdl.AddRow("Status", bot.ConnectionState);
Simulator currentSim = bot.Client.Network.CurrentSim;
cdl.AddRow("Region", currentSim != null ? currentSim.Name : "(none)");
List<Simulator> connectedSimulators = bot.Simulators;
List<string> simulatorNames = connectedSimulators.ConvertAll<string>(cs => cs.Name);
cdl.AddRow("Connections", string.Join(", ", simulatorNames.ToArray()));
MainConsole.Instance.Output(cdl.ToString());
MainConsole.Instance.Output("Settings");
ConsoleDisplayList statusCdl = new ConsoleDisplayList();
statusCdl.AddRow(
"Behaviours",
string.Join(", ", bot.Behaviours.Values.ToList().ConvertAll<string>(b => b.Name).ToArray()));
GridClient botClient = bot.Client;
statusCdl.AddRow("SEND_AGENT_UPDATES", botClient.Settings.SEND_AGENT_UPDATES);
MainConsole.Instance.Output(statusCdl.ToString());
}
/// <summary>
/// Get a specific bot from its number.
/// </summary>
/// <returns>null if no bot was found</returns>
/// <param name='botNumber'></param>
private Bot GetBotFromNumber(int botNumber)
{
string name = GenerateBotNameFromNumber(botNumber);
Bot bot;
lock (m_bots)
bot = m_bots.Find(b => b.Name == name);
return bot;
}
private string GenerateBotNameFromNumber(int botNumber)
{
return string.Format("{0} {1}_{2}", m_firstName, m_lastNameStem, botNumber);
}
internal void Grid_GridRegion(object o, GridRegionEventArgs args)
{
lock (RegionsKnown)
{
GridRegion newRegion = args.Region;
if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
{
return;
}
else
{
m_log.DebugFormat(
"[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
RegionsKnown[newRegion.RegionHandle] = newRegion;
}
}
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Domain.Schedules;
namespace JoinRpg.Services.Interfaces
{
public interface IFieldSetupService
{
Task UpdateFieldParams(UpdateFieldRequest request);
Task DeleteField(int projectId, int projectFieldId);
Task AddField(CreateFieldRequest request);
Task CreateFieldValueVariant(CreateFieldValueVariantRequest request);
Task UpdateFieldValueVariant(UpdateFieldValueVariantRequest request);
Task<ProjectFieldDropdownValue> DeleteFieldValueVariant(int projectId,
int projectFieldId,
int valueId);
Task MoveField(int projectid, int projectcharacterfieldid, short direction);
Task MoveFieldVariant(int projectid,
int projectFieldId,
int projectFieldVariantId,
short direction);
Task CreateFieldValueVariants(int projectId,
int projectFieldId,
[NotNull]
string valuesToAdd);
Task MoveFieldAfter(int projectId, int projectFieldId, int? afterFieldId);
Task SetFieldSettingsAsync(FieldSettingsRequest request);
}
public class FieldSettingsRequest
{
public int? NameField { get; set; }
public int? DescriptionField { get; set; }
public bool LegacyModelEnabled { get; set; }
public int ProjectId { get; set; }
}
public abstract class FieldRequestBase
{
protected FieldRequestBase(int projectId,
string name,
string fieldHint,
bool canPlayerEdit,
bool canPlayerView,
bool isPublic,
MandatoryStatus mandatoryStatus,
IReadOnlyCollection<int> showForGroups,
bool validForNpc,
bool includeInPrint,
bool showForUnapprovedClaims,
int price,
string masterFieldHint,
string? programmaticValue)
{
ProjectId = projectId;
Name = name;
FieldHint = fieldHint;
CanPlayerEdit = canPlayerEdit;
CanPlayerView = canPlayerView;
IsPublic = isPublic;
MandatoryStatus = mandatoryStatus;
ShowForGroups = showForGroups;
ValidForNpc = validForNpc;
IncludeInPrint = includeInPrint;
ShowForUnapprovedClaims = showForUnapprovedClaims;
Price = price;
MasterFieldHint = masterFieldHint;
ProgrammaticValue = programmaticValue;
}
public int ProjectId { get; }
public string Name { get; }
public string FieldHint { get; }
public bool CanPlayerEdit { get; }
public bool CanPlayerView { get; }
public bool IsPublic { get; }
public MandatoryStatus MandatoryStatus { get; }
public IReadOnlyCollection<int> ShowForGroups { get; }
public bool ValidForNpc { get; }
public bool IncludeInPrint { get; }
public bool ShowForUnapprovedClaims { get; }
public int Price { get; }
public string MasterFieldHint { get; }
public string? ProgrammaticValue { get; }
}
public sealed class CreateFieldRequest : FieldRequestBase
{
public ProjectFieldType FieldType { get; }
public FieldBoundTo FieldBoundTo { get; }
/// <inheritdoc />
public CreateFieldRequest(int projectId,
ProjectFieldType fieldType,
string name,
string fieldHint,
bool canPlayerEdit,
bool canPlayerView,
bool isPublic,
FieldBoundTo fieldBoundTo,
MandatoryStatus mandatoryStatus,
IReadOnlyCollection<int> showForGroups,
bool validForNpc,
bool includeInPrint,
bool showForUnapprovedClaims,
int price,
string masterFieldHint,
string? programmaticValue) : base(projectId,
name,
fieldHint,
canPlayerEdit,
canPlayerView,
isPublic,
mandatoryStatus,
showForGroups,
validForNpc,
includeInPrint,
showForUnapprovedClaims,
price,
masterFieldHint,
programmaticValue)
{
FieldType = fieldType;
FieldBoundTo = fieldBoundTo;
}
}
public sealed class UpdateFieldRequest : FieldRequestBase
{
/// <inheritdoc />
public UpdateFieldRequest(int projectId,
string name,
string fieldHint,
bool canPlayerEdit,
bool canPlayerView,
bool isPublic,
MandatoryStatus mandatoryStatus,
IReadOnlyCollection<int> showForGroups,
bool validForNpc,
bool includeInPrint,
bool showForUnapprovedClaims,
int price,
string masterFieldHint,
int projectFieldId,
string programmaticValue) : base(projectId,
name,
fieldHint,
canPlayerEdit,
canPlayerView,
isPublic,
mandatoryStatus,
showForGroups,
validForNpc,
includeInPrint,
showForUnapprovedClaims,
price,
masterFieldHint,
programmaticValue) => ProjectFieldId = projectFieldId;
public int ProjectFieldId { get; }
}
public abstract class FieldValueVariantRequestBase
{
public int ProjectId { get; }
public int ProjectFieldId { get; }
public string Label { get; }
public string? Description { get; }
public string? MasterDescription { get; }
public string? ProgrammaticValue { get; }
public int Price { get; }
public bool PlayerSelectable { get; }
public TimeSlotOptions? TimeSlotOptions { get; }
protected FieldValueVariantRequestBase(int projectId,
string label,
string? description,
int projectFieldId,
string? masterDescription,
string? programmaticValue,
int price,
bool playerSelectable,
TimeSlotOptions? timeSlotOptions)
{
ProjectId = projectId;
Label = label;
Description = description;
ProjectFieldId = projectFieldId;
MasterDescription = masterDescription;
ProgrammaticValue = programmaticValue;
Price = price;
PlayerSelectable = playerSelectable;
TimeSlotOptions = timeSlotOptions;
}
}
public class UpdateFieldValueVariantRequest : FieldValueVariantRequestBase
{
public UpdateFieldValueVariantRequest(int projectId,
int projectFieldDropdownValueId,
string label,
string description,
int projectFieldId,
string masterDescription,
string programmaticValue,
int price,
bool playerSelectable,
TimeSlotOptions? timeSlotOptions)
: base(projectId,
label,
description,
projectFieldId,
masterDescription,
programmaticValue,
price,
playerSelectable,
timeSlotOptions) => ProjectFieldDropdownValueId = projectFieldDropdownValueId;
public int ProjectFieldDropdownValueId { get; }
}
public class CreateFieldValueVariantRequest : FieldValueVariantRequestBase
{
public CreateFieldValueVariantRequest(int projectId,
string label,
string? description,
int projectFieldId,
string? masterDescription,
string? programmaticValue,
int price,
bool playerSelectable,
TimeSlotOptions? timeSlotOptions)
: base(projectId,
label,
description,
projectFieldId,
masterDescription,
programmaticValue,
price,
playerSelectable,
timeSlotOptions)
{
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/24/2009 9:10:23 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
namespace DotSpatial.Projections
{
public static class Reproject
{
#region Private Variables
private const double EPS = 1E-12;
#endregion
#region Methods
/// <summary>
/// This method reprojects the affine transform coefficients. This is used for projection on the fly,
/// where image transforms can take advantage of an affine projection, but does not have the power of
/// a full projective transform and gets less and less accurate as the image covers larger and larger
/// areas. Since most image layers represent small rectangular areas, this should not be a problem in
/// most cases. the affine array should be ordered as follows:
/// X' = [0] + [1] * Column + [2] * Row
/// Y' = [3] + [4] * Column + [5] * Row
/// </summary>
/// <param name="affine">The array of double affine coefficients.</param>
/// <param name="numRows">The number of rows to use for the lower bounds. Value of 0 or less will be set to 1.</param>
/// <param name="numCols">The number of columns to use to get the right bounds. Values of 0 or less will be set to 1.</param>
/// <param name="source"></param>
/// <param name="dest"></param>
/// <returns>The transformed coefficients</returns>
public static double[] ReprojectAffine(double[] affine, double numRows, double numCols, ProjectionInfo source, ProjectionInfo dest)
{
if (numRows <= 0) numRows = 1;
if (numCols <= 0) numCols = 1;
double[] vertices = new double[6];
// Top left
vertices[0] = affine[0];
vertices[1] = affine[3];
// Top right
vertices[2] = affine[0] + affine[1] * numCols;
vertices[3] = affine[3] + affine[4] * numCols;
// Bottom Left
vertices[4] = affine[0] + affine[2] * numRows;
vertices[5] = affine[3] + affine[5] * numRows;
double[] z = new double[3];
ReprojectPoints(vertices, z, source, dest, 0, 3);
double[] affineResult = new double[6];
affineResult[0] = vertices[0];
affineResult[1] = (vertices[2] - vertices[0]) / numCols;
affineResult[2] = (vertices[4] - vertices[0]) / numRows;
affineResult[3] = vertices[1];
affineResult[4] = (vertices[3] - vertices[1]) / numCols;
affineResult[5] = (vertices[5] - vertices[1]) / numRows;
return affineResult;
}
public static void ReprojectPoints(double[] xy, double[] z, ProjectionInfo source, ProjectionInfo dest, int startIndex, int numPoints)
{
ReprojectPoints(xy, z, source, 1.0, dest, 1.0, null, startIndex, numPoints);
}
public static void ReprojectPoints(double[] xy, double[] z, ProjectionInfo source, double srcZtoMeter, ProjectionInfo dest, double dstZtoMeter, IDatumTransform idt, int startIndex, int numPoints)
{
double toMeter = source.Unit.Meters;
// Geocentric coordinates are centered at the core of the earth. Z is up toward the north pole.
// The X axis goes from the center of the earth through Greenwich.
// The Y axis passes through 90E.
// This section converts from geocentric coordinates to geodetic ones if necessary.
if (source.IsGeocentric)
{
if (z == null)
{
throw new ProjectionException(45);
}
for (int i = startIndex; i < numPoints; i++)
{
if (toMeter != 1)
{
xy[i * 2] *= toMeter;
xy[i * 2 + 1] *= toMeter;
}
}
GeocentricGeodetic g = new GeocentricGeodetic(source.GeographicInfo.Datum.Spheroid);
g.GeocentricToGeodetic(xy, z, startIndex, numPoints);
}
// Transform source points to lam/phi if they are not already
ConvertToLatLon(source, xy, z, srcZtoMeter, startIndex, numPoints);
double fromGreenwich = source.GeographicInfo.Meridian.Longitude * source.GeographicInfo.Unit.Radians;
if (fromGreenwich != 0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[2 * i] != double.PositiveInfinity)
xy[2 * i] += fromGreenwich;
}
}
// DATUM TRANSFORM IF NEEDED
if (idt == null)
{
if (!source.GeographicInfo.Datum.Matches(dest.GeographicInfo.Datum))
{
DatumTransform(source, dest, xy, z, startIndex, numPoints);
}
}
else
{
idt.Transform(source, dest, xy, z, startIndex, numPoints);
}
// Adjust to new prime meridian if there is one in the destination cs
fromGreenwich = dest.GeographicInfo.Meridian.Longitude * dest.GeographicInfo.Unit.Radians;
if (fromGreenwich != 0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] != double.PositiveInfinity)
{
xy[i * 2] -= fromGreenwich;
}
}
}
if (dest.IsGeocentric)
{
if (z == null)
{
throw new ProjectionException(45);
}
GeocentricGeodetic g = new GeocentricGeodetic(dest.GeographicInfo.Datum.Spheroid);
g.GeodeticToGeocentric(xy, z, startIndex, numPoints);
double frmMeter = 1 / dest.Unit.Meters;
if (frmMeter != 1)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] != double.PositiveInfinity)
{
xy[i * 2] *= frmMeter;
xy[i * 2 + 1] *= frmMeter;
}
}
}
}
else
{
ConvertToProjected(dest, xy, z, dstZtoMeter, startIndex, numPoints);
}
}
private static void ConvertToProjected(ProjectionInfo dest, double[] xy, double[] z, double dstZtoMeter, int startIndex, int numPoints)
{
double frmMeter = 1 / dest.Unit.Meters;
double frmZMeter = 1 / dstZtoMeter;
bool geoc = dest.Geoc;
double lam0 = dest.Lam0;
double roneEs = 1 / (1 - dest.GeographicInfo.Datum.Spheroid.EccentricitySquared());
bool over = dest.Over;
double x0 = 0;
double y0 = 0;
if (dest.FalseEasting.HasValue) x0 = dest.FalseEasting.Value;
if (dest.FalseNorthing.HasValue) y0 = dest.FalseNorthing.Value;
double a = dest.GeographicInfo.Datum.Spheroid.EquatorialRadius;
for (int i = startIndex; i < numPoints; i++)
{
double lam = xy[2 * i];
double phi = xy[2 * i + 1];
double t = Math.Abs(phi) - Math.PI / 2;
if (t > EPS || Math.Abs(lam) > 10)
{
xy[2 * i] = double.PositiveInfinity;
xy[2 * i + 1] = double.PositiveInfinity;
continue;
}
if (Math.Abs(t) <= EPS)
{
xy[2 * i + 1] = phi < 0 ? -Math.PI / 2 : Math.PI / 2;
}
else if (geoc)
{
xy[2 * i + 1] = Math.Atan(roneEs * Math.Tan(phi));
}
xy[2 * i] -= lam0;
if (!over)
{
xy[2 * i] = Adjlon(xy[2 * i]);
}
}
// break this out because we don't want a chatty call to extension transforms
dest.Transform.Forward(xy, startIndex, numPoints);
if (dstZtoMeter == 1.0)
{
for (int i = startIndex; i < numPoints; i++)
{
xy[2 * i] = frmMeter * (a * xy[2 * i] + x0);
xy[2 * i + 1] = frmMeter * (a * xy[2 * i + 1] + y0);
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
xy[2 * i] = frmMeter * (a * xy[2 * i] + x0);
xy[2 * i + 1] = frmMeter * (a * xy[2 * i + 1] + y0);
z[i] *= frmZMeter;
}
}
}
private static void DatumTransform(ProjectionInfo source, ProjectionInfo dest, double[] xy, double[] z, int startIndex, int numPoints)
{
Spheroid wgs84 = new Spheroid(Proj4Ellipsoid.WGS_1984);
Datum sDatum = source.GeographicInfo.Datum;
Datum dDatum = dest.GeographicInfo.Datum;
/* -------------------------------------------------------------------- */
/* We cannot do any meaningful datum transformation if either */
/* the source or destination are of an unknown datum type */
/* (ie. only a +ellps declaration, no +datum). This is new */
/* behavior for PROJ 4.6.0. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.Unknown ||
dDatum.DatumType == DatumType.Unknown) return;
/* -------------------------------------------------------------------- */
/* Short cut if the datums are identical. */
/* -------------------------------------------------------------------- */
if (sDatum.Matches(dDatum)) return;
// proj4 actually allows some tollerance here
if (sDatum.DatumType == dDatum.DatumType)
{
if (sDatum.Spheroid.EquatorialRadius == dDatum.Spheroid.EquatorialRadius)
{
if (Math.Abs(sDatum.Spheroid.EccentricitySquared() - dDatum.Spheroid.EccentricitySquared()) < 0.000000000050)
{
// The tolerence is to allow GRS80 and WGS84 to escape without being transformed at all.
return;
}
}
}
double srcA = sDatum.Spheroid.EquatorialRadius;
double srcEs = sDatum.Spheroid.EccentricitySquared();
double dstA = dDatum.Spheroid.EquatorialRadius;
double dstEs = dDatum.Spheroid.EccentricitySquared();
/* -------------------------------------------------------------------- */
/* Create a temporary Z value if one is not provided. */
/* -------------------------------------------------------------------- */
if (z == null)
{
z = new double[xy.Length / 2];
}
/* -------------------------------------------------------------------- */
/* If this datum requires grid shifts, then apply it to geodetic */
/* coordinates. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.GridShift)
{
// pj_apply_gridshift(pj_param(srcdefn->params,"snadgrids").s, 0,
// point_count, point_offset, x, y, z );
GridShift.Apply(source.GeographicInfo.Datum.NadGrids, false, xy, startIndex, numPoints);
srcA = wgs84.EquatorialRadius;
srcEs = wgs84.EccentricitySquared();
}
if (dDatum.DatumType == DatumType.GridShift)
{
dstA = wgs84.EquatorialRadius;
dstEs = wgs84.EccentricitySquared();
}
/* ==================================================================== */
/* Do we need to go through geocentric coordinates? */
/* ==================================================================== */
if (srcEs != dstEs || srcA != dstA
|| sDatum.DatumType == DatumType.Param3
|| sDatum.DatumType == DatumType.Param7
|| dDatum.DatumType == DatumType.Param3
|| dDatum.DatumType == DatumType.Param7)
{
/* -------------------------------------------------------------------- */
/* Convert to geocentric coordinates. */
/* -------------------------------------------------------------------- */
GeocentricGeodetic gc = new GeocentricGeodetic(sDatum.Spheroid);
gc.GeodeticToGeocentric(xy, z, startIndex, numPoints);
/* -------------------------------------------------------------------- */
/* Convert between datums. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.Param3 || sDatum.DatumType == DatumType.Param7)
{
PjGeocentricToWgs84(source, xy, z, startIndex, numPoints);
}
if (dDatum.DatumType == DatumType.Param3 || dDatum.DatumType == DatumType.Param7)
{
PjGeocentricFromWgs84(dest, xy, z, startIndex, numPoints);
}
/* -------------------------------------------------------------------- */
/* Convert back to geodetic coordinates. */
/* -------------------------------------------------------------------- */
gc = new GeocentricGeodetic(dDatum.Spheroid);
gc.GeocentricToGeodetic(xy, z, startIndex, numPoints);
}
/* -------------------------------------------------------------------- */
/* Apply grid shift to destination if required. */
/* -------------------------------------------------------------------- */
if (dDatum.DatumType == DatumType.GridShift)
{
// pj_apply_gridshift(pj_param(dstdefn->params,"snadgrids").s, 1,
// point_count, point_offset, x, y, z );
GridShift.Apply(dest.GeographicInfo.Datum.NadGrids, true, xy, startIndex, numPoints);
}
}
private static void ConvertToLatLon(ProjectionInfo source, double[] xy, double[] z, double srcZtoMeter, int startIndex, int numPoints)
{
double toMeter = 1.0;
if (source.Unit != null) toMeter = source.Unit.Meters;
double oneEs = 1 - source.GeographicInfo.Datum.Spheroid.EccentricitySquared();
double ra = 1 / source.GeographicInfo.Datum.Spheroid.EquatorialRadius;
double x0 = 0;
if (source.FalseEasting != null) x0 = source.FalseEasting.Value;
double y0 = 0;
if (source.FalseNorthing != null) y0 = source.FalseNorthing.Value;
if (srcZtoMeter == 1.0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] == double.PositiveInfinity || xy[i * 2 + 1] == double.PositiveInfinity)
{
// This might be error worthy, but not sure if we want to throw an exception here
continue;
}
// descale and de-offset
xy[i * 2] = (xy[i * 2] * toMeter - x0) * ra;
xy[i * 2 + 1] = (xy[i * 2 + 1] * toMeter - y0) * ra;
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] == double.PositiveInfinity || xy[i * 2 + 1] == double.PositiveInfinity)
{
// This might be error worthy, but not sure if we want to throw an exception here
continue;
}
// descale and de-offset
xy[i * 2] = (xy[i * 2] * toMeter - x0) * ra;
xy[i * 2 + 1] = (xy[i * 2 + 1] * toMeter - y0) * ra;
z[i] *= srcZtoMeter;
}
}
if (source.Transform != null)
{
source.Transform.Inverse(xy, startIndex, numPoints);
}
for (int i = startIndex; i < numPoints; i++)
{
double lam0 = source.Lam0;
xy[i * 2] += lam0;
if (!source.Over)
{
xy[i*2] = Adjlon(xy[i*2]);
}
if (source.Geoc && Math.Abs(Math.Abs(xy[i * 2 + 1]) - Math.PI / 2) > EPS)
{
xy[i * 2 + 1] = Math.Atan(oneEs * Math.Tan(xy[i * 2 + 1]));
}
}
}
private static double Adjlon(double lon)
{
if (Math.Abs(lon) <= Math.PI + Math.PI / 72) return (lon);
lon += Math.PI; /* adjust to 0..2pi rad */
lon -= 2 * Math.PI * Math.Floor(lon / (2 * Math.PI)); /* remove integral # of 'revolutions'*/
lon -= Math.PI; /* adjust back to -pi..pi rad */
return (lon);
}
private static void PjGeocentricToWgs84(ProjectionInfo source, double[] xy, double[] zArr, int startIndex, int numPoints)
{
double[] shift = source.GeographicInfo.Datum.ToWGS84;
if (source.GeographicInfo.Datum.DatumType == DatumType.Param3)
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
xy[2 * i] = xy[2 * i] + shift[0]; // dx
xy[2 * i + 1] = xy[2 * i + 1] + shift[1]; // dy
zArr[i] = zArr[i] + shift[2];
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
double x = xy[2 * i];
double y = xy[2 * i + 1];
double z = zArr[i];
xy[2 * i] = shift[6] * (x - shift[5] * y + shift[4] * z) + shift[0];
xy[2 * i + 1] = shift[6] * (shift[5] * x + y - shift[3] * z) + shift[1];
zArr[i] = shift[6] * (-shift[4] * x + shift[3] * y + z) + shift[2];
}
}
}
private static void PjGeocentricFromWgs84(ProjectionInfo dest, double[] xy, double[] zArr, int startIndex, int numPoints)
{
double[] shift = dest.GeographicInfo.Datum.ToWGS84;
if (dest.GeographicInfo.Datum.DatumType == DatumType.Param3)
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
xy[2 * i] = xy[2 * i] - shift[0]; // dx
xy[2 * i + 1] = xy[2 * i + 1] - shift[1]; // dy
zArr[i] = zArr[i] - shift[2];
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
double x = (xy[2 * i] - shift[0]) / shift[6];
double y = (xy[2 * i + 1] - shift[1]) / shift[6];
double z = (zArr[i] - shift[2]) / shift[6];
xy[2 * i] = x + shift[5] * y - shift[4] * z;
xy[2 * i + 1] = -shift[5] * x + y + shift[3] * z;
zArr[i] = shift[4] * x - shift[3] * y + z;
}
}
}
#endregion
#region Properties
#endregion
}
}
| |
namespace Nixxis.Windows.Controls
{
partial class SelectionConnectionString
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.txtUserId = new System.Windows.Forms.TextBox();
this.txtPassword = new System.Windows.Forms.TextBox();
this.txtDataSource = new System.Windows.Forms.TextBox();
this.txtInitialCatalog = new System.Windows.Forms.TextBox();
this.txtOptions = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.txtConnectionString = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.btnSet = new System.Windows.Forms.Button();
this.tableLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.txtUserId, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.txtPassword, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.txtDataSource, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.txtInitialCatalog, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.txtOptions, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.label4, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.label5, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 6);
this.tableLayoutPanel1.Controls.Add(this.label6, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.btnSet, 1, 7);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 8;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 39.9976F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 60.0024F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(261, 173);
this.tableLayoutPanel1.TabIndex = 0;
//
// txtUserId
//
this.txtUserId.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtUserId.Location = new System.Drawing.Point(100, 0);
this.txtUserId.Margin = new System.Windows.Forms.Padding(0);
this.txtUserId.Name = "txtUserId";
this.txtUserId.Size = new System.Drawing.Size(161, 20);
this.txtUserId.TabIndex = 0;
this.txtUserId.TextChanged += new System.EventHandler(this.txtUserId_TextChanged);
//
// txtPassword
//
this.txtPassword.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtPassword.Location = new System.Drawing.Point(100, 20);
this.txtPassword.Margin = new System.Windows.Forms.Padding(0);
this.txtPassword.Name = "txtPassword";
this.txtPassword.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(161, 20);
this.txtPassword.TabIndex = 1;
this.txtPassword.TextChanged += new System.EventHandler(this.txtPassword_TextChanged);
//
// txtDataSource
//
this.txtDataSource.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtDataSource.Location = new System.Drawing.Point(100, 40);
this.txtDataSource.Margin = new System.Windows.Forms.Padding(0);
this.txtDataSource.Name = "txtDataSource";
this.txtDataSource.Size = new System.Drawing.Size(161, 20);
this.txtDataSource.TabIndex = 2;
this.txtDataSource.TextChanged += new System.EventHandler(this.txtDataSource_TextChanged);
//
// txtInitialCatalog
//
this.txtInitialCatalog.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtInitialCatalog.Location = new System.Drawing.Point(100, 60);
this.txtInitialCatalog.Margin = new System.Windows.Forms.Padding(0);
this.txtInitialCatalog.Name = "txtInitialCatalog";
this.txtInitialCatalog.Size = new System.Drawing.Size(161, 20);
this.txtInitialCatalog.TabIndex = 3;
this.txtInitialCatalog.TextChanged += new System.EventHandler(this.txtInitialCatalog_TextChanged);
//
// txtOptions
//
this.txtOptions.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtOptions.Location = new System.Drawing.Point(100, 80);
this.txtOptions.Margin = new System.Windows.Forms.Padding(0);
this.txtOptions.Multiline = true;
this.txtOptions.Name = "txtOptions";
this.txtOptions.Size = new System.Drawing.Size(161, 21);
this.txtOptions.TabIndex = 4;
this.txtOptions.TextChanged += new System.EventHandler(this.txtOptions_TextChanged);
//
// label1
//
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(94, 20);
this.label1.TabIndex = 5;
this.label1.Text = "User Id";
this.label1.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label2
//
this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
this.label2.Location = new System.Drawing.Point(3, 20);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(94, 20);
this.label2.TabIndex = 6;
this.label2.Text = "Password";
this.label2.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label3
//
this.label3.Dock = System.Windows.Forms.DockStyle.Fill;
this.label3.Location = new System.Drawing.Point(3, 40);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(94, 20);
this.label3.TabIndex = 7;
this.label3.Text = "Data Source";
this.label3.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label4
//
this.label4.Dock = System.Windows.Forms.DockStyle.Fill;
this.label4.Location = new System.Drawing.Point(3, 60);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(94, 20);
this.label4.TabIndex = 8;
this.label4.Text = "Initial Catalog";
this.label4.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label5
//
this.label5.Dock = System.Windows.Forms.DockStyle.Fill;
this.label5.Location = new System.Drawing.Point(3, 80);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(94, 21);
this.label5.TabIndex = 9;
this.label5.Text = "Options";
this.label5.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// panel1
//
this.tableLayoutPanel1.SetColumnSpan(this.panel1, 2);
this.panel1.Controls.Add(this.txtConnectionString);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 121);
this.panel1.Margin = new System.Windows.Forms.Padding(0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(261, 31);
this.panel1.TabIndex = 10;
//
// txtConnectionString
//
this.txtConnectionString.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtConnectionString.Location = new System.Drawing.Point(0, 0);
this.txtConnectionString.Multiline = true;
this.txtConnectionString.Name = "txtConnectionString";
this.txtConnectionString.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtConnectionString.Size = new System.Drawing.Size(261, 31);
this.txtConnectionString.TabIndex = 5;
this.txtConnectionString.TextChanged += new System.EventHandler(this.txtConnectionString_TextChanged);
//
// label6
//
this.tableLayoutPanel1.SetColumnSpan(this.label6, 2);
this.label6.Dock = System.Windows.Forms.DockStyle.Fill;
this.label6.Location = new System.Drawing.Point(3, 101);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(255, 20);
this.label6.TabIndex = 11;
this.label6.Text = "ConnectionString";
this.label6.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// btnSet
//
this.btnSet.Location = new System.Drawing.Point(100, 152);
this.btnSet.Margin = new System.Windows.Forms.Padding(0);
this.btnSet.Name = "btnSet";
this.btnSet.Size = new System.Drawing.Size(39, 20);
this.btnSet.TabIndex = 6;
this.btnSet.Text = "Set";
this.btnSet.UseVisualStyleBackColor = true;
this.btnSet.Click += new System.EventHandler(this.btnSet_Click);
//
// SelectionConnectionString
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "SelectionConnectionString";
this.Size = new System.Drawing.Size(261, 173);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TextBox txtUserId;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.TextBox txtDataSource;
private System.Windows.Forms.TextBox txtInitialCatalog;
private System.Windows.Forms.TextBox txtOptions;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TextBox txtConnectionString;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Button btnSet;
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using Microsoft.Win32;
using DeOps.Implementation;
using DeOps.Implementation.Dht;
using DeOps.Implementation.Transport;
using DeOps.Services;
using DeOps.Services.Transfer;
using DeOps.Interface;
using DeOps.Interface.Tools;
namespace DeOps.Simulator
{
public delegate void RunServiceMethod(OpService service);
public partial class SimForm : CustomIconForm
{
public AppContext App;
public InternetSim Sim;
private ListViewColumnSorter lvwColumnSorter = new ListViewColumnSorter();
public Dictionary<ulong, NetView> NetViews = new Dictionary<ulong, NetView>();
FileStream TimeFile;
public int UiThreadId;
//bool Loaded;
//string DelayLoadPath;
public SimForm(AppContext app)
{
Construct();
App = app;
}
public SimForm(string path, AppContext app)
{
Construct();
App = app;
//DelayLoadPath = path;
}
void Construct()
{
InitializeComponent();
ListInstances.ListViewItemSorter = lvwColumnSorter;
UiThreadId = Thread.CurrentThread.ManagedThreadId;
Sim = new InternetSim(Application.StartupPath, InterfaceRes.deops);
}
private void ControlForm_Load(object sender, EventArgs e)
{
Sim.InstanceChange += new InstanceChangeHandler(OnInstanceChange);
}
private void LoadMenuItem_Click(object sender, EventArgs e)
{
// choose folder to load from
try
{
FolderBrowserDialog browse = new FolderBrowserDialog();
string path = App.Settings.LastSimPath;
if (path == null)
path = Application.StartupPath;
browse.SelectedPath = path;
if (browse.ShowDialog(this) != DialogResult.OK)
return;
LoadDirectory(browse.SelectedPath);
App.Settings.LastSimPath = browse.SelectedPath;
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message);
}
}
private void LoadDirectory(string dirpath)
{
Sim.LoadedPath = dirpath;
if (Sim.UseTimeFile)
{
TimeFile = new FileStream(dirpath + Path.DirectorySeparatorChar + "time.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
if (TimeFile.Length >= 8)
{
byte[] startTime = new byte[8];
TimeFile.Read(startTime, 0, 8);
Sim.TimeNow = DateTime.FromBinary(BitConverter.ToInt64(startTime, 0));
Sim.StartTime = Sim.TimeNow;
}
}
string[] dirs = Directory.GetDirectories(dirpath);
LoadProgress.Visible = true;
LoadProgress.Maximum = dirs.Length;
LoadProgress.Value = 0;
foreach (string dir in dirs)
{
string[] paths = Directory.GetFiles(dir, "*.dop");
foreach (string path in paths)
{
string filename = Path.GetFileNameWithoutExtension(path);
string[] parts = filename.Split('-');
string op = parts[0].Trim();
string name = parts[1].Trim();
// if instance with same user name, who has not joined this operation - add to same instance
SimInstance instance = null;
Sim.Instances.LockReading(() =>
instance = Sim.Instances.Where(i => i.Name == name && !i.Ops.Contains(op)).FirstOrDefault());
if (instance != null)
Login(instance, path);
else
Sim.StartInstance(path);
}
LoadProgress.Value = LoadProgress.Value + 1;
Application.DoEvents();
}
LoadProgress.Visible = false;
}
private void Login(SimInstance instance, string path)
{
try
{
Sim.Login(instance, path);
}
catch (Exception ex)
{
MessageBox.Show(this, instance.Name + ": " + ex.Message);
return;
}
}
private void SaveMenuItem_Click(object sender, EventArgs e)
{
Sim.Pause();
Sim.Instances.SafeForEach(instance =>
{
instance.Context.Cores.LockReading(delegate()
{
foreach (OpCore core in instance.Context.Cores)
core.User.Save();
});
});
MessageBox.Show(this, "Nodes Saved");
}
private void ExitMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void buttonStart_Click(object sender, EventArgs e)
{
Sim.Start();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
Sim.DoStep();
}
private void buttonPause_Click(object sender, EventArgs e)
{
Sim.Pause();
}
void OnInstanceChange(SimInstance instance, InstanceChangeType type)
{
if (Thread.CurrentThread.ManagedThreadId != UiThreadId)
{
BeginInvoke(Sim.InstanceChange, instance, type);
return;
}
// add
if (type == InstanceChangeType.Add)
{
AddItem(instance);
}
// refresh
else if (type == InstanceChangeType.Refresh)
{
ListInstances.Items.Clear();
Sim.Instances.SafeForEach(i =>
{
AddItem(i);
});
LabelInstances.Text = Sim.Instances.SafeCount.ToString() + " Instances";
}
// update
else if (type == InstanceChangeType.Update)
{
foreach (ListInstanceItem item in ListInstances.Items)
if (item.Instance == instance)
{
item.Refresh();
break;
}
}
// remove
else if (type == InstanceChangeType.Remove)
{
foreach (ListInstanceItem item in ListInstances.Items)
if (item.Instance == instance)
{
ListInstances.Items.Remove(item);
break;
}
}
}
private void AddItem(SimInstance instance)
{
instance.Context.Cores.LockReading(delegate()
{
foreach (OpCore core in instance.Context.Cores)
ListInstances.Items.Add(new ListInstanceItem(core));
if (instance.Context.Cores.Count == 0)
ListInstances.Items.Add(new ListInstanceItem(instance));
});
}
DateTime LastSimTime = new DateTime(2006, 1, 1, 0, 0, 0);
private void SecondTimer_Tick(object sender, EventArgs e)
{
TimeSpan total = Sim.TimeNow - Sim.StartTime;
TimeSpan real = Sim.TimeNow - LastSimTime;
LastSimTime = Sim.TimeNow;
labelTime.Text = SpantoString(real);
TimeLabel.Text = Sim.TimeNow.ToString();
ElapsedLabel.Text = SpantoString(total);
if (Sim.UseTimeFile && TimeFile != null)
{
TimeFile.Seek(0, SeekOrigin.Begin);
TimeFile.Write(BitConverter.GetBytes(Sim.TimeNow.ToBinary()), 0, 8);
}
/*if (Loaded && DelayLoadPath != null)
{
string path = DelayLoadPath;
DelayLoadPath = null; // done because doevents will refire
LoadDirectory(Application.StartupPath + Path.DirectorySeparatorChar + path);
}*/
}
string SpantoString(TimeSpan span)
{
string postfix = "";
if (span.Milliseconds == 0)
postfix += ".00";
else
postfix += "." + span.Milliseconds.ToString().Substring(0, 2);
span = span.Subtract(new TimeSpan(0, 0, 0, 0, span.Milliseconds));
return span.ToString() + postfix;
}
private void ControlForm_FormClosing(object sender, FormClosingEventArgs e)
{
Sim.Exit();
Application.Exit();
}
private void listInstances_MouseClick(object sender, MouseEventArgs e)
{
// main
// internal
// global
// crawler
// graph
// packets
// search
// operation
// console
// ---
// Disconnect
if (e.Button != MouseButtons.Right)
return;
ListInstanceItem item = ListInstances.GetItemAt(e.X, e.Y) as ListInstanceItem;
if (item == null)
return;
ContextMenu menu = new ContextMenu();
if(item.Core == null)
menu.MenuItems.Add(new MenuItem("Login", new EventHandler(Click_Connect)));
else
{
MenuItem global = null;
if (item.Instance.Context.Lookup != null)
{
global = new MenuItem("Lookup");
global.MenuItems.Add(new MenuItem("Crawler", new EventHandler(Click_GlobalCrawler)));
global.MenuItems.Add(new MenuItem("Graph", new EventHandler(Click_GlobalGraph)));
global.MenuItems.Add(new MenuItem("Packets", new EventHandler(Click_GlobalPackets)));
global.MenuItems.Add(new MenuItem("Search", new EventHandler(Click_GlobalSearch)));
}
MenuItem operation = new MenuItem("Organization");
operation.MenuItems.Add(new MenuItem("Crawler", new EventHandler(Click_OpCrawler)));
operation.MenuItems.Add(new MenuItem("Graph", new EventHandler(Click_OpGraph)));
operation.MenuItems.Add(new MenuItem("Packets", new EventHandler(Click_OpPackets)));
operation.MenuItems.Add(new MenuItem("Search", new EventHandler(Click_OpSearch)));
MenuItem firewall = new MenuItem("Firewall");
firewall.MenuItems.Add(new MenuItem("Open", new EventHandler(Click_FwOpen)));
firewall.MenuItems.Add(new MenuItem("NAT", new EventHandler(Click_FwNAT)));
firewall.MenuItems.Add(new MenuItem("Blocked", new EventHandler(Click_FwBlocked)));
menu.MenuItems.Add(new MenuItem("Main", new EventHandler(Click_Main)));
menu.MenuItems.Add(new MenuItem("Internal", new EventHandler(Click_Internal)));
menu.MenuItems.Add(new MenuItem("Bandwidth", new EventHandler(Click_Bandwidth)));
menu.MenuItems.Add(new MenuItem("Transfers", new EventHandler(Click_Transfers)));
if(global != null) menu.MenuItems.Add(global);
menu.MenuItems.Add(operation);
menu.MenuItems.Add(firewall);
menu.MenuItems.Add(new MenuItem("Console", new EventHandler(Click_Console)));
menu.MenuItems.Add(new MenuItem("-"));
menu.MenuItems.Add(new MenuItem("Logout", new EventHandler(Click_Disconnect)));
}
menu.Show(ListInstances, e.Location);
}
private void listInstances_MouseDoubleClick(object sender, MouseEventArgs e)
{
Click_Main(null, null);
}
private void Click_Main(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
{
OpCore core = item.Core;
if (core == null)
{
item.Instance.Context.RaiseLogin(null);
return;
}
if (item.UI.GuiMain == null)
item.UI.ShowMainView();
item.UI.GuiMain.Activate();
}
}
private void Click_FwOpen(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
{
item.Instance.RealFirewall = FirewallType.Open;
OnInstanceChange(item.Instance, InstanceChangeType.Update);
}
}
private void Click_FwNAT(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
{
item.Instance.RealFirewall = FirewallType.NAT;
OnInstanceChange(item.Instance, InstanceChangeType.Update);
}
}
private void Click_FwBlocked(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
{
item.Instance.RealFirewall = FirewallType.Blocked;
OnInstanceChange(item.Instance, InstanceChangeType.Update);
}
}
private void Click_Console(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
{
CoreUI ui = item.UI;
if (ui.GuiConsole == null)
ui.GuiConsole = new ConsoleForm(ui);
ui.GuiConsole.Show();
ui.GuiConsole.Activate();
}
}
private void Click_Internal(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
InternalsForm.Show(item.UI);
}
private void Click_Bandwidth(object sender, EventArgs e)
{
List<OpCore> cores = new List<OpCore>();
foreach (ListInstanceItem item in ListInstances.SelectedItems)
{
if (!cores.Contains(item.Core.Context.Lookup))
cores.Add(item.Core.Context.Lookup);
cores.Add(item.Core);
}
new BandwidthForm(cores).Show();
}
private void Click_Transfers(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
TransferView.Show(item.Core.Network);
}
private void Click_GlobalCrawler(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
if (item.Core.Context.Lookup != null)
CrawlerForm.Show(item.Core.Context.Lookup.Network);
}
private void Click_GlobalGraph(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
if (item.Core.Context.Lookup != null)
PacketsForm.Show(item.Core.Context.Lookup.Network);
}
private void Click_GlobalPackets(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
if (item.Core.Context.Lookup != null)
PacketsForm.Show(item.Core.Context.Lookup.Network);
}
private void Click_GlobalSearch(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
if (item.Core.Context.Lookup != null)
SearchForm.Show(item.Core.Context.Lookup.Network);
}
private void Click_OpCrawler(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
CrawlerForm.Show(item.Core.Network);
}
private void Click_OpGraph(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
GraphForm.Show(item.Core.Network);
}
private void Click_OpPackets(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
PacketsForm.Show(item.Core.Network);
}
private void Click_OpSearch(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
SearchForm.Show(item.Core.Network);
}
private void Click_Connect(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
if(item.Core == null)
Login(item.Instance, item.Instance.LastPath);
OnInstanceChange(null, InstanceChangeType.Refresh);
}
private void Click_Disconnect(object sender, EventArgs e)
{
foreach (ListInstanceItem item in ListInstances.SelectedItems)
if (item.Core != null)
{
OpCore core = item.Core;
item.Core = null; // remove list item reference
Sim.Logout(core);
}
}
private void listInstances_ColumnClick(object sender, ColumnClickEventArgs e)
{
// Determine if clicked column is already the column that is being sorted.
if (e.Column == lvwColumnSorter.ColumnToSort)
{
// Reverse the current sort direction for this column.
if (lvwColumnSorter.OrderOfSort == SortOrder.Ascending)
lvwColumnSorter.OrderOfSort = SortOrder.Descending;
else
lvwColumnSorter.OrderOfSort = SortOrder.Ascending;
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvwColumnSorter.ColumnToSort = e.Column;
lvwColumnSorter.OrderOfSort = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
ListInstances.Sort();
}
private void LinkUpdate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
OnInstanceChange(null, InstanceChangeType.Refresh);
//Sim.Instances.SafeForEach(instance =>
// OnInstanceChange(instance, InstanceChangeType.Update);
}
private void ViewMenu_DropDownOpening(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item == null || Sim == null)
return;
item.DropDownItems.Clear();
item.DropDownItems.Add(new ViewMenuItem("Lookup", 0, new EventHandler(ViewMenu_OnClick)));
foreach(ulong id in Sim.OpNames.Keys)
item.DropDownItems.Add(new ViewMenuItem(Sim.OpNames[id], id, new EventHandler(ViewMenu_OnClick)));
}
private void ViewMenu_OnClick(object sender, EventArgs e)
{
ViewMenuItem item = sender as ViewMenuItem;
if (item == null || Sim == null)
return;
NetView view = null;
if (!NetViews.ContainsKey(item.OpID))
{
view = new NetView(this, item.OpID);
NetViews[item.OpID] = view;
}
else
view = NetViews[item.OpID];
view.Show();
view.BringToFront();
}
private void GenerateUsersMenuItem_Click(object sender, EventArgs e)
{
GenerateUsers form = new GenerateUsers();
form.ShowDialog();
}
private void OptionsMenuItem_DropDownOpening(object sender, EventArgs e)
{
/*string enc = "Encryption: ";
enc += Sim.TestEncryption ? "On" : "Off";
EncryptionMenuItem.Text = enc;*/
string text = "Speed: ";
text += Sim.SleepTime.ToString() + "ms";
SpeedMenuItem.Text = text;
FreshStartMenuItem.Checked = Sim.FreshStart;
LoadOnlineMenuItem.Checked = Sim.LoadOnline;
LoggingMenu.Checked = Sim.Logging;
LanMenu.Checked = Sim.LAN;
EncryptionMenu.Checked = Sim.TestEncryption;
}
private void SpeedMenuItem_Click(object sender, EventArgs e)
{
GetTextDialog getText = new GetTextDialog("Options", "Enter # of ms to sleep between sim ticks (1000ms is real-time)", Sim.SleepTime.ToString());
if (getText.ShowDialog() == DialogResult.OK)
int.TryParse(getText.ResultBox.Text, out Sim.SleepTime);
}
private void FreshStartMenuItem_Click(object sender, EventArgs e)
{
Sim.FreshStart = !Sim.FreshStart;
}
private void CollectMenuItem_Click(object sender, EventArgs e)
{
GC.Collect();
}
private void LoadOnlineMenu_Click(object sender, EventArgs e)
{
Sim.LoadOnline = !Sim.LoadOnline;
}
private void LoggingMenu_Click(object sender, EventArgs e)
{
Sim.Logging = !Sim.Logging;
}
private void UnloadAllMenuItem_Click(object sender, EventArgs e)
{
// unload
Sim.InstanceChange -= new InstanceChangeHandler(OnInstanceChange);
if (TimeFile != null)
{
TimeFile.Dispose();
TimeFile = null;
}
Sim.Exit();
// re-init
Sim = new InternetSim(Application.StartupPath, InterfaceRes.deops);
Sim.InstanceChange += new InstanceChangeHandler(OnInstanceChange);
OnInstanceChange(null, InstanceChangeType.Refresh);
}
private void LanMenu_Click(object sender, EventArgs e)
{
Sim.LAN = !Sim.LAN;
}
private void EncryptionMenu_Click(object sender, EventArgs e)
{
Sim.TestEncryption = !Sim.TestEncryption;
}
private void TestServicesMenu_Click(object sender, EventArgs e)
{
SelectServices form = new SelectServices(this, "Test Services", delegate(OpService service) { service.SimTest(); });
form.Show();
}
private void CleanupServicesMenu_Click(object sender, EventArgs e)
{
SelectServices form = new SelectServices(this, "Cleanup Services", delegate(OpService service) { service.SimCleanup(); });
form.Show();
}
}
public class ViewMenuItem : ToolStripMenuItem
{
public ulong OpID;
public ViewMenuItem(string name, ulong id, EventHandler onClick)
: base(name, null, onClick)
{
OpID = id;
}
}
public class ListInstanceItem : ListViewItem
{
public SimInstance Instance;
public OpCore Core;
public CoreUI UI;
public ListInstanceItem(SimInstance instance)
{
// empty context
Instance = instance;
Refresh();
}
public ListInstanceItem(OpCore core)
{
Core = core;
UI = new CoreUI(core);
Instance = core.Sim;
Core.Exited += Core_Exited;
Refresh();
}
void Core_Exited(OpCore core)
{
if (UI.GuiMain != null)
UI.GuiMain.Close();
}
public void Refresh()
{
int SUBITEM_COUNT = 11;
while (SubItems.Count < SUBITEM_COUNT)
SubItems.Add("");
Text = Instance.Index.ToString();
if (Core == null)
{
SubItems[1].Text = "Login: " + Path.GetFileNameWithoutExtension(Instance.LastPath);
ForeColor = Color.Gray;
for(int i = 2; i < SUBITEM_COUNT; i++)
SubItems[i].Text = "";
return;
}
ForeColor = Color.Black;
// 0 context index
// 1 user
// 2 op
// 3 Dht id
// 4 client id
// 5 firewall
// 6 alerts
// 7 proxies
// 8 Notes
// 9 bytes in
// 10 bytes out
// alerts...
string alerts = "";
// firewall incorrect
if (Instance.RealFirewall != Core.Firewall)
alerts += "Firewall, ";
// ip incorrect
//if (Instance.Context.LocalIP != null && !Instance.RealIP.Equals(Instance.Context.LocalIP))
// alerts += "IP Mismatch, ";
// routing unresponsive global/op
if(Instance.Context.Lookup != null)
if (!Instance.Context.Lookup.Network.Responsive)
alerts += "Lookup Routing, ";
if (!Core.Network.Responsive)
alerts += "Op Routing, ";
// not proxied global/op
if (Instance.RealFirewall != FirewallType.Open)
{
if (Instance.Context.Lookup != null)
if (Instance.Context.Lookup.Network.TcpControl.ProxyMap.Count == 0)
alerts += "Lookup Proxy, ";
if (Core.Network.TcpControl.ProxyMap.Count == 0)
alerts += "Op Proxy, ";
}
// locations
if (Core.Locations.Clients.SafeCount <= 1)
alerts += "Locs, ";
SubItems[1].Text = Core.User.Settings.UserName;
SubItems[2].Text = Core.User.Settings.Operation;
SubItems[3].Text = Utilities.IDtoBin(Core.UserID);
SubItems[4].Text = Instance.RealIP.ToString() + "/" + Core.Network.Local.ClientID.ToString();
SubItems[5].Text = Instance.RealFirewall.ToString();
SubItems[6].Text = alerts;
if (Instance.Context.Lookup != null)
{
SubItems[7].Text = ProxySummary(Instance.Context.Lookup.Network.TcpControl);
SubItems[8].Text = NotesSummary();
}
SubItems[9].Text = Utilities.CommaIze(Instance.BytesRecvd);
SubItems[10].Text = Utilities.CommaIze(Instance.BytesSent);
}
private string ProxySummary(TcpHandler control)
{
StringBuilder summary = new StringBuilder();
lock (control.SocketList)
foreach (TcpConnect connect in control.SocketList)
if (connect.State == TcpState.Connected &&
(connect.Proxy == ProxyType.ClientBlocked || connect.Proxy == ProxyType.ClientNAT) &&
Instance.Internet.UserNames.ContainsKey(connect.UserID))
summary.Append(Instance.Internet.UserNames[connect.UserID] + ", ");
return summary.ToString();
}
private string NotesSummary()
{
//crit change store to other column at end total searches and transfers to detect backlogs
StringBuilder summary = new StringBuilder();
if(Core.Trust != null)
summary.Append(Core.Trust.TrustMap.SafeCount.ToString() + " trust, ");
summary.Append(Core.Locations.Clients.SafeCount.ToString() + " locs, ");
summary.Append(Core.Network.Searches.Pending.Count.ToString() + " searches, ");
summary.Append(Core.Transfers.Transfers.Count.ToString() + " transfers, ");
summary.Append(Core.Network.RudpControl.SessionMap.Count.ToString() + " sessions");
//foreach (ulong key in store.Index.Keys)
// foreach (StoreData data in store.Index[key])
// if (data.Kind == DataKind.Profile)
// summary.Append(((ProfileData)data.Packet).Name + ", ");
//foreach (ulong key in store.Index.Keys)
// if(Instance.Internet.OpNames.ContainsKey(key))
// summary.Append(Instance.Internet.OpNames[key] + " " + store.Index[key].Count + ", ");
return summary.ToString();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008-2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework
{
/// <summary>
/// TestCaseAttribute is used to mark parameterized test cases
/// and provide them with their arguments.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)]
public class TestCaseAttribute : NUnitAttribute, ITestBuilder, ITestCaseData, IImplyFixture
{
#region Constructors
/// <summary>
/// Construct a TestCaseAttribute with a list of arguments.
/// This constructor is not CLS-Compliant
/// </summary>
/// <param name="arguments"></param>
public TestCaseAttribute(params object[] arguments)
{
RunState = RunState.Runnable;
if (arguments == null)
Arguments = new object[] { null };
else
Arguments = arguments;
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a single argument
/// </summary>
/// <param name="arg"></param>
public TestCaseAttribute(object arg)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg };
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a two arguments
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
public TestCaseAttribute(object arg1, object arg2)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg1, arg2 };
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a three arguments
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
public TestCaseAttribute(object arg1, object arg2, object arg3)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg1, arg2, arg3 };
Properties = new PropertyBag();
}
#endregion
#region ITestData Members
/// <summary>
/// Gets or sets the name of the test.
/// </summary>
/// <value>The name of the test.</value>
public string TestName { get; set; }
/// <summary>
/// Gets or sets the RunState of this test case.
/// </summary>
public RunState RunState { get; private set; }
/// <summary>
/// Gets the list of arguments to a test case
/// </summary>
public object[] Arguments { get; private set; }
/// <summary>
/// Gets the properties of the test case
/// </summary>
public IPropertyBag Properties { get; private set; }
#endregion
#region ITestCaseData Members
/// <summary>
/// Gets or sets the expected result.
/// </summary>
/// <value>The result.</value>
public object ExpectedResult
{
get { return _expectedResult; }
set
{
_expectedResult = value;
HasExpectedResult = true;
}
}
private object _expectedResult;
/// <summary>
/// Returns true if the expected result has been set
/// </summary>
public bool HasExpectedResult { get; private set; }
#endregion
#region Other Properties
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
public string Description
{
get { return Properties.Get(PropertyNames.Description) as string; }
set { Properties.Set(PropertyNames.Description, value); }
}
/// <summary>
/// The author of this test
/// </summary>
public string Author
{
get { return Properties.Get(PropertyNames.Author) as string; }
set { Properties.Set(PropertyNames.Author, value); }
}
/// <summary>
/// The type that this test is testing
/// </summary>
public Type TestOf
{
get { return _testOf; }
set
{
_testOf = value;
Properties.Set(PropertyNames.TestOf, value.FullName);
}
}
private Type _testOf;
/// <summary>
/// Gets or sets the reason for ignoring the test
/// </summary>
public string Ignore
{
get { return IgnoreReason; }
set { IgnoreReason = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestCaseAttribute"/> is explicit.
/// </summary>
/// <value>
/// <c>true</c> if explicit; otherwise, <c>false</c>.
/// </value>
public bool Explicit
{
get { return RunState == RunState.Explicit; }
set { RunState = value ? RunState.Explicit : RunState.Runnable; }
}
/// <summary>
/// Gets or sets the reason for not running the test.
/// </summary>
/// <value>The reason.</value>
public string Reason
{
get { return Properties.Get(PropertyNames.SkipReason) as string; }
set { Properties.Set(PropertyNames.SkipReason, value); }
}
/// <summary>
/// Gets or sets the ignore reason. When set to a non-null
/// non-empty value, the test is marked as ignored.
/// </summary>
/// <value>The ignore reason.</value>
public string IgnoreReason
{
get { return Reason; }
set
{
RunState = RunState.Ignored;
Reason = value;
}
}
#if !PORTABLE
/// <summary>
/// Comma-delimited list of platforms to run the test for
/// </summary>
public string IncludePlatform { get; set; }
/// <summary>
/// Comma-delimited list of platforms to not run the test for
/// </summary>
public string ExcludePlatform { get; set; }
#endif
/// <summary>
/// Gets and sets the category for this test case.
/// May be a comma-separated list of categories.
/// </summary>
public string Category
{
get { return Properties.Get(PropertyNames.Category) as string; }
set
{
foreach (string cat in value.Split(new char[] { ',' }) )
Properties.Add(PropertyNames.Category, cat);
}
}
#endregion
#region Helper Methods
private TestCaseParameters GetParametersForTestCase(IMethodInfo method)
{
TestCaseParameters parms;
try
{
#if NETCF
var tmethod = method.MakeGenericMethodEx(Arguments);
if (tmethod == null)
throw new NotSupportedException("Cannot determine generic types from probing");
method = tmethod;
#endif
IParameterInfo[] parameters = method.GetParameters();
int argsNeeded = parameters.Length;
int argsProvided = Arguments.Length;
parms = new TestCaseParameters(this);
// Special handling for params arguments
if (argsNeeded > 0 && argsProvided >= argsNeeded - 1)
{
IParameterInfo lastParameter = parameters[argsNeeded - 1];
Type lastParameterType = lastParameter.ParameterType;
Type elementType = lastParameterType.GetElementType();
if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false))
{
if (argsProvided == argsNeeded)
{
Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType();
if (!lastParameterType.IsAssignableFrom(lastArgumentType))
{
Array array = Array.CreateInstance(elementType, 1);
array.SetValue(parms.Arguments[argsProvided - 1], 0);
parms.Arguments[argsProvided - 1] = array;
}
}
else
{
object[] newArglist = new object[argsNeeded];
for (int i = 0; i < argsNeeded && i < argsProvided; i++)
newArglist[i] = parms.Arguments[i];
int length = argsProvided - argsNeeded + 1;
Array array = Array.CreateInstance(elementType, length);
for (int i = 0; i < length; i++)
array.SetValue(parms.Arguments[argsNeeded + i - 1], i);
newArglist[argsNeeded - 1] = array;
parms.Arguments = newArglist;
argsProvided = argsNeeded;
}
}
}
//if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
// parms.Arguments = new object[]{parms.Arguments};
// Special handling when sole argument is an object[]
if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
{
if (argsProvided > 1 ||
argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[]))
{
parms.Arguments = new object[] { parms.Arguments };
}
}
if (argsProvided == argsNeeded)
PerformSpecialConversions(parms.Arguments, parameters);
}
catch (Exception ex)
{
parms = new TestCaseParameters(ex);
}
return parms;
}
/// <summary>
/// Performs several special conversions allowed by NUnit in order to
/// permit arguments with types that cannot be used in the constructor
/// of an Attribute such as TestCaseAttribute or to simplify their use.
/// </summary>
/// <param name="arglist">The arguments to be converted</param>
/// <param name="parameters">The ParameterInfo array for the method</param>
private static void PerformSpecialConversions(object[] arglist, IParameterInfo[] parameters)
{
for (int i = 0; i < arglist.Length; i++)
{
object arg = arglist[i];
Type targetType = parameters[i].ParameterType;
if (arg == null)
continue;
if (arg is SpecialValue && (SpecialValue)arg == SpecialValue.Null)
{
arglist[i] = null;
continue;
}
if (targetType.IsAssignableFrom(arg.GetType()))
continue;
#if !PORTABLE
if (arg is DBNull)
{
arglist[i] = null;
continue;
}
#endif
bool convert = false;
if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) ||
targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?))
{
convert = arg is int;
}
else if (targetType == typeof(decimal) || targetType == typeof(decimal?))
{
convert = arg is double || arg is string || arg is int;
}
else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?))
{
convert = arg is string;
}
if (convert)
{
Type convertTo = targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ?
targetType.GetGenericArguments()[0] : targetType;
arglist[i] = Convert.ChangeType(arg, convertTo, System.Globalization.CultureInfo.InvariantCulture);
}
// Convert.ChangeType doesn't work for TimeSpan from string
if ((targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?)) && arg is string)
{
TimeSpan value;
if(TimeSpan.TryParse((string)arg, out value))
arglist[i] = value;
}
}
}
#endregion
#region ITestBuilder Members
/// <summary>
/// Construct one or more TestMethods from a given MethodInfo,
/// using available parameter data.
/// </summary>
/// <param name="method">The MethodInfo for which tests are to be constructed.</param>
/// <param name="suite">The suite to which the tests will be added.</param>
/// <returns>One or more TestMethods</returns>
public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite)
{
TestMethod test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, GetParametersForTestCase(method));
#if !PORTABLE
if (test.RunState != RunState.NotRunnable &&
test.RunState != RunState.Ignored)
{
PlatformHelper platformHelper = new PlatformHelper();
if (!platformHelper.IsPlatformSupported(this))
{
test.RunState = RunState.Skipped;
test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason);
}
}
#endif
yield return test;
}
#endregion
}
}
| |
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 SIP_Grading_API.Areas.HelpPage.ModelDescriptions;
using SIP_Grading_API.Areas.HelpPage.Models;
namespace SIP_Grading_API.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);
}
}
}
}
| |
// Track BuildR
// Available on the Unity3D Asset Store
// Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com
// For support contact email@jasperstocker.com
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(TrackBuildR))]
public class TrackBuildREditor : Editor
{
private const float LINE_RESOLUTION = 0.005f;
private const float HANDLE_SCALE = 0.1f;
private TrackBuildR _trackBuildR;
private TrackBuildRTrack _track;
private float _handleSize;
[SerializeField]
private int selectedPoint = 0;//selected track point
[SerializeField]
private int selectedCurveIndex = 0;//selected curve
public static Texture2D[] _stageToolbarTexturesA;
public static Texture2D[] _stageToolbarTexturesB;
public static string[] trackModeString = new[] { "track", "boundary", "bumpers", "textures", "terrain", "stunt", "diagram", "options", "export" };
public static string[] pointModeString = new[] { "transform", "control points", "track up","track point" };
public static string[] boundaryModeString = new[] { "boundary transform", "boundary control points" };
public static string[] pitModeString = new[] { "edit pit lane", "set start point", "set end point" };
public const int numberOfMenuOptionsA = 5;
public const int numberOfMenuOptionsB = 4;
void OnEnable()
{
if (target != null)
{
_trackBuildR = (TrackBuildR)target;
_track = _trackBuildR.track;
}
_stageToolbarTexturesA = new Texture2D[numberOfMenuOptionsA];
_stageToolbarTexturesA[0] = (Texture2D)Resources.Load("GUI/track");
_stageToolbarTexturesA[1] = (Texture2D)Resources.Load("GUI/boundary");
_stageToolbarTexturesA[2] = (Texture2D)Resources.Load("GUI/bumpers");
_stageToolbarTexturesA[3] = (Texture2D)Resources.Load("GUI/textures");
_stageToolbarTexturesA[4] = (Texture2D)Resources.Load("GUI/terrain");
_stageToolbarTexturesB = new Texture2D[numberOfMenuOptionsB];
_stageToolbarTexturesB[0] = (Texture2D)Resources.Load("GUI/stunt");
_stageToolbarTexturesB[1] = (Texture2D)Resources.Load("GUI/diagram");
_stageToolbarTexturesB[2] = (Texture2D)Resources.Load("GUI/options");
_stageToolbarTexturesB[3] = (Texture2D)Resources.Load("GUI/export");
//Preview Camera
if (_trackBuildR.trackEditorPreview != null)
DestroyImmediate(_trackBuildR.trackEditorPreview);
if (!EditorApplication.isPlaying && SystemInfo.supportsRenderTextures)
{
_trackBuildR.trackEditorPreview = new GameObject("Track Preview Cam");
_trackBuildR.trackEditorPreview.hideFlags = HideFlags.HideAndDontSave;
_trackBuildR.trackEditorPreview.AddComponent<Camera>();
_trackBuildR.trackEditorPreview.camera.fieldOfView = 80;
//Retreive camera settings from the main camera
Camera[] cams = Camera.allCameras;
bool sceneHasCamera = cams.Length > 0;
Camera sceneCamera = null;
Skybox sceneCameraSkybox = null;
if (Camera.main)
{
sceneCamera = Camera.main;
}
else if (sceneHasCamera)
{
sceneCamera = cams[0];
}
if (sceneCamera != null)
if (sceneCameraSkybox == null)
sceneCameraSkybox = sceneCamera.GetComponent<Skybox>();
if (sceneCamera != null)
{
_trackBuildR.trackEditorPreview.camera.backgroundColor = sceneCamera.backgroundColor;
if (sceneCameraSkybox != null)
_trackBuildR.trackEditorPreview.AddComponent<Skybox>().material = sceneCameraSkybox.material;
else
if (RenderSettings.skybox != null)
_trackBuildR.trackEditorPreview.AddComponent<Skybox>().material = RenderSettings.skybox;
}
}
}
void OnDisable()
{
CleanUp();
}
void OnDestroy()
{
CleanUp();
}
private void CleanUp()
{
TrackBuildREditorInspector.CleanUp();
DestroyImmediate(_trackBuildR.trackEditorPreview);
}
/// <summary>
/// This function renders and controls the layout track function in the menu
/// Users can click place track points into the scene for a quick and easy creation of a track
/// </summary>
private void DrawTrack()
{
SceneView.focusedWindow.wantsMouseMove = true;
_handleSize = HandleUtility.GetHandleSize(_trackBuildR.transform.position) * 0.1f;
Plane buildingPlane = new Plane(Vector3.up, _trackBuildR.transform.forward);
float distance;
Vector3 mousePlanePoint = Vector3.zero;
Ray mouseRay = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 30, 0));
if (buildingPlane.Raycast(mouseRay, out distance))
mousePlanePoint = mouseRay.GetPoint(distance);
int numberOfPoints = _track.realNumberOfPoints;
for (int i = 0; i < numberOfPoints; i++)
{
TrackBuildRPoint thisPoint = _track[i];
Vector3 thisPosition = thisPoint.worldPosition;
Vector3 lastPosition = (i > 0) ? _track[i - 1].worldPosition : thisPosition;
Vector3 nextPosition = (i < numberOfPoints - 1) ? _track[i + 1].worldPosition : thisPosition;
Vector3 backwardTrack = thisPosition - lastPosition;
Vector3 forwardTrack = nextPosition - thisPosition;
Vector3 controlDirection = (backwardTrack + forwardTrack).normalized;
float controlMagnitude = (backwardTrack.magnitude + forwardTrack.magnitude) * 0.333f;
thisPoint.forwardControlPoint = (controlDirection * controlMagnitude) + thisPosition;
}
//draw track outline
int numberOfCurves = _track.numberOfCurves;
Vector3 position = _trackBuildR.transform.position;
for (int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint curve = _track[i];
int curvePoints = curve.storedPointSize;
bool lastPoint = i == numberOfCurves - 1;
Handles.color = (lastPoint && _track.loop) ? TrackBuildRColours.RED : TrackBuildRColours.GREEN;
for (int p = 1; p < curvePoints; p++)
{
int indexA = p - 1;
int indexB = p;
Handles.DrawLine(curve.sampledPoints[indexA] + position, curve.sampledPoints[indexB] + position);
Vector3 trackCrossWidth = curve.sampledTrackCrosses[indexA] * (curve.sampledWidths[indexA] * 0.5f);
Handles.DrawLine(curve.sampledPoints[indexA] + trackCrossWidth + position, curve.sampledPoints[indexB] + trackCrossWidth + position);
Handles.DrawLine(curve.sampledPoints[indexA] - trackCrossWidth + position, curve.sampledPoints[indexB] - trackCrossWidth + position);
}
}
Handles.color = Color.green;
if (Handles.Button(mousePlanePoint, Quaternion.identity, _handleSize, _handleSize, Handles.DotCap))
{
TrackBuildRPoint newTrackPoint = _track.gameObject.AddComponent<TrackBuildRPoint>();//CreateInstance<TrackBuildRPoint>();
newTrackPoint.baseTransform = _trackBuildR.transform;
newTrackPoint.position = mousePlanePoint;
_track.AddPoint(newTrackPoint);
}
if (_track.realNumberOfPoints > 0)
{
TrackBuildRPoint pointOne = _track[0];
Handles.Label(pointOne.worldPosition, "Loop Track");
if (Handles.Button(pointOne.worldPosition, Quaternion.identity, _handleSize, _handleSize, Handles.DotCap))
{
_track.drawMode = false;
_trackBuildR.UpdateRender();
}
}
if (GUI.changed)
{
UpdateGui();
}
}
void OnSceneGUI()
{
if (_track.drawMode)
{
DrawTrack();
return;
}
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = false;
Vector3 position = _trackBuildR.transform.position;
Camera sceneCamera = Camera.current;
_handleSize = HandleUtility.GetHandleSize(_trackBuildR.transform.position) * 0.1f;
int realNumberOfPoints = _track.realNumberOfPoints;
Ray mouseRay = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 30, 0));
Quaternion mouseLookDirection = Quaternion.LookRotation(-mouseRay.direction);
int numberOfCurves = _track.numberOfCurves;
switch (_trackBuildR.mode)
{
case TrackBuildR.modes.track:
Handles.color = TrackBuildRColours.GREEN;
switch (_trackBuildR.pointMode)
{
case TrackBuildR.pointModes.add:
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = true;
if (Event.current.type == EventType.MouseMove)
Repaint();
Handles.color = TrackBuildRColours.GREY;
for(int i = 0; i < _track.realNumberOfPoints; i++)
{
Vector3 pointPos = _track[i].worldPosition;
float handleSize = HandleUtility.GetHandleSize(pointPos);
Handles.DotCap(0, pointPos, Quaternion.identity, handleSize*0.05f);
}
Handles.color = TrackBuildRColours.GREEN;
float mousePercentage = NearestmMousePercentage();// _track.GetNearestPoint(mousePlanePoint);
Vector3 mouseTrackPoint = _track.GetTrackPosition(mousePercentage) + position;
Handles.Label(mouseTrackPoint, "Add New Track Point");
float newPointHandleSize = HandleUtility.GetHandleSize(mouseTrackPoint) * HANDLE_SCALE;
if (Handles.Button(mouseTrackPoint, mouseLookDirection, newPointHandleSize, newPointHandleSize, Handles.DotCap))
{
int newPointIndex = _track.GetLastPointIndex(mousePercentage);
TrackBuildRPoint newPoint = _track.InsertPoint(newPointIndex + 1);
newPoint.worldPosition = mouseTrackPoint;
newPoint.width = _track.GetTrackWidth(mousePercentage);
newPoint.crownAngle = _track.GetTrackCrownAngle(mousePercentage);
selectedPoint = newPointIndex + 1;
GUI.changed = true;
_trackBuildR.pointMode = TrackBuildR.pointModes.transform;
}
break;
case TrackBuildR.pointModes.remove:
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = true;
Handles.color = TrackBuildRColours.RED;
for (int i = 0; i < realNumberOfPoints; i++)
{
TrackBuildRPoint point = _track[i];
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
Handles.Label(point.worldPosition, "Remove Track Point");
if (Handles.Button(point.worldPosition, mouseLookDirection, pointHandleSize, pointHandleSize, Handles.DotCap))
{
_track.RemovePoint(point);
GUI.changed = true;
_trackBuildR.pointMode = TrackBuildR.pointModes.transform;
}
}
break;
default:
SceneGUIPointBased();
break;
}
//draw track outline
for (int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint curve = _track[i];
if(curve==null)
continue;
int curvePoints = curve.storedPointSize;
float dotPA = Vector3.Dot(sceneCamera.transform.forward, curve.worldPosition - sceneCamera.transform.position);
float dotPB = Vector3.Dot(sceneCamera.transform.forward, curve.nextPoint.worldPosition - sceneCamera.transform.position);
if (dotPA < 0 && dotPB < 0)
continue;
float curveDistance = Vector3.Distance(sceneCamera.transform.position, curve.center);
int pointJump = Mathf.Max((int)(curveDistance / 20.0f), 1);
Color trackOutline = curve.render ? TrackBuildRColours.GREEN : TrackBuildRColours.RED;
Color trackOutlineA = trackOutline;
trackOutlineA.a = 0.5f;
for (int p = pointJump; p < curvePoints; p += pointJump)
{
int indexA = p - pointJump;
int indexB = p;
if (p + pointJump > curvePoints - 1)
indexB = curvePoints - 1;
Handles.color = trackOutlineA;
Handles.DrawLine(curve.sampledPoints[indexA] + position, curve.sampledPoints[indexB] + position);
Handles.color = trackOutline;
Vector3 trackCrossWidth = curve.sampledTrackCrosses[indexA] * (curve.sampledWidths[indexA] * 0.5f);
Handles.DrawLine(curve.sampledPoints[indexA] + trackCrossWidth + position, curve.sampledPoints[indexB] + trackCrossWidth + position);
Handles.DrawLine(curve.sampledPoints[indexA] - trackCrossWidth + position, curve.sampledPoints[indexB] - trackCrossWidth + position);
}
}
break;
case TrackBuildR.modes.boundary:
//draw boundary outline
for (int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint curve = _track[i];
int curvePoints = curve.storedPointSize;
float dotPA = Vector3.Dot(sceneCamera.transform.forward, curve.worldPosition - sceneCamera.transform.position);
float dotPB = Vector3.Dot(sceneCamera.transform.forward, curve.nextPoint.worldPosition - sceneCamera.transform.position);
if (dotPA < 0 && dotPB < 0)
continue;
float curveDistance = Vector3.Distance(sceneCamera.transform.position, curve.center);
int pointJump = Mathf.Max((int)(curveDistance / 20.0f), 1);
for (int p = pointJump; p < curvePoints; p += pointJump)
{
int indexA = p - pointJump;
int indexB = p;
if (p + pointJump > curvePoints - 1)
indexB = curvePoints - 1;
if (_track.disconnectBoundary)
{
Handles.color = TrackBuildRColours.BLUE;
Handles.DrawLine(curve.sampledLeftBoundaryPoints[indexA] + position, curve.sampledLeftBoundaryPoints[indexB] + position);
Handles.color = TrackBuildRColours.RED;
Handles.DrawLine(curve.sampledRightBoundaryPoints[indexA] + position, curve.sampledRightBoundaryPoints[indexB] + position);
}
else
{
Vector3 trackCrossWidth = curve.sampledTrackCrosses[indexA] * (curve.sampledWidths[indexA] * 0.5f);
Handles.color = TrackBuildRColours.BLUE;
Handles.DrawLine(curve.sampledPoints[indexA] + trackCrossWidth + position, curve.sampledPoints[indexB] + trackCrossWidth + position);
Handles.color = TrackBuildRColours.RED;
Handles.DrawLine(curve.sampledPoints[indexA] - trackCrossWidth + position, curve.sampledPoints[indexB] - trackCrossWidth + position);
}
}
}
SceneGUIPointBased();
break;
case TrackBuildR.modes.textures:
for (int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint thisCurve = _track[i];
float pointHandleSize = HandleUtility.GetHandleSize(thisCurve.center) * HANDLE_SCALE;
Handles.color = (i == selectedCurveIndex) ? TrackBuildRColours.RED : TrackBuildRColours.BLUE;
if (Handles.Button(thisCurve.center, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
selectedCurveIndex = i;
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
GUI.changed = true;
}
}
Handles.color = TrackBuildRColours.RED;
TrackBuildRPoint selectedCurve = _track[selectedCurveIndex];
int numberOfSelectedCurvePoints = selectedCurve.storedPointSize;
for (int i = 0; i < numberOfSelectedCurvePoints - 1; i++)
{
Vector3 leftPointA = selectedCurve.sampledLeftBoundaryPoints[i];
Vector3 leftPointB = selectedCurve.sampledLeftBoundaryPoints[i + 1];
Vector3 rightPointA = selectedCurve.sampledRightBoundaryPoints[i];
Vector3 rightPointB = selectedCurve.sampledRightBoundaryPoints[i + 1];
Handles.DrawLine(leftPointA, leftPointB);
Handles.DrawLine(rightPointA, rightPointB);
if (i == 0)
Handles.DrawLine(leftPointA, rightPointA);
if (i == numberOfSelectedCurvePoints - 2)
Handles.DrawLine(leftPointB, rightPointB);
}
break;
case TrackBuildR.modes.terrain:
//nothing
break;
case TrackBuildR.modes.stunt:
SceneGUIPointBased();
TrackBuildRPoint atPoint = _track[selectedPoint];
TrackBuildRPoint lastPoint = _track.GetPoint(selectedPoint - 1);
TrackBuildRPoint nextPoint = _track.GetPoint(selectedPoint + 1);
float trackWidth;
Vector3 startCross;
Vector3 p0, p1, p2, p3, p4, p5, p6, p7;
switch(_trackBuildR.stuntMode)
{
case TrackBuildR.stuntModes.loop:
atPoint = _track[selectedPoint];
trackWidth = atPoint.width;
float loopRadius = _track.loopRadius;
Vector3 loopPosition = atPoint.worldPosition;
Vector3 trackDirection = atPoint.trackDirection.normalized;
Vector3 trackup = atPoint.trackUpQ * Vector3.forward;
Vector3 trackCross = atPoint.trackCross;
Vector3 loopCentreHeight = loopRadius * trackup;
Quaternion loopAngle = Quaternion.FromToRotation(Vector3.right, trackDirection);
for(float i = 0; i < 0.99f; i += 0.01f )
{
float radA = Mathf.PI * 2 * (i+0.5f);
float radB = Mathf.PI * 2 * (i+0.51f);
Vector3 pointLoopPositionA = loopAngle * ((new Vector3(Mathf.Sin(radA), Mathf.Cos(radA), 0)) * loopRadius);
Vector3 pointLoopPositionB = loopAngle * ((new Vector3(Mathf.Sin(radB), Mathf.Cos(radB), 0)) * loopRadius);
Vector3 lateral = Vector3.Lerp((trackCross * trackWidth * -0.6f), (trackCross * trackWidth * 0.6f), i);
Vector3 pointPositionA = (pointLoopPositionA) + lateral + loopPosition + loopCentreHeight;
Vector3 pointPositionB = (pointLoopPositionB) + lateral + loopPosition + loopCentreHeight;
Handles.DrawLine(pointPositionA, pointPositionB);
}
break;
case TrackBuildR.stuntModes.jump:
atPoint = _track[selectedPoint];
lastPoint = _track.GetPoint(selectedPoint - 1);
nextPoint = _track.GetPoint(selectedPoint + 1);
float trackPartDistance = lastPoint.arcLength + atPoint.arcLength;
float jumpDistance = Mathf.Min(trackPartDistance * 0.333f, _track.maxJumpLength);
Vector3 jumpDirection = atPoint.trackDirection;
Vector3 jumpMiddle = atPoint.worldPosition;
startCross = atPoint.trackCross;
trackWidth = atPoint.width*0.5f;
Quaternion trackUp = atPoint.trackUpQ;
Vector3 jumpHeight = trackUp * (Vector3.forward * _track.jumpHeight);
Vector3 jumpStartPosition = jumpMiddle - jumpDirection * (jumpDistance * 0.33f);
Vector3 jumpEndPosition = jumpMiddle + jumpDirection * (jumpDistance * 0.33f);
p0 = lastPoint.worldPosition + trackWidth * startCross;
p1 = lastPoint.worldPosition - trackWidth * startCross;
p2 = jumpStartPosition + trackWidth * startCross + jumpHeight;
p3 = jumpStartPosition - trackWidth * startCross + jumpHeight;
p4 = jumpEndPosition + trackWidth * startCross + jumpHeight;
p5 = jumpEndPosition - trackWidth * startCross + jumpHeight;
p6 = nextPoint.worldPosition + trackWidth * startCross;
p7 = nextPoint.worldPosition - trackWidth * startCross;
Handles.DrawLine(p0, p2);
Handles.DrawLine(p1, p3);
Handles.DrawLine(p0, p1);
Handles.DrawLine(p2, p3);
Handles.DrawLine(p2, p2 - jumpHeight);
Handles.DrawLine(p3, p3 - jumpHeight);
Handles.DrawLine(p0, p2 - jumpHeight);
Handles.DrawLine(p1, p3 - jumpHeight);
Handles.DrawLine(p4, p6);
Handles.DrawLine(p5, p7);
Handles.DrawLine(p4, p5);
Handles.DrawLine(p6, p7);
Handles.DrawLine(p4, p4 - jumpHeight);
Handles.DrawLine(p5, p5 - jumpHeight);
Handles.DrawLine(p6, p4 - jumpHeight);
Handles.DrawLine(p7, p5 - jumpHeight);
break;
// case TrackBuildR.stuntModes.twist:
//
// atPoint = _track[selectedPoint];
// lastPoint = _track.GetPoint(selectedPoint - 1);
//
// float twistDistance = Mathf.Min((lastPoint.arcLength + atPoint.arcLength) * 0.333f, _track.maxJumpLength);
//
// Vector3 twistDirection = atPoint.trackDirection;
// Vector3 twistMiddle = atPoint.worldPosition;
// Vector3 twistUp = atPoint.trackUp;
// float twistRadius = _track.twistRadius;
// Vector3 twistStartPosition = twistMiddle - twistDirection * (twistDistance * 0.33f);
// Vector3 twistEndPosition = twistMiddle + twistDirection * (twistDistance * 0.33f);
// Vector3 twistCentreHeight = twistUp * twistRadius;
// Quaternion twistAngle = Quaternion.LookRotation(twistDirection, twistUp);
// for(float i = 0; i < 0.99f; i += 0.01f )
// {
// float radA = Mathf.PI * 2 * (i+0.5f);
// float radB = Mathf.PI * 2 * (i+0.51f);
// Vector3 pointLoopPositionA = twistAngle * ((new Vector3(Mathf.Sin(radA), Mathf.Cos(radA), 0)) * twistRadius);
// Vector3 pointLoopPositionB = twistAngle * ((new Vector3(Mathf.Sin(radB), Mathf.Cos(radB), 0)) * twistRadius);
// float smoothI = i * i * (3.0f - 2.0f * i);
// Vector3 lateral = Vector3.Lerp(twistStartPosition, twistEndPosition, i + (i-smoothI));
// Vector3 pointPositionA = (pointLoopPositionA) + lateral + twistCentreHeight;
// Vector3 pointPositionB = (pointLoopPositionB) + lateral + twistCentreHeight;
// Handles.DrawLine(pointPositionA, pointPositionB);
// }
//
// break;
case TrackBuildR.stuntModes.jumptwist:
atPoint = _track[selectedPoint];
lastPoint = _track.GetPoint(selectedPoint - 1);
nextPoint = _track.GetPoint(selectedPoint + 1);
float trackTPartDistance = lastPoint.arcLength + atPoint.arcLength;
float jumpTDistance = Mathf.Min(trackTPartDistance * 0.333f, _track.maxJumpLength);
trackWidth = atPoint.width * 0.5f;
startCross = atPoint.trackCross;
Vector3 jumpTDirection = atPoint.trackDirection;
Vector3 jumpTMiddle = atPoint.worldPosition;
Quaternion atPointUpQ = atPoint.trackUpQ;
Quaternion trackUpJump = Quaternion.AngleAxis(_track.twistAngle, -jumpTDirection);
Vector3 trackCrossExit = trackUpJump * startCross;
Vector3 trackCrossEntry = Quaternion.Inverse(trackUpJump) * startCross;
Vector3 jumpLateral = startCross * _track.twistAngle / 33.3f;
Vector3 jumpTHeight = atPointUpQ * (Vector3.forward * _track.jumpHeight);
Vector3 jumpTStartPosition = jumpTMiddle - jumpTDirection * (jumpTDistance * 0.33f) + jumpTHeight - jumpLateral;
Vector3 jumpTEndPosition = jumpTMiddle + jumpTDirection * (jumpTDistance * 0.33f) + jumpTHeight + jumpLateral;
p0 = lastPoint.worldPosition + trackWidth * startCross;
p1 = lastPoint.worldPosition - trackWidth * startCross;
p2 = jumpTStartPosition + trackWidth * trackCrossExit;
p3 = jumpTStartPosition - trackWidth * trackCrossExit;
p4 = jumpTEndPosition + trackWidth * trackCrossEntry;
p5 = jumpTEndPosition - trackWidth * trackCrossEntry;
p6 = nextPoint.worldPosition + trackWidth * startCross;
p7 = nextPoint.worldPosition - trackWidth * startCross;
Handles.DrawLine(p0, p2);
Handles.DrawLine(p1, p3);
Handles.DrawLine(p0, p1);
Handles.DrawLine(p2, p3);
// Handles.DrawLine(p2, p2 - jumpTHeight);
// Handles.DrawLine(p3, p3 - jumpTHeight);
// Handles.DrawLine(p0, p2 - jumpTHeight);
// Handles.DrawLine(p1, p3 - jumpTHeight);
Handles.DrawLine(p4, p6);
Handles.DrawLine(p5, p7);
Handles.DrawLine(p4, p5);
Handles.DrawLine(p6, p7);
// Handles.DrawLine(p4, p4 - jumpTHeight);
// Handles.DrawLine(p5, p5 - jumpTHeight);
// Handles.DrawLine(p6, p4 - jumpTHeight);
// Handles.DrawLine(p7, p5 - jumpTHeight);
break;
}
break;
case TrackBuildR.modes.diagram:
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = true;
if (!_track.showDiagram)
break;
Plane diagramPlane = new Plane(Vector3.up, position);
float diagramDistance;
float crossSize = _handleSize * 10;
switch (_trackBuildR.track.assignedPoints)
{
case 0://display the diagram scale points
Vector3 diagramPointA = _track.scalePointA;
Vector3 diagramPointB = _track.scalePointB;
if (diagramPointA != Vector3.zero || diagramPointB != Vector3.zero)
{
Handles.color = TrackBuildRColours.BLUE;
Handles.DrawLine(diagramPointA, diagramPointA + Vector3.left * crossSize);
Handles.DrawLine(diagramPointA, diagramPointA + Vector3.right * crossSize);
Handles.DrawLine(diagramPointA, diagramPointA + Vector3.forward * crossSize);
Handles.DrawLine(diagramPointA, diagramPointA + Vector3.back * crossSize);
Handles.color = TrackBuildRColours.GREEN;
Handles.DrawLine(diagramPointB, diagramPointB + Vector3.left * crossSize);
Handles.DrawLine(diagramPointB, diagramPointB + Vector3.right * crossSize);
Handles.DrawLine(diagramPointB, diagramPointB + Vector3.forward * crossSize);
Handles.DrawLine(diagramPointB, diagramPointB + Vector3.back * crossSize);
Handles.color = TrackBuildRColours.RED;
Handles.DrawLine(diagramPointA, diagramPointB);
}
break;
case 1://place the first of two scale points to define the diagram scale size
Ray diagramRay = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 30, 0));
if (diagramPlane.Raycast(diagramRay, out diagramDistance))
{
Vector3 diagramPlanePoint = diagramRay.GetPoint(diagramDistance);
Handles.color = TrackBuildRColours.BLUE;
Handles.DrawLine(diagramPlanePoint, diagramPlanePoint + Vector3.left * crossSize);
Handles.DrawLine(diagramPlanePoint, diagramPlanePoint + Vector3.right * crossSize);
Handles.DrawLine(diagramPlanePoint, diagramPlanePoint + Vector3.forward * crossSize);
Handles.DrawLine(diagramPlanePoint, diagramPlanePoint + Vector3.back * crossSize);
Handles.color = new Color(0, 0, 0, 0);
if (Handles.Button(diagramPlanePoint, Quaternion.identity, crossSize, crossSize, Handles.DotCap))
{
_track.scalePointA = diagramPlanePoint;
_track.assignedPoints = 2;
}
}
break;
case 2://place the second of two scale points to define the diagram scale
Vector3 diagramPoint1 = _track.scalePointA;
Handles.color = TrackBuildRColours.BLUE;
Handles.DrawLine(diagramPoint1, diagramPoint1 + Vector3.left * crossSize);
Handles.DrawLine(diagramPoint1, diagramPoint1 + Vector3.right * crossSize);
Handles.DrawLine(diagramPoint1, diagramPoint1 + Vector3.forward * crossSize);
Handles.DrawLine(diagramPoint1, diagramPoint1 + Vector3.back * crossSize);
Ray diagramRayB = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 30, 0));
if (diagramPlane.Raycast(diagramRayB, out diagramDistance))
{
Vector3 diagramPlanePoint = diagramRayB.GetPoint(diagramDistance);
Handles.color = TrackBuildRColours.RED;
Handles.DrawLine(diagramPlanePoint, diagramPoint1);
Handles.color = TrackBuildRColours.GREEN;
Handles.DrawLine(diagramPlanePoint, diagramPlanePoint + Vector3.left * crossSize);
Handles.DrawLine(diagramPlanePoint, diagramPlanePoint + Vector3.right * crossSize);
Handles.DrawLine(diagramPlanePoint, diagramPlanePoint + Vector3.forward * crossSize);
Handles.DrawLine(diagramPlanePoint, diagramPlanePoint + Vector3.back * crossSize);
Handles.color = new Color(0, 0, 0, 0);
if (Handles.Button(diagramPlanePoint, Quaternion.identity, crossSize, crossSize, Handles.DotCap))
{
_track.scalePointB = diagramPlanePoint;
_track.assignedPoints = 0;
//wUpdateDiagram();
}
}
break;
}
break;
}
if (Event.current.type == EventType.ValidateCommand)
{
switch (Event.current.commandName)
{
case "UndoRedoPerformed":
// Debug.Log("UndoRedoPerformed");
_trackBuildR.ForceFullRecalculation();
GUI.changed = true;
return;
}
}
if (GUI.changed)
{
UpdateGui();
}
}
private void SceneGUIPointBased()
{
Vector3 position = _trackBuildR.transform.position;
Camera sceneCamera = Camera.current;
_handleSize = HandleUtility.GetHandleSize(_trackBuildR.transform.position) * 0.1f;
int realNumberOfPoints = _track.realNumberOfPoints;
Ray mouseRay = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 30, 0));
for (int i = 0; i < realNumberOfPoints; i++)
{
TrackBuildRPoint point = _track[i];
if (Vector3.Dot(sceneCamera.transform.forward, point.worldPosition - sceneCamera.transform.position) < 0)
continue;
Handles.Label(point.worldPosition, "point " + (i + 1));
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
Handles.color = (i == selectedPoint) ? TrackBuildRColours.RED : TrackBuildRColours.GREEN;
if (Handles.Button(point.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
selectedPoint = i;
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
GUI.changed = true;
point.isDirty = true;
}
if (i == selectedPoint)
{
switch (_trackBuildR.mode)
{
case TrackBuildR.modes.track:
switch (_trackBuildR.pointMode)
{
case TrackBuildR.pointModes.transform:
Vector3 currentPosition = point.worldPosition;
currentPosition = Handles.DoPositionHandle(currentPosition, Quaternion.identity);
if (currentPosition != point.worldPosition)
{
Undo.RecordObject(point, "Point Changed");
point.isDirty = true;
point.worldPosition = currentPosition;
}
//greyed out control points for user ease
Handles.color = TrackBuildRColours.DARK_GREY;
Handles.DrawLine(point.worldPosition, point.forwardControlPoint + position);
Handles.DrawLine(point.worldPosition, point.backwardControlPoint + position);
if (Handles.Button(point.backwardControlPoint + position, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
_trackBuildR.pointMode = TrackBuildR.pointModes.controlpoint;
if (Handles.Button(point.forwardControlPoint + position, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
_trackBuildR.pointMode = TrackBuildR.pointModes.controlpoint;
break;
case TrackBuildR.pointModes.controlpoint:
//render reverse first so forward renders on top
Handles.DrawLine(point.worldPosition, point.backwardControlPoint + position);
point.backwardControlPoint = Handles.DoPositionHandle(point.backwardControlPoint + position, Quaternion.identity) - position;
if (Vector3.Dot(mouseRay.direction, point.worldPosition - mouseRay.origin) > 0)
Handles.Label(point.backwardControlPoint, "point " + (i + 1) + " reverse control point");
if (Vector3.Dot(mouseRay.direction, point.worldPosition - mouseRay.origin) > 0)
Handles.Label(point.forwardControlPoint, "point " + (i + 1) + " control point");
Handles.color = TrackBuildRColours.RED;
Handles.DrawLine(point.worldPosition, point.forwardControlPoint + position);
point.forwardControlPoint = Handles.DoPositionHandle(point.forwardControlPoint + position, Quaternion.identity) - position;
break;
case TrackBuildR.pointModes.trackup:
Undo.RecordObject(point, "Point Changed");
point.trackUpQ = Handles.RotationHandle(point.trackUpQ, point.worldPosition);
Handles.color = TrackBuildRColours.BLUE;
Handles.ArrowCap(0, point.worldPosition, point.trackUpQ, pointHandleSize * 10);
Handles.Label(point.worldPosition + point.trackUpQ * Vector3.forward * pointHandleSize * 15, "Up Vector");
Handles.color = TrackBuildRColours.GREEN;
Handles.ArrowCap(0, point.worldPosition, Quaternion.LookRotation(point.trackDirection), pointHandleSize * 10);
Handles.Label(point.worldPosition + point.trackDirection * pointHandleSize * 15, "Direction Vector");
Handles.color = TrackBuildRColours.RED;
Quaternion quatForward = Quaternion.LookRotation(point.trackUpQ * Vector3.up);
Handles.ArrowCap(0, point.worldPosition, quatForward, pointHandleSize * 10);
Handles.Label(point.worldPosition + Quaternion.LookRotation(point.trackUpQ * Vector3.up) * Vector3.forward * pointHandleSize * 15, "Up Forward Vector");
Handles.color = TrackBuildRColours.PURPLE;
Quaternion quatCross = Quaternion.LookRotation(point.trackCross);
Handles.ArrowCap(0, point.worldPosition, quatCross, pointHandleSize * 10);
Handles.Label(point.worldPosition + point.trackCross * pointHandleSize * 15, "Cross Vector");
break;
case TrackBuildR.pointModes.trackpoint:
//Track Width
Handles.color = TrackBuildRColours.RED;
float pointWidth = point.width / 2;
Vector3 sliderPos = Handles.Slider(point.worldPosition + point.trackCross * pointWidth, point.trackCross);
float pointwidth = Vector3.Distance(sliderPos, point.worldPosition) * 2;
if (pointwidth != point.width)
{
Undo.RecordObject(point, "Point Changed");
point.isDirty = true;
point.width = pointwidth;
}
//Crown
Handles.color = TrackBuildRColours.GREEN;
Vector3 crownPosition = point.worldPosition + point.trackUp * point.crownAngle;
Vector3 newCrownPosition = Handles.Slider(crownPosition, point.trackUp);
Vector3 crownDifference = newCrownPosition - point.worldPosition;
if (crownDifference.sqrMagnitude != 0)//Crown Modified
{
Undo.RecordObject(point, "Point Changed");
point.isDirty = true;
point.crownAngle = Vector3.Project(crownDifference, point.trackUp).magnitude * Mathf.Sign(Vector3.Dot(crownDifference, point.trackUp));
}
break;
}
break;
case TrackBuildR.modes.boundary:
if (_track.disconnectBoundary)
{
if (Vector3.Dot(mouseRay.direction, point.worldPosition - mouseRay.origin) > 0)
{
Handles.color = TrackBuildRColours.RED;
Handles.Label(point.leftTrackBoundaryWorld, "point " + (i + 1) + " left track boundary");
Handles.Label(point.rightTrackBoundaryWorld, "point " + (i + 1) + " right track boundary");
Handles.DrawLine(point.worldPosition, point.leftTrackBoundaryWorld);
Handles.DrawLine(point.worldPosition, point.rightTrackBoundaryWorld);
}
switch (_trackBuildR.boundaryMode)
{
case TrackBuildR.boundaryModes.transform:
Undo.RecordObject(point, "Point Changed");
point.leftTrackBoundaryWorld = Handles.DoPositionHandle(point.leftTrackBoundaryWorld, Quaternion.identity);
point.rightTrackBoundaryWorld = Handles.DoPositionHandle(point.rightTrackBoundaryWorld, Quaternion.identity);
break;
case TrackBuildR.boundaryModes.controlpoint:
Undo.RecordObject(point, "Point Changed");
Handles.color = TrackBuildRColours.RED;
Handles.DrawLine(point.leftTrackBoundaryWorld, point.leftForwardControlPoint + position);
point.leftForwardControlPoint = Handles.DoPositionHandle(point.leftForwardControlPoint + position, Quaternion.identity) - position;
Handles.DrawLine(point.leftTrackBoundaryWorld, point.leftBackwardControlPoint + position);
point.leftBackwardControlPoint = Handles.DoPositionHandle(point.leftBackwardControlPoint + position, Quaternion.identity) - position;
Handles.DrawLine(point.rightTrackBoundaryWorld, point.rightForwardControlPoint + position);
point.rightForwardControlPoint = Handles.DoPositionHandle(point.rightForwardControlPoint + position, Quaternion.identity) - position;
Handles.DrawLine(point.rightTrackBoundaryWorld, point.rightBackwardControlPoint + position);
point.rightBackwardControlPoint = Handles.DoPositionHandle(point.rightBackwardControlPoint + position, Quaternion.identity) - position;
break;
}
}
break;
case TrackBuildR.modes.stunt:
break;
}
}
}
}
/// <summary>
/// Get the nearest point on the track curve to the mouse position
/// We essentailly project the track onto a 2D plane that is the editor camera and then find a point on that
/// </summary>
/// <returns>A percentage of the nearest point on the track curve to the nerest metre</returns>
private float NearestmMousePercentage()
{
Camera cam = Camera.current;
float screenHeight = cam.pixelHeight;
Vector2 mousePos = Event.current.mousePosition;
mousePos.y = screenHeight - mousePos.y;
int numberOfSearchPoints = 600;
Vector3 position = _trackBuildR.transform.position;
Vector2 zeropoint = cam.WorldToScreenPoint(_track.GetTrackPosition(0) + position);
float nearestPointSqrMag = Vector2.SqrMagnitude(zeropoint - mousePos);
float nearestT = 0;
float nearestPointSqrMagB = Vector2.SqrMagnitude(zeropoint - mousePos);
float nearestTb = 0;
for (int i = 1; i < numberOfSearchPoints; i++)
{
float t = i / (float)numberOfSearchPoints;
Vector2 point = cam.WorldToScreenPoint(_track.GetTrackPosition(t) + position);
float thisPointMag = Vector2.SqrMagnitude(point - mousePos);
if (thisPointMag < nearestPointSqrMag)
{
nearestPointSqrMagB = nearestPointSqrMag;
nearestTb = nearestT;
nearestT = t;
nearestPointSqrMag = thisPointMag;
}
else
{
if (thisPointMag < nearestPointSqrMagB)
{
nearestTb = t;
nearestPointSqrMagB = thisPointMag;
}
}
}
float pointADist = Mathf.Sqrt(nearestPointSqrMag);
float pointBDist = Mathf.Sqrt(nearestPointSqrMagB);
float lerpvalue = pointADist / (pointADist + pointBDist);
return Mathf.Lerp(nearestT, nearestTb, lerpvalue);
}
public override void OnInspectorGUI()
{
TrackBuildREditorInspector.OnInspectorGUI(_trackBuildR, selectedPoint, selectedCurveIndex);
if (GUI.changed)
{
UpdateGui();
}
}
/// <summary>
/// Handle GUI changes and repaint requests
/// </summary>
private void UpdateGui()
{
Repaint();
HandleUtility.Repaint();
SceneView.RepaintAll();
_trackBuildR.UpdateRender();
EditorUtility.SetDirty(_trackBuildR);
EditorUtility.SetDirty(_track);
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using MLifter.DAL.Interfaces;
using MLifter.DAL.Interfaces.DB;
using MLifter.DAL.Tools;
using MLifter.Generics;
using Npgsql;
namespace MLifter.DAL.DB.PostgreSQL
{
class PgSqlDictionaryConnector : MLifter.DAL.Interfaces.DB.IDbDictionaryConnector
{
private static Dictionary<ConnectionStringStruct, PgSqlDictionaryConnector> instances = new Dictionary<ConnectionStringStruct, PgSqlDictionaryConnector>();
public static PgSqlDictionaryConnector GetInstance(ParentClass parentClass)
{
lock (instances)
{
ConnectionStringStruct connection = parentClass.CurrentUser.ConnectionString;
if (!instances.ContainsKey(connection))
instances.Add(connection, new PgSqlDictionaryConnector(parentClass));
return instances[connection];
}
}
private ParentClass Parent;
private PgSqlDictionaryConnector(ParentClass parentClass)
{
Parent = parentClass;
Parent.DictionaryClosed += new EventHandler(Parent_DictionaryClosed);
}
void Parent_DictionaryClosed(object sender, EventArgs e)
{
IParent parent = sender as IParent;
instances.Remove(parent.Parent.CurrentUser.ConnectionString);
}
#region IDbDictionaryConnector Members
public string GetDbVersion()
{
string version = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.DataBaseVersion, 0)] as string;
if (version != null && version.Length > 0)
return version;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT value FROM \"DatabaseInformation\" WHERE property=:prop";
cmd.Parameters.Add("prop", DataBaseInformation.Version.ToString());
version = Convert.ToString(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser));
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.DataBaseVersion, 0, new TimeSpan(1, 0, 0))] = version;
return version;
}
}
}
/// <summary>
/// Gets the content protected.
/// </summary>
/// <param name="id">The id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-02-13</remarks>
public bool GetContentProtected(int id)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT content_protected FROM \"LearningModules\" WHERE id=:id;";
cmd.Parameters.Add("id", id);
bool? output = PostgreSQLConn.ExecuteScalar<bool>(cmd, Parent.CurrentUser);
return output.HasValue ? output.Value : false;
}
}
}
public string GetTitle(int id)
{
string titleCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.LearningModuleTitle, id)] as string;
if (titleCache != null)
return titleCache;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT title FROM \"LearningModules\" WHERE id=:id";
cmd.Parameters.Add("id", id);
string title = Convert.ToString(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser));
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.LearningModuleTitle, id)] = title;
return title;
}
}
}
public void SetTitle(int id, string title)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"LearningModules\" SET title=:title WHERE id=:id";
cmd.Parameters.Add("id", id);
cmd.Parameters.Add("title", title);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.LearningModuleTitle, id));
}
}
}
public string GetAuthor(int id)
{
string authorCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.LearningModuleAuthor, id)] as string;
if (authorCache != null)
return authorCache;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT author FROM \"LearningModules\" WHERE id=:id";
cmd.Parameters.Add("id", id);
string author = Convert.ToString(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser));
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.LearningModuleAuthor, id)] = author;
return author;
}
}
}
public void SetAuthor(int id, string author)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"LearningModules\" SET author=:author WHERE id=:id";
cmd.Parameters.Add("id", id);
cmd.Parameters.Add("author", author);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.LearningModuleAuthor, id));
}
}
}
public string GetDescription(int id)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT description FROM \"LearningModules\" WHERE id=:id";
cmd.Parameters.Add("id", id);
return Convert.ToString(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser));
}
}
}
public void SetDescription(int id, string description)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"LearningModules\" SET description=:description WHERE id=:id";
cmd.Parameters.Add("id", id);
cmd.Parameters.Add("description", description);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
}
}
}
public string GetGuid(int id)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT guid FROM \"LearningModules\" WHERE id=:id";
cmd.Parameters.Add("id", id);
return Convert.ToString(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser));
}
}
}
public void SetGuid(int id, string guid)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"LearningModules\" SET guid=:guid WHERE id=:id";
cmd.Parameters.Add("id", id);
cmd.Parameters.Add("guid", guid);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
}
}
}
public ISettings GetDefaultSettings(int id)
{
DbSettings settingsCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.DefaultLearningModuleSettings, id)] as DbSettings;
if (settingsCache != null)
return settingsCache;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT default_settings_id FROM \"LearningModules\" WHERE id=:id";
cmd.Parameters.Add("id", id);
int? settingsid = PostgreSQLConn.ExecuteScalar<int>(cmd, Parent.CurrentUser);
if (!settingsid.HasValue)
return null;
DbSettings settings = new DbSettings(settingsid.Value, false, Parent);
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.DefaultLearningModuleSettings, id, Cache.DefaultSettingsValidationTime)] = settings;
return settings;
}
}
}
public void SetDefaultSettings(int id, int settingsId)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"LearningModules\" SET default_settings_id=:settingsid WHERE id=:id";
cmd.Parameters.Add("id", id);
cmd.Parameters.Add("settingsid", settingsId);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.DefaultLearningModuleSettings, id));
}
}
}
public ISettings GetAllowedSettings(int id)
{
DbSettings settingsCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.AllowedLearningModuleSettings, id)] as DbSettings;
if (settingsCache != null)
return settingsCache;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT allowed_settings_id FROM \"LearningModules\" WHERE id=:id";
cmd.Parameters.Add("id", id);
int? settingsid = PostgreSQLConn.ExecuteScalar<int>(cmd, Parent.CurrentUser);
if (!settingsid.HasValue)
return null;
DbSettings settings = new DbSettings(settingsid.Value, false, Parent);
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.AllowedLearningModuleSettings, id, Cache.DefaultSettingsValidationTime)] = settings;
return settings;
}
}
}
public void SetAllowedSettings(int id, int settingsId)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"LearningModules\" SET allowed_settings_id=:settingsid WHERE id=:id";
cmd.Parameters.Add("id", id);
cmd.Parameters.Add("settingsid", settingsId);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.AllowedLearningModuleSettings, id));
}
}
}
public ISettings GetUserSettings(int id)
{
DbSettings settingsCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.UserLearningModuleSettings, id)] as DbSettings;
if (settingsCache != null)
return settingsCache;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT \"GetUserSettings\"(:uid, :lm_id);";
cmd.Parameters.Add("uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("lm_id", id);
int? settingsid = PostgreSQLConn.ExecuteScalar<int>(cmd, Parent.CurrentUser);
if (!settingsid.HasValue)
return null;
DbSettings settings = new DbSettings(settingsid.Value, false, Parent);
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.UserLearningModuleSettings, id, Cache.DefaultSettingsValidationTime)] = settings;
return settings;
}
}
}
public void SetUserSettings(int id, int settingsId)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"UserProfilesLearningModulesSettings\" SET settings_id=:settingsid WHERE user_id=:uid and lm_id=:lm_id;";
cmd.Parameters.Add("uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("lm_id", id);
cmd.Parameters.Add("settingsid", settingsId);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.AllowedLearningModuleSettings, id));
}
}
}
public ISettings CreateSettings()
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT \"CreateNewSetting\"()";
//PostgreSQLConn.ExecuteNonQuery(cmd);
int sid = Convert.ToInt32(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser).ToString());
return new DbSettings(sid, false, Parent);
}
}
}
public double GetScore(int id)
{
double? score = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.Score, id)] as double?;
if (score != null && score.HasValue)
return (double)score.Value;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT * FROM \"GetScore\"(:uid, :lm_id);";
cmd.Parameters.Add("uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("lm_id", id);
NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
reader.Read();
double sum, total;
double? result;
try
{
sum = System.Convert.ToDouble(reader["sum"]);
total = System.Convert.ToDouble(reader["total"]);
result = (double)(sum / total * 100);
}
catch
{
result = null;
}
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.Score, id, new TimeSpan(0, 0, 1))] = result;
return result.HasValue ? result.Value : 0;
}
}
}
public double GetHighscore(int id)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT highscore FROM \"UserProfilesLearningModulesSettings\" WHERE user_id=:uid and lm_id=:lm_id;";
cmd.Parameters.Add("uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("lm_id", id);
return PostgreSQLConn.ExecuteScalar<double>(cmd, Parent.CurrentUser).Value;
}
}
}
public void SetHighscore(int id, double Highscore)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"UserProfilesLearningModulesSettings\" SET highscore=:value WHERE user_id=:uid and lm_id=:lm_id;";
cmd.Parameters.Add("uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("lm_id", id);
cmd.Parameters.Add("value", Highscore);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
}
}
}
/// <summary>
/// Gets the size of the dictionary.
/// </summary>
/// <param name="id">The LearningModule id.</param>
/// <param name="defaultCardSizeValue">The default size of a card without media (e.g. 1024 bytes).</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2008-10-02</remarks>
public long GetDictionarySize(int id, int defaultCardSizeValue)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
long? mediaSize;
long? cardsCount;
//1. Get the FileSize sum of all MediaFiles in this LearningModule
cmd.CommandText = "SELECT SUM(CAST(\"MediaProperties\".value AS INT)) AS LearningModuleSize" +
" FROM \"MediaContent\", \"Cards_MediaContent\", \"MediaProperties\"" +
" WHERE \"Cards_MediaContent\".media_id = \"MediaContent\".id AND \"Cards_MediaContent\".cards_id IN" +
" (SELECT id FROM \"Cards\", \"LearningModules_Cards\" WHERE \"LearningModules_Cards\".cards_id = \"Cards\".id AND" +
" \"LearningModules_Cards\".lm_id = :id) AND \"MediaProperties\".media_id = \"MediaContent\".id AND" +
"\"MediaProperties\".property = 'MediaSize'";
cmd.Parameters.Add("id", id);
mediaSize = PostgreSQLConn.ExecuteScalar<long>(cmd, Parent.CurrentUser);
//2. Get the number of cards in this LearningModule (to calculate the approximately size of all Cards without Media)
using (NpgsqlCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT COUNT(*) FROM \"Cards\", \"LearningModules_Cards\" WHERE \"LearningModules_Cards\".cards_id = \"Cards\".id AND \"LearningModules_Cards\".lm_id = :id";
cmd2.Parameters.Add("id", id);
cardsCount = PostgreSQLConn.ExecuteScalar<long>(cmd2, Parent.CurrentUser);
}
long size = 0;
if (mediaSize.HasValue)
size += mediaSize.Value;
if (cardsCount.HasValue)
size += cardsCount.Value * defaultCardSizeValue;
return size;
}
}
}
/// <summary>
/// Gets the number of all Media Objects/Files in this LearningModules.
/// </summary>
/// <param name="id">The id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2008-10-02</remarks>
public int GetDictionaryMediaObjectsCount(int id)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
int? mediaSizeObjectsCount;
cmd.CommandText = "SELECT COUNT(*) AS LearningModuleMediaObjectsCount" +
" FROM \"MediaContent\", \"Cards_MediaContent\", \"MediaProperties\"" +
" WHERE \"Cards_MediaContent\".media_id = \"MediaContent\".id AND \"Cards_MediaContent\".cards_id IN" +
" (SELECT id FROM \"Cards\", \"LearningModules_Cards\" WHERE \"LearningModules_Cards\".cards_id = \"Cards\".id AND" +
" \"LearningModules_Cards\".lm_id = :id) AND \"MediaProperties\".media_id = \"MediaContent\".id AND" +
"\"MediaProperties\".property = 'MediaSize'";
cmd.Parameters.Add("id", id);
mediaSizeObjectsCount = PostgreSQLConn.ExecuteScalar<int>(cmd, Parent.CurrentUser);
if (!mediaSizeObjectsCount.HasValue)
return 0;
return mediaSizeObjectsCount.Value;
}
}
}
/// <summary>
/// Gets the category Id.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>the global category ID (0-5)</returns>
/// <remarks>Documented by Dev08, 2008-10-02</remarks>
public Category GetCategoryId(int id)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT global_id FROM \"LearningModules\", \"Categories\" WHERE \"LearningModules\".categories_id = \"Categories\".id AND \"LearningModules\".id = :id";
cmd.Parameters.Add("id", id);
int? globalId = PostgreSQLConn.ExecuteScalar<int>(cmd, Parent.CurrentUser);
if (!globalId.HasValue)
return new Category(0);
return new Category(globalId.Value);
}
}
}
/// <summary>
/// Sets the category.
/// </summary>
/// <param name="id">The LM id.</param>
/// <param name="catId">The category id (global id).</param>
/// <remarks>Documented by Dev08, 2008-10-03</remarks>
public void SetCategory(int id, int catId)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"LearningModules\" SET categories_id = (SELECT id FROM \"Categories\" WHERE global_id = :globalCatId) WHERE \"LearningModules\".id = :lmId";
cmd.Parameters.Add("lmId", id);
cmd.Parameters.Add("globalCatId", catId);
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
return;
}
}
}
/// <summary>
/// Sets the category.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="cat">The category.</param>
/// <remarks>Documented by Dev08, 2008-10-03</remarks>
public void SetCategory(int id, Category cat)
{
SetCategory(id, cat.Id);
}
public bool CheckUserSession()
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
return PostgreSQLConn.CheckSession(cmd, Parent.CurrentUser);
}
}
}
public void PreloadCardCache(int id)
{
if (Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardCacheInitialized, id)] != null)
return;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
// Pull all the data from the database
cmd.CommandText = "SELECT cards_id, chapters_id, chapters_title, box, active, \"timestamp\", \"text\", side FROM \"vwGetCardsForCache\" WHERE lm_id = :lm_id AND user_id = :user_id";
cmd.Parameters.Add("lm_id", id);
cmd.Parameters.Add("user_id", Parent.CurrentUser.Id);
NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
// Status and temporary data holding variables
int cardId = -1;
int chapterId = -1;
IList<IWord> question = new List<IWord>();
IList<IWord> answer = new List<IWord>();
while (reader.Read())
{
// Order of the values is the order in the SQL command text
object[] values = new object[reader.FieldCount];
reader.GetValues(values);
int thisId = Convert.ToInt32(values[0]);
if (thisId != cardId)
{
if (cardId != -1)
{
// Now store the question and answer words for this card before going to the next
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.QuestionWords, cardId)] = question;
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.AnswerWords, cardId)] = answer;
question = new List<IWord>();
answer = new List<IWord>();
}
cardId = thisId;
chapterId = Convert.ToInt32(values[1]);
// Update Id and store initial data found in every row for this card
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.CardState, id)] = new CardState(Convert.ToInt32(values[3]),
Convert.ToBoolean(values[4]), values[5] is DBNull || values[5] == null ? new DateTime() : Convert.ToDateTime(values[5])); // box, active, timestamp
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.ChapterTitle, chapterId)] = values[2].ToString();
}
// Pull the question word or answer word from this row
String side = values[7].ToString();
if (side == Side.Question.ToString())
{
question.Add(new DbWord(cardId, values[6].ToString(), WordType.Word, true, Parent));
}
else if (side == Side.Answer.ToString())
{
answer.Add(new DbWord(cardId, values[6].ToString(), WordType.Word, true, Parent));
}
}
}
}
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.CardCacheInitialized, id)] = true;
}
public void ClearUnusedMedia(int id)
{
//ToDo: Implement
}
/// <summary>
/// Gets the extensions.
/// </summary>
/// <param name="id">The id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-07-02</remarks>
public IList<Guid> GetExtensions(int id)
{
IList<Guid> guids = new List<Guid>();
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT guid FROM \"Extensions\" WHERE lm_id=@lm_id";
cmd.Parameters.Add("@lm_id", id);
NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
while (reader.Read())
guids.Add(new Guid(reader["guid"] as string));
}
}
return guids;
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="SchemaElementLookUpTable.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.EntityModel.SchemaObjectModel
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Metadata.Edm;
using System.Diagnostics;
/// <summary>
/// Summary description for SchemaElementLookUpTable.
/// </summary>
internal sealed class SchemaElementLookUpTable<T> : IEnumerable<T>, ISchemaElementLookUpTable<T>
where T : SchemaElement
{
#region Instance Fields
private Dictionary<string,T> _keyToType = null;
private List<string> _keysInDefOrder = new List<string>();
#endregion
#region Public Methods
/// <summary>
///
/// </summary>
public SchemaElementLookUpTable()
{
}
/// <summary>
///
/// </summary>
public int Count
{
get
{
return KeyToType.Count;
}
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool ContainsKey(string key)
{
return KeyToType.ContainsKey(KeyFromName(key));
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public T LookUpEquivalentKey(string key)
{
key = KeyFromName(key);
T element;
if (KeyToType.TryGetValue(key, out element))
{
return element;
}
return null;
}
/// <summary>
///
/// </summary>
public T this[string key]
{
get
{
return KeyToType[KeyFromName(key)];
}
}
/// <summary>
///
/// </summary>
public T GetElementAt(int index)
{
return KeyToType[_keysInDefOrder[index]];
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator()
{
return new SchemaElementLookUpTableEnumerator<T,T>(KeyToType,_keysInDefOrder);
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new SchemaElementLookUpTableEnumerator<T,T>(KeyToType,_keysInDefOrder);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerator<S> GetFilteredEnumerator<S>()
where S : T
{
return new SchemaElementLookUpTableEnumerator<S,T>(KeyToType,_keysInDefOrder);
}
/// <summary>
/// Add the given type to the schema look up table. If there is an error, it
/// adds the error and returns false. otherwise, it adds the type to the lookuptable
/// and returns true
/// </summary>
public AddErrorKind TryAdd(T type)
{
Debug.Assert(type != null, "type parameter is null");
if (String.IsNullOrEmpty(type.Identity))
{
return AddErrorKind.MissingNameError;
}
string key = KeyFromElement(type);
T element;
if (KeyToType.TryGetValue(key, out element))
{
return AddErrorKind.DuplicateNameError;
}
KeyToType.Add(key,type);
_keysInDefOrder.Add(key);
return AddErrorKind.Succeeded;
}
public void Add(T type, bool doNotAddErrorForEmptyName, Func<object, string> duplicateKeyErrorFormat)
{
Debug.Assert(type != null, "type parameter is null");
Debug.Assert(null != duplicateKeyErrorFormat, "duplicateKeyErrorFormat cannot be null");
AddErrorKind error = TryAdd(type);
if (error == AddErrorKind.MissingNameError)
{
if (!doNotAddErrorForEmptyName)
{
type.AddError(ErrorCode.InvalidName, EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.MissingName);
}
return;
}
else if (error == AddErrorKind.DuplicateNameError)
{
type.AddError(ErrorCode.AlreadyDefined, EdmSchemaErrorSeverity.Error,
duplicateKeyErrorFormat(type.FQName));
}
else
{
Debug.Assert(error == AddErrorKind.Succeeded, "Invalid error encountered");
}
}
#endregion
#region Internal Methods
#endregion
#region Private Methods
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static string KeyFromElement(T type)
{
return KeyFromName(type.Identity);
}
/// <summary>
///
/// </summary>
/// <param name="unnormalizedKey"></param>
/// <returns></returns>
private static string KeyFromName(string unnormalizedKey)
{
Debug.Assert(!String.IsNullOrEmpty(unnormalizedKey), "unnormalizedKey parameter is null or empty");
return unnormalizedKey;
}
#endregion
#region Private Properties
/// <summary>
///
/// </summary>
private Dictionary<string,T> KeyToType
{
get
{
if ( _keyToType == null )
{
_keyToType = new Dictionary<string,T>(StringComparer.Ordinal);
}
return _keyToType;
}
}
#endregion
}
enum AddErrorKind
{
Succeeded,
MissingNameError,
DuplicateNameError,
}
}
| |
using System;
using System.Collections;
using System.CodeDom;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Xml;
namespace Stetic {
public enum FileFormat {
Native,
Glade
}
public abstract class ObjectWrapper : MarshalByRefObject, IDisposable
{
static Hashtable wrappers = new Hashtable ();
protected IProject proj;
protected object wrapped;
protected ClassDescriptor classDescriptor;
SignalCollection signals;
internal Hashtable translationInfo;
Hashtable extendedData;
bool loading;
IObjectFrontend frontend;
bool disposed;
// This id is used by the undo methods to identify an object.
// This id is not stored, since it's used only while the widget is being
// edited in the designer
string undoId = WidgetUtils.GetUndoId ();
UndoManager undoManager;
static UndoManager defaultUndoManager = new UndoManager (true);
public ObjectWrapper ()
{
undoManager = defaultUndoManager;
}
public SignalCollection Signals {
get {
if (signals == null)
signals = new SignalCollection (this);
return signals;
}
}
public UndoManager UndoManager {
get { return GetUndoManagerInternal (); }
internal set { undoManager = value; }
}
// Called the get a diff of changes since the last call to GetUndoDiff().
// The returned object can be used to restore the object status by calling
// ApplyUndoRedoDiff. The implementation can use the UndoManager object to
// store status information.
public virtual object GetUndoDiff ()
{
return null;
}
// Called to apply a set of changes to the object. It returns
// a set of changes which can be used to reverse the operation.
public virtual object ApplyUndoRedoDiff (object diff)
{
return null;
}
public string UndoId {
get { return undoId; }
internal set { undoId = value; }
}
public virtual ObjectWrapper FindObjectByUndoId (string id)
{
if (undoId == id)
return this;
else
return null;
}
internal virtual UndoManager GetUndoManagerInternal ()
{
return undoManager;
}
internal protected bool Loading {
get { return loading; }
set { loading = value; }
}
public IObjectFrontend Frontend {
[NoGuiDispatch]
get { return frontend; }
[NoGuiDispatch]
set {
if (disposed)
throw new InvalidOperationException ("Can't bind component to disposed wrapper");
if (frontend != null)
frontend.Dispose ();
frontend = value;
}
}
public IDictionary ExtendedData {
get {
if (extendedData == null)
extendedData = new Hashtable ();
return extendedData;
}
}
public void AttachDesigner (IDesignArea designer)
{
OnDesignerAttach (designer);
}
public void DetachDesigner (IDesignArea designer)
{
OnDesignerDetach (designer);
}
public virtual void Wrap (object obj, bool initialized)
{
this.wrapped = obj;
wrappers [GetIndentityObject (obj)] = this;
}
public virtual void Dispose ()
{
if (IsDisposed)
return;
if (Disposed != null)
Disposed (this, EventArgs.Empty);
disposed = true;
if (frontend != null)
frontend.Dispose ();
frontend = null;
if (wrapped != null)
wrappers.Remove (GetIndentityObject (wrapped));
System.Runtime.Remoting.RemotingServices.Disconnect (this);
}
public bool IsDisposed {
[NoGuiDispatch]
get { return disposed; }
}
public static ObjectWrapper Create (IProject proj, object wrapped)
{
ClassDescriptor klass = Registry.LookupClassByName (wrapped.GetType ().FullName);
ObjectWrapper wrapper = klass.CreateWrapper ();
wrapper.Loading = true;
wrapper.proj = proj;
wrapper.classDescriptor = klass;
wrapper.Wrap (wrapped, true);
wrapper.OnWrapped ();
wrapper.Loading = false;
return wrapper;
}
internal static void Bind (IProject proj, ClassDescriptor klass, ObjectWrapper wrapper, object wrapped, bool initialized)
{
wrapper.proj = proj;
wrapper.classDescriptor = klass;
wrapper.Wrap (wrapped, initialized);
wrapper.OnWrapped ();
}
public virtual void Read (ObjectReader reader, XmlElement element)
{
throw new System.NotImplementedException ();
}
public virtual XmlElement Write (ObjectWriter writer)
{
throw new System.NotImplementedException ();
}
public static ObjectWrapper ReadObject (ObjectReader reader, XmlElement elem)
{
string className = elem.GetAttribute ("class");
ClassDescriptor klass;
if (reader.Format == FileFormat.Native)
klass = Registry.LookupClassByName (className);
else
klass = Registry.LookupClassByCName (className);
if (klass == null) {
ErrorWidget we = new ErrorWidget (className, elem.GetAttribute ("id"));
ErrorWidgetWrapper wrap = (ErrorWidgetWrapper) Create (reader.Project, we);
wrap.Read (reader, elem);
return wrap;
}
if (!klass.SupportsGtkVersion (reader.Project.TargetGtkVersion)) {
ErrorWidget we = new ErrorWidget (className, klass.TargetGtkVersion, reader.Project.TargetGtkVersion, elem.GetAttribute ("id"));
ErrorWidgetWrapper wrap = (ErrorWidgetWrapper) Create (reader.Project, we);
wrap.Read (reader, elem);
return wrap;
}
ObjectWrapper wrapper = klass.CreateWrapper ();
wrapper.classDescriptor = klass;
wrapper.proj = reader.Project;
try {
wrapper.OnBeginRead (reader.Format);
wrapper.Read (reader, elem);
} catch (Exception ex) {
Console.WriteLine (ex);
ErrorWidget we = new ErrorWidget (ex, elem.GetAttribute ("id"));
ErrorWidgetWrapper wrap = (ErrorWidgetWrapper) Create (reader.Project, we);
wrap.Read (reader, elem);
return wrap;
} finally {
wrapper.OnEndRead (reader.Format);
}
return wrapper;
}
internal void GenerateInitCode (GeneratorContext ctx, CodeExpression var)
{
// Set the value for initialization properties. The value for those properties is
// usually set in the constructor, but top levels are created by the user, so
// those properties need to be explicitely set in the Gui.Build method.
foreach (PropertyDescriptor prop in ClassDescriptor.InitializationProperties) {
GeneratePropertySet (ctx, var, prop);
}
}
internal protected virtual void GenerateBuildCode (GeneratorContext ctx, CodeExpression var)
{
// Write the widget properties
foreach (ItemGroup group in ClassDescriptor.ItemGroups) {
foreach (ItemDescriptor item in group) {
if (!item.SupportsGtkVersion (Project.TargetGtkVersion))
continue;
PropertyDescriptor prop = item as PropertyDescriptor;
if (prop == null || !prop.IsRuntimeProperty)
continue;
if (ClassDescriptor.InitializationProperties != null && Array.IndexOf (ClassDescriptor.InitializationProperties, prop) != -1)
continue;
GeneratePropertySet (ctx, var, prop);
}
}
}
internal protected virtual void GeneratePostBuildCode (GeneratorContext ctx, CodeExpression var)
{
}
internal protected virtual CodeExpression GenerateObjectCreation (GeneratorContext ctx)
{
if (ClassDescriptor.InitializationProperties != null) {
CodeExpression[] paramters = new CodeExpression [ClassDescriptor.InitializationProperties.Length];
for (int n=0; n < paramters.Length; n++) {
PropertyDescriptor prop = ClassDescriptor.InitializationProperties [n];
paramters [n] = ctx.GenerateValue (prop.GetValue (Wrapped), prop.RuntimePropertyType, prop.Translatable && prop.IsTranslated (Wrapped));
}
return new CodeObjectCreateExpression (WrappedTypeName, paramters);
} else
return new CodeObjectCreateExpression (WrappedTypeName);
}
protected virtual void GeneratePropertySet (GeneratorContext ctx, CodeExpression var, PropertyDescriptor prop)
{
object oval = prop.GetValue (Wrapped);
if (oval == null || (prop.HasDefault && prop.IsDefaultValue (oval)))
return;
CodeExpression val = ctx.GenerateValue (oval, prop.RuntimePropertyType, prop.Translatable && prop.IsTranslated (Wrapped));
CodeExpression cprop;
TypedPropertyDescriptor tprop = prop as TypedPropertyDescriptor;
if (tprop == null || tprop.GladeProperty == prop) {
cprop = new CodePropertyReferenceExpression (var, prop.Name);
} else {
cprop = new CodePropertyReferenceExpression (var, tprop.GladeProperty.Name);
cprop = new CodePropertyReferenceExpression (cprop, prop.Name);
}
ctx.Statements.Add (new CodeAssignStatement (cprop, val));
}
public static ObjectWrapper Lookup (object obj)
{
if (obj == null)
return null;
else
return wrappers [GetIndentityObject (obj)] as Stetic.ObjectWrapper;
}
public object Wrapped {
get {
return wrapped;
}
}
public IProject Project {
get {
return proj;
}
}
public ClassDescriptor ClassDescriptor {
get { return classDescriptor; }
}
public virtual string WrappedTypeName {
get { return classDescriptor.WrappedTypeName; }
}
public void NotifyChanged ()
{
if (UndoManager.CanNotifyChanged (this))
OnObjectChanged (new ObjectWrapperEventArgs (this));
}
internal void FireObjectChangedEvent ()
{
OnObjectChanged (new ObjectWrapperEventArgs (this));
}
static object GetIndentityObject (object ob)
{
if (ob is Gtk.Container.ContainerChild) {
// We handle ContainerChild in a special way here since
// the Gtk.Container indexer always returns a new ContainerChild
// instance. We register its wrapper using ContainerChildHashItem
// to make sure that two different instance of the same ContainerChild
// can be found equal.
ContainerChildHashItem p = new ContainerChildHashItem ();
p.ContainerChild = (Gtk.Container.ContainerChild) ob;
return p;
}
else
return ob;
}
public delegate void WrapperNotificationDelegate (object obj, string propertyName);
public event WrapperNotificationDelegate Notify;
public event SignalEventHandler SignalAdded;
public event SignalEventHandler SignalRemoved;
public event SignalChangedEventHandler SignalChanged;
public event EventHandler Disposed;
// Fired when any information of the object changes.
public event ObjectWrapperEventHandler ObjectChanged;
protected virtual void OnBeginRead (FileFormat format)
{
loading = true;
}
protected virtual void OnEndRead (FileFormat format)
{
loading = false;
}
internal protected virtual void OnObjectChanged (ObjectWrapperEventArgs args)
{
if (frontend != null)
frontend.NotifyChanged ();
if (!Loading) {
if (proj != null)
proj.NotifyObjectChanged (args);
if (ObjectChanged != null)
ObjectChanged (this, args);
}
}
protected virtual void EmitNotify (string propertyName)
{
if (!Loading) {
NotifyChanged ();
if (!Loading && Notify != null)
Notify (this, propertyName);
}
}
internal protected virtual void OnSignalAdded (SignalEventArgs args)
{
OnObjectChanged (args);
if (!Loading) {
if (proj != null)
proj.NotifySignalAdded (args);
if (SignalAdded != null)
SignalAdded (this, args);
}
}
internal protected virtual void OnSignalRemoved (SignalEventArgs args)
{
OnObjectChanged (args);
if (!Loading) {
if (proj != null)
proj.NotifySignalRemoved (args);
if (SignalRemoved != null)
SignalRemoved (this, args);
}
}
internal protected virtual void OnSignalChanged (SignalChangedEventArgs args)
{
OnObjectChanged (args);
if (!Loading) {
if (proj != null)
proj.NotifySignalChanged (args);
if (SignalChanged != null)
SignalChanged (this, args);
}
}
internal protected virtual void OnDesignerAttach (IDesignArea designer)
{
}
internal protected virtual void OnDesignerDetach (IDesignArea designer)
{
}
internal protected virtual void OnWrapped ()
{
}
internal protected virtual void DropObject (string data, Gtk.Widget obj)
{
// Called by DND.Drop
}
public override object InitializeLifetimeService ()
{
// Will be disconnected when calling Dispose
return null;
}
}
// Wraps a ContainerChild, and properly implements GetHashCode() and Equals()
struct ContainerChildHashItem
{
public Gtk.Container.ContainerChild ContainerChild;
public override int GetHashCode ()
{
return ContainerChild.Parent.GetHashCode () + ContainerChild.Child.GetHashCode ();
}
public override bool Equals (object ob)
{
if (!(ob is ContainerChildHashItem))
return false;
ContainerChildHashItem ot = (ContainerChildHashItem) ob;
return ot.ContainerChild.Child == ContainerChild.Child && ot.ContainerChild.Parent == ContainerChild.Parent;
}
}
public interface IObjectFrontend: IDisposable
{
void NotifyChanged ();
}
}
| |
// 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 GetAndWithElementInt320()
{
var test = new VectorGetAndWithElement__GetAndWithElementInt320();
// 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__GetAndWithElementInt320
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Int32[] values = new Int32[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetInt32();
}
Vector256<Int32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
Int32 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Int32 insertedValue = TestLibrary.Generator.GetInt32();
try
{
Vector256<Int32> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Int32[] values = new Int32[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetInt32();
}
Vector256<Int32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Int32)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Int32 insertedValue = TestLibrary.Generator.GetInt32();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<Int32>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Int32 result, Int32[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<Int32> result, Int32[] values, Int32 insertedValue, [CallerMemberName] string method = "")
{
Int32[] resultElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Int32[] result, Int32[] values, Int32 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.WithElement(0): {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;
}
}
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class LinearLayout : android.view.ViewGroup
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected LinearLayout(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public new partial class LayoutParams : android.view.ViewGroup.MarginLayoutParams
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::java.lang.String debug(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.widget.LinearLayout.LayoutParams.staticClass, "debug", "(Ljava/lang/String;)Ljava/lang/String;", ref global::android.widget.LinearLayout.LayoutParams._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m1;
public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.LinearLayout.LayoutParams._m1.native == global::System.IntPtr.Zero)
global::android.widget.LinearLayout.LayoutParams._m1 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m2;
public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.LinearLayout.LayoutParams._m2.native == global::System.IntPtr.Zero)
global::android.widget.LinearLayout.LayoutParams._m2 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(II)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m3;
public LayoutParams(int arg0, int arg1, float arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.LinearLayout.LayoutParams._m3.native == global::System.IntPtr.Zero)
global::android.widget.LinearLayout.LayoutParams._m3 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(IIF)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m4;
public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.LinearLayout.LayoutParams._m4.native == global::System.IntPtr.Zero)
global::android.widget.LinearLayout.LayoutParams._m4 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m5;
public LayoutParams(android.view.ViewGroup.MarginLayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.LinearLayout.LayoutParams._m5.native == global::System.IntPtr.Zero)
global::android.widget.LinearLayout.LayoutParams._m5 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$MarginLayoutParams;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _weight6071;
public float weight
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetFloatField(this.JvmHandle, _weight6071);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _gravity6072;
public int gravity
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _gravity6072);
}
set
{
}
}
static LayoutParams()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.LinearLayout.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/LinearLayout$LayoutParams"));
global::android.widget.LinearLayout.LayoutParams._weight6071 = @__env.GetFieldIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "weight", "F");
global::android.widget.LinearLayout.LayoutParams._gravity6072 = @__env.GetFieldIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "gravity", "I");
}
}
public new int Gravity
{
set
{
setGravity(value);
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual void setGravity(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "setGravity", "(I)V", ref global::android.widget.LinearLayout._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "onLayout", "(ZIIII)V", ref global::android.widget.LinearLayout._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
public new int Baseline
{
get
{
return getBaseline();
}
}
private static global::MonoJavaBridge.MethodId _m2;
public override int getBaseline()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.LinearLayout.staticClass, "getBaseline", "()I", ref global::android.widget.LinearLayout._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
protected override void onMeasure(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "onMeasure", "(II)V", ref global::android.widget.LinearLayout._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.LinearLayout.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z", ref global::android.widget.LinearLayout._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::android.widget.LinearLayout.LayoutParams generateLayoutParams(android.util.AttributeSet arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.LinearLayout.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/widget/LinearLayout$LayoutParams;", ref global::android.widget.LinearLayout._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.LinearLayout.LayoutParams;
}
private static global::MonoJavaBridge.MethodId _m6;
protected virtual global::android.widget.LinearLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.LinearLayout.staticClass, "generateLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Landroid/widget/LinearLayout$LayoutParams;", ref global::android.widget.LinearLayout._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.LinearLayout.LayoutParams;
}
private static global::MonoJavaBridge.MethodId _m7;
protected virtual global::android.widget.LinearLayout.LayoutParams generateDefaultLayoutParams()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.LinearLayout.staticClass, "generateDefaultLayoutParams", "()Landroid/widget/LinearLayout$LayoutParams;", ref global::android.widget.LinearLayout._m7) as android.widget.LinearLayout.LayoutParams;
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual bool isBaselineAligned()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.LinearLayout.staticClass, "isBaselineAligned", "()Z", ref global::android.widget.LinearLayout._m8);
}
public new bool BaselineAligned
{
set
{
setBaselineAligned(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void setBaselineAligned(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "setBaselineAligned", "(Z)V", ref global::android.widget.LinearLayout._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int BaselineAlignedChildIndex
{
get
{
return getBaselineAlignedChildIndex();
}
set
{
setBaselineAlignedChildIndex(value);
}
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual int getBaselineAlignedChildIndex()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.LinearLayout.staticClass, "getBaselineAlignedChildIndex", "()I", ref global::android.widget.LinearLayout._m10);
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual void setBaselineAlignedChildIndex(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "setBaselineAlignedChildIndex", "(I)V", ref global::android.widget.LinearLayout._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float WeightSum
{
get
{
return getWeightSum();
}
set
{
setWeightSum(value);
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual float getWeightSum()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.widget.LinearLayout.staticClass, "getWeightSum", "()F", ref global::android.widget.LinearLayout._m12);
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void setWeightSum(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "setWeightSum", "(F)V", ref global::android.widget.LinearLayout._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void setOrientation(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "setOrientation", "(I)V", ref global::android.widget.LinearLayout._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int Orientation
{
get
{
return getOrientation();
}
set
{
setOrientation(value);
}
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual int getOrientation()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.LinearLayout.staticClass, "getOrientation", "()I", ref global::android.widget.LinearLayout._m15);
}
public new int HorizontalGravity
{
set
{
setHorizontalGravity(value);
}
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void setHorizontalGravity(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "setHorizontalGravity", "(I)V", ref global::android.widget.LinearLayout._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int VerticalGravity
{
set
{
setVerticalGravity(value);
}
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setVerticalGravity(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.LinearLayout.staticClass, "setVerticalGravity", "(I)V", ref global::android.widget.LinearLayout._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m18;
public LinearLayout(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.LinearLayout._m18.native == global::System.IntPtr.Zero)
global::android.widget.LinearLayout._m18 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m19;
public LinearLayout(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.LinearLayout._m19.native == global::System.IntPtr.Zero)
global::android.widget.LinearLayout._m19 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int HORIZONTAL
{
get
{
return 0;
}
}
public static int VERTICAL
{
get
{
return 1;
}
}
static LinearLayout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.LinearLayout.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/LinearLayout"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans.Streams
{
internal class StreamConsumer<T> : IInternalAsyncObservable<T>
{
internal bool IsRewindable { get; private set; }
private readonly StreamImpl<T> stream;
private readonly string streamProviderName;
[NonSerialized]
private readonly IStreamProviderRuntime providerRuntime;
[NonSerialized]
private readonly IStreamPubSub pubSub;
private StreamConsumerExtension myExtension;
private IStreamConsumerExtension myGrainReference;
[NonSerialized]
private readonly AsyncLock bindExtLock;
[NonSerialized]
private readonly Logger logger;
public StreamConsumer(StreamImpl<T> stream, string streamProviderName, IStreamProviderRuntime providerUtilities, IStreamPubSub pubSub, bool isRewindable)
{
if (stream == null) throw new ArgumentNullException("stream");
if (providerUtilities == null) throw new ArgumentNullException("providerUtilities");
if (pubSub == null) throw new ArgumentNullException("pubSub");
logger = LogManager.GetLogger(string.Format("StreamConsumer<{0}>-{1}", typeof(T).Name, stream), LoggerType.Runtime);
this.stream = stream;
this.streamProviderName = streamProviderName;
providerRuntime = providerUtilities;
this.pubSub = pubSub;
IsRewindable = isRewindable;
myExtension = null;
myGrainReference = null;
bindExtLock = new AsyncLock();
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer)
{
return SubscribeAsync(observer, null);
}
public async Task<StreamSubscriptionHandle<T>> SubscribeAsync(
IAsyncObserver<T> observer,
StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
if (token != null && !IsRewindable)
throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable.");
if (observer is GrainReference)
throw new ArgumentException("On-behalf subscription via grain references is not supported. Only passing of object references is allowed.", "observer");
if (logger.IsVerbose) logger.Verbose("Subscribe Observer={0} Token={1}", observer, token);
await BindExtensionLazy();
IStreamFilterPredicateWrapper filterWrapper = null;
if (filterFunc != null)
filterWrapper = new FilterPredicateWrapperData(filterData, filterFunc);
if (logger.IsVerbose) logger.Verbose("Subscribe - Connecting to Rendezvous {0} My GrainRef={1} Token={2}",
pubSub, myGrainReference, token);
GuidId subscriptionId = pubSub.CreateSubscriptionId(stream.StreamId, myGrainReference);
// Optimistic Concurrency:
// In general, we should first register the subsription with the pubsub (pubSub.RegisterConsumer)
// and only if it succeeds store it locally (myExtension.SetObserver).
// Basicaly, those 2 operations should be done as one atomic transaction - either both or none and isolated from concurrent reads.
// BUT: there is a distributed race here: the first msg may arrive before the call is awaited
// (since the pubsub notifies the producer that may immideately produce)
// and will thus not find the subriptionHandle in the extension, basically violating "isolation".
// Therefore, we employ Optimistic Concurrency Control here to guarantee isolation:
// we optimisticaly store subscriptionId in the handle first before calling pubSub.RegisterConsumer
// and undo it in the case of failure.
// There is no problem with that we call myExtension.SetObserver too early before the handle is registered in pub sub,
// since this subscriptionId is unique (random Guid) and no one knows it anyway, unless successfully subscribed in the pubsub.
var subriptionHandle = myExtension.SetObserver(subscriptionId, stream, observer, token, filterWrapper);
try
{
await pubSub.RegisterConsumer(subscriptionId, stream.StreamId, streamProviderName, myGrainReference, filterWrapper);
return subriptionHandle;
} catch(Exception)
{
// Undo the previous call myExtension.SetObserver.
myExtension.RemoveObserver(subscriptionId);
throw;
}
}
public async Task<StreamSubscriptionHandle<T>> ResumeAsync(
StreamSubscriptionHandle<T> handle,
IAsyncObserver<T> observer,
StreamSequenceToken token = null)
{
StreamSubscriptionHandleImpl<T> oldHandleImpl = CheckHandleValidity(handle);
if (token != null && !IsRewindable)
throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable.");
if (logger.IsVerbose) logger.Verbose("Resume Observer={0} Token={1}", observer, token);
await BindExtensionLazy();
if (logger.IsVerbose) logger.Verbose("Resume - Connecting to Rendezvous {0} My GrainRef={1} Token={2}",
pubSub, myGrainReference, token);
StreamSubscriptionHandle<T> newHandle = myExtension.SetObserver(oldHandleImpl.SubscriptionId, stream, observer, token, null);
// On failure caller should be able to retry using the original handle, so invalidate old handle only if everything succeeded.
oldHandleImpl.Invalidate();
return newHandle;
}
public async Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle)
{
await BindExtensionLazy();
StreamSubscriptionHandleImpl<T> handleImpl = CheckHandleValidity(handle);
if (logger.IsVerbose) logger.Verbose("Unsubscribe StreamSubscriptionHandle={0}", handle);
myExtension.RemoveObserver(handleImpl.SubscriptionId);
// UnregisterConsumer from pubsub even if does not have this handle localy, to allow UnsubscribeAsync retries.
if (logger.IsVerbose) logger.Verbose("Unsubscribe - Disconnecting from Rendezvous {0} My GrainRef={1}",
pubSub, myGrainReference);
await pubSub.UnregisterConsumer(handleImpl.SubscriptionId, stream.StreamId, streamProviderName);
handleImpl.Invalidate();
}
public async Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptions()
{
await BindExtensionLazy();
List<GuidId> subscriptionIds = await pubSub.GetAllSubscriptions(stream.StreamId, myGrainReference);
return subscriptionIds.Select(id => new StreamSubscriptionHandleImpl<T>(id, stream, IsRewindable))
.ToList<StreamSubscriptionHandle<T>>();
}
public async Task Cleanup()
{
if (logger.IsVerbose) logger.Verbose("Cleanup() called");
if (myExtension == null)
return;
var allHandles = myExtension.GetAllStreamHandles<T>();
var tasks = new List<Task>();
foreach (var handle in allHandles)
{
myExtension.RemoveObserver(handle.SubscriptionId);
tasks.Add(pubSub.UnregisterConsumer(handle.SubscriptionId, stream.StreamId, streamProviderName));
}
try
{
await Task.WhenAll(tasks);
} catch (Exception exc)
{
logger.Warn(ErrorCode.StreamProvider_ConsumerFailedToUnregister,
"Ignoring unhandled exception during PubSub.UnregisterConsumer", exc);
}
myExtension = null;
}
// Used in test.
internal bool InternalRemoveObserver(StreamSubscriptionHandle<T> handle)
{
return myExtension != null && myExtension.RemoveObserver(((StreamSubscriptionHandleImpl<T>)handle).SubscriptionId);
}
internal Task<int> DiagGetConsumerObserversCount()
{
return Task.FromResult(myExtension.DiagCountStreamObservers<T>(stream.StreamId));
}
private async Task BindExtensionLazy()
{
if (myExtension == null)
{
using (await bindExtLock.LockAsync())
{
if (myExtension == null)
{
if (logger.IsVerbose) logger.Verbose("BindExtensionLazy - Binding local extension to stream runtime={0}", providerRuntime);
var tup = await providerRuntime.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>(
() => new StreamConsumerExtension(providerRuntime, IsRewindable));
myExtension = tup.Item1;
myGrainReference = tup.Item2;
if (logger.IsVerbose) logger.Verbose("BindExtensionLazy - Connected Extension={0} GrainRef={1}", myExtension, myGrainReference);
}
}
}
}
private StreamSubscriptionHandleImpl<T> CheckHandleValidity(StreamSubscriptionHandle<T> handle)
{
if (handle == null)
throw new ArgumentNullException("handle");
if (!handle.StreamIdentity.Equals(stream))
throw new ArgumentException("Handle is not for this stream.", "handle");
var handleImpl = handle as StreamSubscriptionHandleImpl<T>;
if (handleImpl == null)
throw new ArgumentException("Handle type not supported.", "handle");
if (!handleImpl.IsValid)
throw new ArgumentException("Handle is no longer valid. It has been used to unsubscribe or resume.", "handle");
return handleImpl;
}
}
}
| |
// 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.Composition;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.EngineV1;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Traits = Microsoft.CodeAnalysis.Test.Utilities.Traits;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
public class DiagnosticStateTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void SerializationTest_Document()
{
using (var workspace = new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, workspaceKind: "DiagnosticTest"))
{
var utcTime = DateTime.UtcNow;
var version1 = VersionStamp.Create(utcTime);
var version2 = VersionStamp.Create(utcTime.AddDays(1));
var document = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp).AddDocument("TestDocument", "");
var diagnostics = new[]
{
new DiagnosticData(
"test1", "Test", "test1 message", "test1 message format",
DiagnosticSeverity.Info, DiagnosticSeverity.Info, false, 1,
ImmutableArray<string>.Empty, ImmutableDictionary<string, string>.Empty,
workspace, document.Project.Id, new DiagnosticDataLocation(document.Id,
new TextSpan(10, 20), "originalFile1", 30, 30, 40, 40, "mappedFile1", 10, 10, 20, 20)),
new DiagnosticData(
"test2", "Test", "test2 message", "test2 message format",
DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 0,
ImmutableArray.Create<string>("Test2"), ImmutableDictionary<string, string>.Empty.Add("propertyKey", "propertyValue"),
workspace, document.Project.Id, new DiagnosticDataLocation(document.Id,
new TextSpan(30, 40), "originalFile2", 70, 70, 80, 80, "mappedFile2", 50, 50, 60, 60), title: "test2 title", description: "test2 description", helpLink: "http://test2link"),
new DiagnosticData(
"test3", "Test", "test3 message", "test3 message format",
DiagnosticSeverity.Error, DiagnosticSeverity.Warning, true, 2,
ImmutableArray.Create<string>("Test3", "Test3_2"), ImmutableDictionary<string, string>.Empty.Add("p1Key", "p1Value").Add("p2Key", "p2Value"),
workspace, document.Project.Id, new DiagnosticDataLocation(document.Id,
new TextSpan(50, 60), "originalFile3", 110, 110, 120, 120, "mappedFile3", 90, 90, 100, 100), title: "test3 title", description: "test3 description", helpLink: "http://test3link"),
};
var original = new DiagnosticIncrementalAnalyzer.AnalysisData(version1, version2, diagnostics.ToImmutableArray());
var state = new DiagnosticIncrementalAnalyzer.DiagnosticState("Test", VersionStamp.Default, LanguageNames.CSharp);
state.PersistAsync(document, original, CancellationToken.None).Wait();
var recovered = state.TryGetExistingDataAsync(document, CancellationToken.None).Result;
Assert.Equal(original.TextVersion, recovered.TextVersion);
Assert.Equal(original.DataVersion, recovered.DataVersion);
AssertDiagnostics(original.Items, recovered.Items);
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void SerializationTest_Project()
{
using (var workspace = new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, workspaceKind: "DiagnosticTest"))
{
var utcTime = DateTime.UtcNow;
var version1 = VersionStamp.Create(utcTime);
var version2 = VersionStamp.Create(utcTime.AddDays(1));
var document = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp).AddDocument("TestDocument", "");
var diagnostics = new[]
{
new DiagnosticData(
"test1", "Test", "test1 message", "test1 message format",
DiagnosticSeverity.Info, DiagnosticSeverity.Info, false, 1,
ImmutableArray<string>.Empty, ImmutableDictionary<string, string>.Empty,
workspace, document.Project.Id, description: "test1 description", helpLink: "http://test1link"),
new DiagnosticData(
"test2", "Test", "test2 message", "test2 message format",
DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 0,
ImmutableArray.Create<string>("Test2"), ImmutableDictionary<string, string>.Empty.Add("p1Key", "p2Value"),
workspace, document.Project.Id),
new DiagnosticData(
"test3", "Test", "test3 message", "test3 message format",
DiagnosticSeverity.Error, DiagnosticSeverity.Warning, true, 2,
ImmutableArray.Create<string>("Test3", "Test3_2"), ImmutableDictionary<string, string>.Empty.Add("p2Key", "p2Value").Add("p1Key", "p1Value"),
workspace, document.Project.Id, description: "test3 description", helpLink: "http://test3link"),
};
var original = new DiagnosticIncrementalAnalyzer.AnalysisData(version1, version2, diagnostics.ToImmutableArray());
var state = new DiagnosticIncrementalAnalyzer.DiagnosticState("Test", VersionStamp.Default, LanguageNames.CSharp);
state.PersistAsync(document.Project, original, CancellationToken.None).Wait();
var recovered = state.TryGetExistingDataAsync(document.Project, CancellationToken.None).Result;
Assert.Equal(original.TextVersion, recovered.TextVersion);
Assert.Equal(original.DataVersion, recovered.DataVersion);
AssertDiagnostics(original.Items, recovered.Items);
}
}
private void AssertDiagnostics(ImmutableArray<DiagnosticData> items1, ImmutableArray<DiagnosticData> items2)
{
Assert.Equal(items1.Length, items1.Length);
for (var i = 0; i < items1.Length; i++)
{
Assert.Equal(items1[i].Id, items2[i].Id);
Assert.Equal(items1[i].Category, items2[i].Category);
Assert.Equal(items1[i].Message, items2[i].Message);
Assert.Equal(items1[i].ENUMessageForBingSearch, items2[i].ENUMessageForBingSearch);
Assert.Equal(items1[i].Severity, items2[i].Severity);
Assert.Equal(items1[i].IsEnabledByDefault, items2[i].IsEnabledByDefault);
Assert.Equal(items1[i].WarningLevel, items2[i].WarningLevel);
Assert.Equal(items1[i].DefaultSeverity, items2[i].DefaultSeverity);
Assert.Equal(items1[i].CustomTags.Count, items2[i].CustomTags.Count);
for (var j = 0; j < items1[i].CustomTags.Count; j++)
{
Assert.Equal(items1[i].CustomTags[j], items2[i].CustomTags[j]);
}
Assert.Equal(items1[i].Properties.Count, items2[i].Properties.Count);
Assert.True(items1[i].Properties.SetEquals(items2[i].Properties));
Assert.Equal(items1[i].Workspace, items2[i].Workspace);
Assert.Equal(items1[i].ProjectId, items2[i].ProjectId);
Assert.Equal(items1[i].DocumentId, items2[i].DocumentId);
Assert.Equal(items1[i].HasTextSpan, items2[i].HasTextSpan);
if (items1[i].HasTextSpan)
{
Assert.Equal(items1[i].TextSpan, items2[i].TextSpan);
}
Assert.Equal(items1[i].DataLocation?.MappedFilePath, items2[i].DataLocation?.MappedFilePath);
Assert.Equal(items1[i].DataLocation?.MappedStartLine, items2[i].DataLocation?.MappedStartLine);
Assert.Equal(items1[i].DataLocation?.MappedStartColumn, items2[i].DataLocation?.MappedStartColumn);
Assert.Equal(items1[i].DataLocation?.MappedEndLine, items2[i].DataLocation?.MappedEndLine);
Assert.Equal(items1[i].DataLocation?.MappedEndColumn, items2[i].DataLocation?.MappedEndColumn);
Assert.Equal(items1[i].DataLocation?.OriginalFilePath, items2[i].DataLocation?.OriginalFilePath);
Assert.Equal(items1[i].DataLocation?.OriginalStartLine, items2[i].DataLocation?.OriginalStartLine);
Assert.Equal(items1[i].DataLocation?.OriginalStartColumn, items2[i].DataLocation?.OriginalStartColumn);
Assert.Equal(items1[i].DataLocation?.OriginalEndLine, items2[i].DataLocation?.OriginalEndLine);
Assert.Equal(items1[i].DataLocation?.OriginalEndColumn, items2[i].DataLocation?.OriginalEndColumn);
Assert.Equal(items1[i].Description, items2[i].Description);
Assert.Equal(items1[i].HelpLink, items2[i].HelpLink);
}
}
[ExportWorkspaceServiceFactory(typeof(IPersistentStorageService), "DiagnosticTest"), Shared]
public class PersistentStorageServiceFactory : IWorkspaceServiceFactory
{
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
return new Service();
}
public class Service : IPersistentStorageService
{
private readonly Storage _instance = new Storage();
IPersistentStorage IPersistentStorageService.GetStorage(Solution solution)
{
return _instance;
}
internal class Storage : IPersistentStorage
{
private readonly Dictionary<object, Stream> _map = new Dictionary<object, Stream>();
public Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
{
var stream = _map[name];
stream.Position = 0;
return Task.FromResult(stream);
}
public Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken))
{
var stream = _map[Tuple.Create(project, name)];
stream.Position = 0;
return Task.FromResult(stream);
}
public Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken))
{
var stream = _map[Tuple.Create(document, name)];
stream.Position = 0;
return Task.FromResult(stream);
}
public Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
_map[name] = new MemoryStream();
stream.CopyTo(_map[name]);
return SpecializedTasks.True;
}
public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
_map[Tuple.Create(project, name)] = new MemoryStream();
stream.CopyTo(_map[Tuple.Create(project, name)]);
return SpecializedTasks.True;
}
public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
_map[Tuple.Create(document, name)] = new MemoryStream();
stream.CopyTo(_map[Tuple.Create(document, name)]);
return SpecializedTasks.True;
}
protected virtual void Dispose(bool disposing)
{
}
public void Dispose()
{
Dispose(true);
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Boogie;
namespace Symbooglix
{
namespace Transform
{
public class GlobalDeadDeclEliminationPass : IPass
{
public GlobalDeadDeclEliminationPass()
{
}
public string GetName()
{
return "Global Dead Declaration Elimination Pass";
}
public void SetPassInfo(ref PassInfo passInfo)
{
return;
}
public bool RunOn(Program prog, PassInfo passInfo)
{
// Collect used functions and global variables.
// Note we don't want to consider an axiom as "using" interpreted functions because
// axioms using interpreted functions aren't (or at least shouldn't be) constraining
// those interpreted functions. If we considered interpreted functions as being used by
// axioms then this might prevent those axioms (and uninterpreted functions in those axioms)
// form being removed.
var FFV = new FindUsedFunctionAndGlobalVariableVisitor(/*ignoreInterpretedFunctionsInAxioms=*/ true);
FFV.Visit(prog);
// Initialise with all declared functions
var functionsToRemove = new HashSet<Function>(prog.TopLevelDeclarations.OfType<Function>());
// reduce the set by removing functions used in code
functionsToRemove.ExceptWith(FFV.FuncsUsedInCode);
// Initialise with all declared global variables
var gvsToRemove = new HashSet<Variable>(prog.TopLevelDeclarations.OfType<Variable>());
// reduce the set by removing variables used in code
gvsToRemove.ExceptWith(FFV.VarsUsedInCode);
// We don't Initialise with all declared axioms
var axiomsToRemove = new HashSet<Axiom>();
// Compute transitive closure of axiom dependencies.
// Some axioms may share variables for example
// axiom e > f;
// axiom f > g;
// axiom g > h;
//
// if we decide that only variable h is live we need to keep all three axioms
// which requires that we know how axioms depend on each other
//
// An axiom A is directly dependent on axiom B iff they share any common
// functions or global variables.
//
// Axioms can be transitively dependent on each other
Dictionary<Axiom, HashSet<Axiom>> axiomDeps = new Dictionary<Axiom, HashSet<Axiom>>();
foreach (var axiom in prog.TopLevelDeclarations.OfType<Axiom>())
{
axiomDeps[axiom] = new HashSet<Axiom>();
}
// Compute direct dependencies
foreach (var axiom in prog.TopLevelDeclarations.OfType<Axiom>())
{
foreach (var otherAxiom in prog.TopLevelDeclarations.OfType<Axiom>().Where( a => a != axiom))
{
if (axiomDeps[axiom].Contains(otherAxiom))
continue;
if ( FFV.FuncsUsedInAxiom[axiom].Overlaps( FFV.FuncsUsedInAxiom[otherAxiom]) ||
FFV.VarsUsedInAxiom[axiom].Overlaps( FFV.VarsUsedInAxiom[otherAxiom])
)
{
axiomDeps[axiom].Add(otherAxiom);
axiomDeps[otherAxiom].Add(axiom);
}
}
}
// For each axiom compute the transistive closure of dependencies by reaching a fixed point for each axiom
foreach (var axiom in prog.TopLevelDeclarations.OfType<Axiom>())
{
bool setChanged = false;
do
{
var axiomsToAdd = new HashSet<Axiom>();
setChanged = false;
foreach (var dep in axiomDeps[axiom])
{
axiomsToAdd.UnionWith(axiomDeps[dep]);
}
int previousNumberOfDeps = axiomDeps[axiom].Count;
axiomDeps[axiom].UnionWith(axiomsToAdd);
if (axiomDeps[axiom].Count > previousNumberOfDeps)
setChanged = true;
} while (setChanged);
}
// Work out which axioms to remove
var axiomsMustKeep = new HashSet<Axiom>();
foreach (var axiom in prog.TopLevelDeclarations.OfType<Axiom>())
{
var liveVars = new HashSet<Variable>(FFV.VarsUsedInAxiom[axiom]);
// Remove the variables (that we plan to remove) from the set so we are only left with live variables
liveVars.ExceptWith(gvsToRemove);
var liveFuncs = new HashSet<Function>(FFV.FuncsUsedInAxiom[axiom]);
// Remove the functions (that we plan to remove) from the set so we are only left with live functions
liveFuncs.ExceptWith(functionsToRemove);
if (liveVars.Count == 0 && liveFuncs.Count == 0)
{
axiomsToRemove.Add(axiom);
}
else
{
// Can't remove axiom. This means we shouldn't remove any of its dependencies
// We can't modify axiomsToRemove directly (i.e. axiomsToRemove.ExceptWith(axiomDeps[axiom]) )
// because the dependencies might be added to axiomsToRemove in a later iteration of this loop
axiomsMustKeep.UnionWith(axiomDeps[axiom]);
}
}
// Remove any axioms from the set that we discovered must be kept.
axiomsToRemove.ExceptWith(axiomsMustKeep);
// Work out which functions to remove
var newFunctionsToRemove = new HashSet<Function>(); // can't modify set whilst iterating so write into temp
foreach (var f in functionsToRemove)
{
if (!FFV.AxiomsUsingFunc.ContainsKey(f))
{
// no axioms use this function so we can definitely remove it
newFunctionsToRemove.Add(f);
continue;
}
var liveAxiomsUsingFunc = new HashSet<Axiom>(FFV.AxiomsUsingFunc[f]);
// Compute which live axioms use this function
liveAxiomsUsingFunc.ExceptWith(axiomsToRemove);
if (liveAxiomsUsingFunc.Count == 0)
{
// We can remove this function
newFunctionsToRemove.Add(f);
}
}
functionsToRemove = newFunctionsToRemove;
// Work out which global variables to remove
var newGvsToRemove = new HashSet<Variable>(); // can't modify the set whilst iterarting so write into temp
foreach (var gv in gvsToRemove)
{
if (!FFV.AxiomsUsingVar.ContainsKey(gv))
{
// no axioms use this variable so we can definitely remove it
newGvsToRemove.Add(gv);
continue;
}
var liveAxiomsUsingVar = new HashSet<Axiom>(FFV.AxiomsUsingVar[gv]);
// compute which live axioms use this variable
liveAxiomsUsingVar.ExceptWith(axiomsToRemove);
if (liveAxiomsUsingVar.Count == 0)
{
// We can remove this variable
newGvsToRemove.Add(gv);
}
}
gvsToRemove = newGvsToRemove;
bool changed = false;
// Now remove the axioms
foreach (var axiom in axiomsToRemove)
{
changed = true;
Console.Error.WriteLine("Warning removing dead axiom: {0}", axiom.Expr.ToString());
prog.RemoveTopLevelDeclaration(axiom);
}
// Now remove the functions
foreach (var f in functionsToRemove)
{
changed = true;
Console.Error.WriteLine("Warning removing dead function {0}", f.Name);
prog.RemoveTopLevelDeclaration(f);
}
// Now remove the globally scoped variables
foreach (var gv in gvsToRemove)
{
changed = true;
Console.Error.WriteLine("Warning removing dead globally scoped variable {0}", gv.Name);
prog.RemoveTopLevelDeclaration(gv);
}
// FIXME: We need some way of validating the Boogie Program to make sure
// all function Calls point to top level declared functions and that reference globals
// are still top level declarations.
return changed;
}
public void Reset()
{
}
}
class FindUsedFunctionAndGlobalVariableVisitor : ReadOnlyVisitor
{
public HashSet<Function> FuncsUsedInCode; // Used in Procedure, Implementations and function bodies
public HashSet<Variable> VarsUsedInCode; // Used in Procedure, Implementations and function bodies
// Effectively storing the mapping both ways
public Dictionary<Function, HashSet<Axiom>> AxiomsUsingFunc;
public Dictionary<Axiom, HashSet<Function>> FuncsUsedInAxiom;
public Dictionary<Variable, HashSet<Axiom>> AxiomsUsingVar;
public Dictionary<Axiom, HashSet<Variable>> VarsUsedInAxiom;
private bool InAxiom;
private Axiom CurrentAxiom;
public readonly bool IgnoreInterpretedFunctionsInAxioms;
public FindUsedFunctionAndGlobalVariableVisitor(bool ignoreInterpretedFunctionsInAxioms)
{
FuncsUsedInCode = new HashSet<Function>();
VarsUsedInCode = new HashSet<Variable>();
AxiomsUsingFunc = new Dictionary<Function, HashSet<Axiom>>();
FuncsUsedInAxiom = new Dictionary<Axiom, HashSet<Function>>();
AxiomsUsingVar = new Dictionary<Variable, HashSet<Axiom>>();
VarsUsedInAxiom = new Dictionary<Axiom, HashSet<Variable>>();
IgnoreInterpretedFunctionsInAxioms = ignoreInterpretedFunctionsInAxioms;
InAxiom = false;
}
public void Clear()
{
FuncsUsedInCode.Clear();
VarsUsedInCode.Clear();
AxiomsUsingFunc.Clear();
FuncsUsedInAxiom.Clear();
AxiomsUsingVar.Clear();
VarsUsedInAxiom.Clear();
}
public override Program VisitProgram(Program node)
{
foreach (var tld in node.TopLevelDeclarations)
{
// Don't record top level functions or variables because these are declarations.
// We only care about uses of functions or variables
if (tld is GlobalVariable || tld is Constant || tld is Function)
{
continue;
}
else
{
Visit(tld);
}
}
return node;
}
public override Axiom VisitAxiom(Axiom node)
{
// Entering an Axiom
InAxiom = true;
CurrentAxiom = node;
// Initialise HashSets for this axiom
if (!FuncsUsedInAxiom.ContainsKey(node))
FuncsUsedInAxiom[node] = new HashSet<Function>();
if (!VarsUsedInAxiom.ContainsKey(node))
VarsUsedInAxiom[node] = new HashSet<Variable>();
var result = base.VisitAxiom(node);
// Leaving an Axiom
CurrentAxiom = null;
InAxiom = false;
return result;
}
public override Expr VisitNAryExpr(NAryExpr node)
{
if (node.Fun is FunctionCall)
VisitFunctionCall(node.Fun as FunctionCall);
return base.VisitNAryExpr(node);
}
public override Function VisitFunction(Function node) {
Debug.Assert(node != null);
if (InAxiom) {
Debug.Assert(CurrentAxiom != null);
if (IgnoreInterpretedFunctionsInAxioms && ExprUtil.AsUninterpretedFunction(node) == null) {
// This FunctionCall does not call an uninterpreted function. Therefore it must call an
// an interpreted function
return node;
}
if (FuncsUsedInAxiom[CurrentAxiom].Contains(node)) {
// We've already visited this function before
// in the context of this axiom. So don't visit again.
// This means we might travserse the same function
// body multiple times in the context of different axioms.
// I think that means we'll never get stuck traversing
// recursive function bodies but I'm not sure.
return node;
}
// Record the mapping both ways
if (!AxiomsUsingFunc.ContainsKey(node)) {
AxiomsUsingFunc[node] = new HashSet<Axiom>();
}
AxiomsUsingFunc[node].Add(CurrentAxiom);
// Assume Hash set has already been initialised
FuncsUsedInAxiom[CurrentAxiom].Add(node);
} else {
if (FuncsUsedInCode.Contains(node)) {
// We've visited this function before in the context
// of code so we don't need to add it to `FuncsUsedInCode`
// or travserse its body again. Traversing again might
// get us stuck in a loop with recursive functions.
return node;
}
FuncsUsedInCode.Add(node);
}
// Now if the function has a body traverse that because
// this function depends on functions that this function calls
if (node.Body != null) {
Visit(node.Body);
}
return node;
}
public void VisitFunctionCall(FunctionCall node)
{
VisitFunction(node.Func);
}
public override Variable VisitVariable(Variable node)
{
// We only record the Globally scoped variables
if (!(node is GlobalVariable) && !(node is Constant))
return base.VisitVariable(node);
if (InAxiom)
{
Debug.Assert(CurrentAxiom != null);
// Record the mapping both ways
if (!AxiomsUsingVar.ContainsKey(node))
{
AxiomsUsingVar[node] = new HashSet<Axiom>();
}
AxiomsUsingVar[node].Add(CurrentAxiom);
// Assume Hash set has already been initialised
VarsUsedInAxiom[CurrentAxiom].Add(node);
}
else
{
VarsUsedInCode.Add(node);
}
return base.VisitVariable(node);
}
}
}
}
| |
// 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.IO;
using System.Threading;
// The CODEDOM check is here to support frameworks that may not have fully
// incorporated all of corefx, but want to use System.Configuration.ConfigurationManager.
// TempFileCollection was moved in corefx.
#if CODEDOM
using System.CodeDom.Compiler;
#else
using System.IO.Internal;
#endif
namespace System.Configuration.Internal
{
internal class WriteFileContext
{
private const int SavingTimeout = 10000; // 10 seconds
private const int SavingRetryInterval = 100; // 100 milliseconds
private readonly string _templateFilename;
private TempFileCollection _tempFiles;
internal WriteFileContext(string filename, string templateFilename)
{
string directoryname = UrlPath.GetDirectoryOrRootName(filename);
_templateFilename = templateFilename;
_tempFiles = new TempFileCollection(directoryname);
try
{
TempNewFilename = _tempFiles.AddExtension("newcfg");
}
catch
{
((IDisposable)_tempFiles).Dispose();
_tempFiles = null;
throw;
}
}
internal string TempNewFilename { get; }
// Cleanup the WriteFileContext object based on either success
// or failure
//
// Note: The current algorithm guarantess
// 1) The file we are saving to will always be present
// on the file system (ie. there will be no window
// during saving in which there won't be a file there)
// 2) It will always be available for reading from a
// client and it will be complete and accurate.
//
// ... This means that writing is a bit more complicated, and may
// have to be retried (because of reading lock), but I don't see
// anyway to get around this given 1 and 2.
internal void Complete(string filename, bool success)
{
try
{
if (!success) return;
if (File.Exists(filename))
{
// Test that we can write to the file
ValidateWriteAccess(filename);
// Copy Attributes from original
DuplicateFileAttributes(filename, TempNewFilename);
}
else
{
if (_templateFilename != null)
{
// Copy Acl from template file
DuplicateTemplateAttributes(_templateFilename, TempNewFilename);
}
}
ReplaceFile(TempNewFilename, filename);
// Don't delete, since we just moved it.
_tempFiles.KeepFiles = true;
}
finally
{
((IDisposable)_tempFiles).Dispose();
_tempFiles = null;
}
}
// Copy all the files attributes that we care about from the source
// file to the destination file
private void DuplicateFileAttributes(string source, string destination)
{
DateTime creationTime;
// Copy File Attributes, ie. Hidden, Readonly, etc.
FileAttributes attributes = File.GetAttributes(source);
File.SetAttributes(destination, attributes);
// Copy Creation Time
creationTime = File.GetCreationTimeUtc(source);
File.SetCreationTimeUtc(destination, creationTime);
// Copy ACL's
DuplicateTemplateAttributes(source, destination);
}
// Copy over all the attributes you would want copied from a template file.
// As of right now this is just acl's
private void DuplicateTemplateAttributes(string source, string destination)
{
FileAttributes fileAttributes = File.GetAttributes(source);
File.SetAttributes(destination, fileAttributes);
}
// Validate that we can write to the file. This will enforce the ACL's
// on the file. Since we do our moving of files to replace, this is
// nice to ensure we are not by-passing some security permission
// that someone set (although that could bypass this via move themselves)
//
// Note: 1) This is really just a nice to have, since with directory permissions
// they could do the same thing we are doing
//
// 2) We are depending on the current behavior that if the file is locked
// and we can not open it, that we will get an UnauthorizedAccessException
// and not the IOException.
private void ValidateWriteAccess(string filename)
{
FileStream fs = null;
try
{
// Try to open file for write access
fs = new FileStream(filename,
FileMode.Open,
FileAccess.Write,
FileShare.ReadWrite);
}
catch (IOException)
{
// Someone else was using the file. Since we did not get
// the unauthorizedAccessException we have access to the file
}
finally
{
fs?.Close();
}
}
/// <summary>
/// Replace one file with another, retrying if locked.
/// </summary>
private void ReplaceFile(string source, string target)
{
bool writeSucceeded;
int duration = 0;
writeSucceeded = AttemptMove(source, target);
// The file may be open for read, if it is then
// lets try again because maybe they will finish
// soon, and we will be able to replace
while (!writeSucceeded &&
(duration < SavingTimeout) &&
File.Exists(target) &&
!FileIsWriteLocked(target))
{
Thread.Sleep(SavingRetryInterval);
duration += SavingRetryInterval;
writeSucceeded = AttemptMove(source, target);
}
if (!writeSucceeded)
{
throw new ConfigurationErrorsException(SR.Format(SR.Config_write_failed, target));
}
}
// Attempt to move a file from one location to another, overwriting if needed
private bool AttemptMove(string source, string target)
{
try
{
if (File.Exists(target))
{
File.Replace(source, target, null);
}
else
{
File.Move(source, target);
}
return true;
}
catch
{
return false;
}
}
private static bool FileIsWriteLocked(string fileName)
{
Stream fileStream = null;
if (!File.Exists(fileName))
{
// It can't be locked if it doesn't exist
return false;
}
try
{
// Try to open for shared reading
fileStream = new FileStream(fileName,
FileMode.Open,
FileAccess.Read,
FileShare.Read | FileShare.Delete);
// If we can open it for shared reading, it is not write locked
return false;
}
catch
{
return true;
}
finally
{
fileStream?.Close();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApplicationInsights.Management
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.ApplicationInsights;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExportConfigurationsOperations operations.
/// </summary>
internal partial class ExportConfigurationsOperations : IServiceOperations<ApplicationInsightsManagementClient>, IExportConfigurationsOperations
{
/// <summary>
/// Initializes a new instance of the ExportConfigurationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExportConfigurationsOperations(ApplicationInsightsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ApplicationInsightsManagementClient
/// </summary>
public ApplicationInsightsManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of Continuous Export configuration of an Application Insights
/// component.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<ApplicationInsightsComponentExportConfiguration>>> ListWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<ApplicationInsightsComponentExportConfiguration>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<ApplicationInsightsComponentExportConfiguration>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create a Continuous Export configuration of an Application Insights
/// component.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='exportProperties'>
/// Properties that need to be specified to create a Continuous Export
/// configuration of a Application Insights component.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<ApplicationInsightsComponentExportConfiguration>>> CreateWithHttpMessagesAsync(string resourceGroupName, string resourceName, ApplicationInsightsComponentExportRequest exportProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
if (exportProperties == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "exportProperties");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("exportProperties", exportProperties);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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;
if(exportProperties != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(exportProperties, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<ApplicationInsightsComponentExportConfiguration>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<ApplicationInsightsComponentExportConfiguration>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete a Continuous Export configuration of an Application Insights
/// component.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='exportId'>
/// The Continuous Export configuration ID. This is unique within a Application
/// Insights component.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ApplicationInsightsComponentExportConfiguration>> DeleteWithHttpMessagesAsync(string resourceGroupName, string resourceName, string exportId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
if (exportId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "exportId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("exportId", exportId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration/{exportId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
_url = _url.Replace("{exportId}", System.Uri.EscapeDataString(exportId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ApplicationInsightsComponentExportConfiguration>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationInsightsComponentExportConfiguration>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get the Continuous Export configuration for this export id.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='exportId'>
/// The Continuous Export configuration ID. This is unique within a Application
/// Insights component.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ApplicationInsightsComponentExportConfiguration>> GetWithHttpMessagesAsync(string resourceGroupName, string resourceName, string exportId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
if (exportId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "exportId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("exportId", exportId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration/{exportId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
_url = _url.Replace("{exportId}", System.Uri.EscapeDataString(exportId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ApplicationInsightsComponentExportConfiguration>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationInsightsComponentExportConfiguration>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Update the Continuous Export configuration for this export id.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='exportId'>
/// The Continuous Export configuration ID. This is unique within a Application
/// Insights component.
/// </param>
/// <param name='exportProperties'>
/// Properties that need to be specified to update the Continuous Export
/// configuration.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ApplicationInsightsComponentExportConfiguration>> UpdateWithHttpMessagesAsync(string resourceGroupName, string resourceName, string exportId, ApplicationInsightsComponentExportRequest exportProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
if (exportId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "exportId");
}
if (exportProperties == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "exportProperties");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("exportId", exportId);
tracingParameters.Add("exportProperties", exportProperties);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration/{exportId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
_url = _url.Replace("{exportId}", System.Uri.EscapeDataString(exportId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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;
if(exportProperties != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(exportProperties, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ApplicationInsightsComponentExportConfiguration>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationInsightsComponentExportConfiguration>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace AngleSharp.Dom
{
using AngleSharp.Text;
using System;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// A location object with information about a Url.
/// </summary>
sealed class Location : ILocation
{
#region Fields
private readonly Url _url;
#endregion
#region Events
public event EventHandler<ChangedEventArgs>? Changed;
#endregion
#region ctor
internal Location(String url)
: this(new Url(url))
{
}
internal Location(Url url)
{
_url = url ?? new Url(String.Empty);
}
#endregion
#region Properties
public Url Original => _url;
public String? Origin => _url.Origin;
public Boolean IsRelative => _url.IsRelative;
public String? UserName
{
get => _url.UserName;
set => _url.UserName = value;
}
public String? Password
{
get => _url.Password;
set => _url.Password = value;
}
[AllowNull]
public String Hash
{
get => NonEmptyPrefix(_url.Fragment, "#");
set
{
var old = _url.Href;
if (value != null)
{
if (value.Has(Symbols.Num))
{
value = value.Substring(1);
}
else if (value.Length == 0)
{
value = null!;
}
}
if (!value.Is(_url.Fragment))
{
_url.Fragment = value;
RaiseHashChanged(old);
}
}
}
public String Host
{
get => _url.Host;
set
{
var old = _url.Href;
if (!value.Isi(_url.Host))
{
_url.Host = value;
RaiseLocationChanged(old);
}
}
}
public String HostName
{
get => _url.HostName;
set
{
var old = _url.Href;
if (!value.Isi(_url.HostName))
{
_url.HostName = value;
RaiseLocationChanged(old);
}
}
}
public String Href
{
get => _url.Href;
set
{
var old = _url.Href;
if (!value.Is(_url.Href))
{
_url.Href = value;
RaiseLocationChanged(old);
}
}
}
public String PathName
{
get
{
var data = _url.Data;
return String.IsNullOrEmpty(data) ? "/" + _url.Path : data;
}
set
{
var old = _url.Href;
if (!value.Is(_url.Path))
{
_url.Path = value;
RaiseLocationChanged(old);
}
}
}
public String Port
{
get => _url.Port;
set
{
var old = _url.Href;
if (!value.Isi(_url.Port))
{
_url.Port = value;
RaiseLocationChanged(old);
}
}
}
public String Protocol
{
get => NonEmptyPostfix(_url.Scheme, ":");
set
{
var old = _url.Href;
if (!value.Isi(_url.Scheme))
{
_url.Scheme = value;
RaiseLocationChanged(old);
}
}
}
public String Search
{
get => NonEmptyPrefix(_url.Query, "?");
set
{
var old = _url.Href;
if (!value.Is(_url.Query))
{
_url.Query = value;
RaiseLocationChanged(old);
}
}
}
#endregion
#region Methods
public void Assign(String url)
{
var old = _url.Href;
if (!old.Is(url))
{
_url.Href = url;
RaiseLocationChanged(old);
}
}
public void Replace(String url)
{
var old = _url.Href;
if (!old.Is(url))
{
_url.Href = url;
RaiseLocationChanged(old);
}
}
public void Reload() => Changed?.Invoke(this, new ChangedEventArgs(false, _url.Href, _url.Href));
public override String ToString() => _url.Href;
#endregion
#region Helpers
private void RaiseHashChanged(String oldAddress) =>
Changed?.Invoke(this, new ChangedEventArgs(true, oldAddress, _url.Href));
private void RaiseLocationChanged(String oldAddress) =>
Changed?.Invoke(this, new ChangedEventArgs(false, oldAddress, _url.Href));
private static String NonEmptyPrefix(String? check, String prefix) =>
String.IsNullOrEmpty(check) ? String.Empty : String.Concat(prefix, check);
private static String NonEmptyPostfix(String? check, String postfix) =>
String.IsNullOrEmpty(check) ? String.Empty : String.Concat(check, postfix);
#endregion
#region Event Arguments
public sealed class ChangedEventArgs : EventArgs
{
public ChangedEventArgs(Boolean hashChanged, String previousLocation, String currentLocation)
{
IsHashChanged = hashChanged;
PreviousLocation = previousLocation;
CurrentLocation = currentLocation;
}
public Boolean IsReloaded => PreviousLocation.Is(CurrentLocation);
public Boolean IsHashChanged { get; }
public String PreviousLocation { get; }
public String CurrentLocation { get; }
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.