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 AddByte()
{
var test = new SimpleBinaryOpTest__AddByte();
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__AddByte
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[ElementCount];
private static Byte[] _data2 = new Byte[ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte> _dataTable;
static SimpleBinaryOpTest__AddByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AddByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte>(_data1, _data2, new Byte[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Add(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Add(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Add(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddByte();
var result = Sse2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Add(_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(Vector128<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if ((byte)(left[0] + right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((byte)(left[i] + right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Add)}<Byte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Orleans.Serialization;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// This is the base class for all typed grain references.
/// </summary>
[Serializable]
public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable
{
private readonly string genericArguments;
private readonly GuidId observerId;
[NonSerialized]
private static readonly TraceLogger logger = TraceLogger.GetLogger("GrainReference", TraceLogger.LoggerType.Runtime);
[NonSerialized] private const bool USE_DEBUG_CONTEXT = true;
[NonSerialized] private const bool USE_DEBUG_CONTEXT_PARAMS = false;
[NonSerialized]
private readonly bool isUnordered = false;
internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } }
internal bool IsObserverReference { get { return GrainId.IsClient; } }
internal GuidId ObserverId { get { return observerId; } }
private bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } }
internal GrainId GrainId { get; private set; }
/// <summary>
/// Called from generated code.
/// </summary>
protected internal readonly SiloAddress SystemTargetSilo;
/// <summary>
/// Whether the runtime environment for system targets has been initialized yet.
/// Called from generated code.
/// </summary>
protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } }
internal bool IsUnordered { get { return isUnordered; } }
#region Constructors
/// <summary>
/// Constructs a reference to the grain with the specified Id.
/// </summary>
/// <param name="grainId">The Id of the grain to refer to.</param>
private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId)
{
GrainId = grainId;
genericArguments = genericArgument;
SystemTargetSilo = systemTargetSilo;
this.observerId = observerId;
if (String.IsNullOrEmpty(genericArgument))
{
genericArguments = null; // always keep it null instead of empty.
}
// SystemTarget checks
if (grainId.IsSystemTarget && systemTargetSilo==null)
{
throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId));
}
if (grainId.IsSystemTarget && genericArguments != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument");
}
if (grainId.IsSystemTarget && observerId != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument");
}
if (!grainId.IsSystemTarget && systemTargetSilo != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo");
}
// ObserverId checks
if (grainId.IsClient && observerId == null)
{
throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId));
}
if (grainId.IsClient && genericArguments != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument");
}
if (grainId.IsClient && systemTargetSilo != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument");
}
if (!grainId.IsClient && observerId != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId");
}
isUnordered = GetUnordered();
}
/// <summary>
/// Constructs a copy of a grain reference.
/// </summary>
/// <param name="other">The reference to copy.</param>
protected GrainReference(GrainReference other)
: this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId) { }
#endregion
#region Instance creator factory functions
/// <summary>
/// Constructs a reference to the grain with the specified ID.
/// </summary>
/// <param name="grainId">The ID of the grain to refer to.</param>
internal static GrainReference FromGrainId(GrainId grainId, string genericArguments = null, SiloAddress systemTargetSilo = null)
{
return new GrainReference(grainId, genericArguments, systemTargetSilo, null);
}
internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId)
{
return new GrainReference(grainId, null, null, observerId);
}
/// <summary>
/// Called from generated code.
/// </summary>
public static Task<GrainReference> CreateObjectReference(IAddressable o, IGrainMethodInvoker invoker)
{
return Task.FromResult(RuntimeClient.Current.CreateObjectReference(o, invoker));
}
/// <summary>
/// Called from generated code.
/// </summary>
public static Task DeleteObjectReference(IAddressable observer)
{
RuntimeClient.Current.DeleteObjectReference(observer);
return TaskDone.Done;
}
#endregion
/// <summary>
/// Tests this reference for equality to another object.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="obj">The object to test for equality against this reference.</param>
/// <returns><c>true</c> if the object is equal to this reference.</returns>
public override bool Equals(object obj)
{
return Equals(obj as GrainReference);
}
public bool Equals(GrainReference other)
{
if (other == null)
return false;
if (genericArguments != other.genericArguments)
return false;
if (!GrainId.Equals(other.GrainId))
{
return false;
}
if (IsSystemTarget)
{
return Equals(SystemTargetSilo, other.SystemTargetSilo);
}
if (IsObserverReference)
{
return observerId.Equals(other.observerId);
}
return true;
}
/// <summary> Calculates a hash code for a grain reference. </summary>
public override int GetHashCode()
{
int hash = GrainId.GetHashCode();
if (IsSystemTarget)
{
hash = hash ^ SystemTargetSilo.GetHashCode();
}
if (IsObserverReference)
{
hash = hash ^ observerId.GetHashCode();
}
return hash;
}
/// <summary>Get a uniform hash code for this grain reference.</summary>
public uint GetUniformHashCode()
{
// GrainId already includes the hashed type code for generic arguments.
return GrainId.GetUniformHashCode();
}
/// <summary>
/// Compares two references for equality.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="reference1">First grain reference to compare.</param>
/// <param name="reference2">Second grain reference to compare.</param>
/// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns>
public static bool operator ==(GrainReference reference1, GrainReference reference2)
{
if (((object)reference1) == null)
return ((object)reference2) == null;
return reference1.Equals(reference2);
}
/// <summary>
/// Compares two references for inequality.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="reference1">First grain reference to compare.</param>
/// <param name="reference2">Second grain reference to compare.</param>
/// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns>
public static bool operator !=(GrainReference reference1, GrainReference reference2)
{
if (((object)reference1) == null)
return ((object)reference2) != null;
return !reference1.Equals(reference2);
}
#region Protected members
/// <summary>
/// Implemented by generated subclasses to return a constant
/// Implemented in generated code.
/// </summary>
protected virtual int InterfaceId
{
get
{
throw new InvalidOperationException("Should be overridden by subclass");
}
}
/// <summary>
/// Implemented in generated code.
/// </summary>
public virtual bool IsCompatible(int interfaceId)
{
throw new InvalidOperationException("Should be overridden by subclass");
}
/// <summary>
/// Return the name of the interface for this GrainReference.
/// Implemented in Orleans generated code.
/// </summary>
public virtual string InterfaceName
{
get
{
throw new InvalidOperationException("Should be overridden by subclass");
}
}
/// <summary>
/// Return the method name associated with the specified interfaceId and methodId values.
/// </summary>
/// <param name="interfaceId">Interface Id</param>
/// <param name="methodId">Method Id</param>
/// <returns>Method name string.</returns>
protected virtual string GetMethodName(int interfaceId, int methodId)
{
throw new InvalidOperationException("Should be overridden by subclass");
}
/// <summary>
/// Called from generated code.
/// </summary>
protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
{
Task<object> resultTask = InvokeMethodAsync<object>(methodId, arguments, options | InvokeMethodOptions.OneWay);
if (!resultTask.IsCompleted && resultTask.Result != null)
{
throw new OrleansException("Unexpected return value: one way InvokeMethod is expected to return null.");
}
}
/// <summary>
/// Called from generated code.
/// </summary>
protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
{
object[] argsDeepCopy = null;
if (arguments != null)
{
CheckForGrainArguments(arguments);
argsDeepCopy = (object[])SerializationManager.DeepCopy(arguments);
}
var request = new InvokeMethodRequest(this.InterfaceId, methodId, argsDeepCopy);
if (IsUnordered)
options |= InvokeMethodOptions.Unordered;
Task<object> resultTask = InvokeMethod_Impl(request, null, options);
if (resultTask == null)
{
if (typeof(T) == typeof(object))
{
// optimize for most common case when using one way calls.
return PublicOrleansTaskExtensions.CompletedTask as Task<T>;
}
return Task.FromResult(default(T));
}
resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask);
return resultTask.Unbox<T>();
}
#endregion
#region Private members
private Task<object> InvokeMethod_Impl(InvokeMethodRequest request, string debugContext, InvokeMethodOptions options)
{
if (debugContext == null && USE_DEBUG_CONTEXT)
{
debugContext = string.Intern(GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments));
}
// Call any registered client pre-call interceptor function.
CallClientInvokeCallback(request);
bool isOneWayCall = ((options & InvokeMethodOptions.OneWay) != 0);
var resolver = isOneWayCall ? null : new TaskCompletionSource<object>();
RuntimeClient.Current.SendRequest(this, request, resolver, ResponseCallback, debugContext, options, genericArguments);
return isOneWayCall ? null : resolver.Task;
}
private void CallClientInvokeCallback(InvokeMethodRequest request)
{
// Make callback to any registered client callback function, allowing opportunity for an application to set any additional RequestContext info, etc.
// Should we set some kind of callback-in-progress flag to detect and prevent any inappropriate callback loops on this GrainReference?
try
{
Action<InvokeMethodRequest, IGrain> callback = GrainClient.ClientInvokeCallback; // Take copy to avoid potential race conditions
if (callback == null) return;
// Call ClientInvokeCallback only for grain calls, not for system targets.
if (this is IGrain)
{
callback(request, (IGrain) this);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.ProxyClient_ClientInvokeCallback_Error,
"Error while invoking ClientInvokeCallback function " + GrainClient.ClientInvokeCallback,
exc);
throw;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void ResponseCallback(Message message, TaskCompletionSource<object> context)
{
Response response;
if (message.Result != Message.ResponseTypes.Rejection)
{
try
{
response = (Response)message.BodyObject;
}
catch (Exception exc)
{
// catch the Deserialize exception and break the promise with it.
response = Response.ExceptionResponse(exc);
}
}
else
{
Exception rejection;
switch (message.RejectionType)
{
case Message.RejectionTypes.GatewayTooBusy:
rejection = new GatewayTooBusyException();
break;
case Message.RejectionTypes.DuplicateRequest:
return; // Ignore duplicates
default:
rejection = message.BodyObject as OrleansException;
if (rejection == null)
{
if (string.IsNullOrEmpty(message.RejectionInfo))
{
message.RejectionInfo = "Unable to send request - no rejection info available";
}
rejection = new OrleansException(message.RejectionInfo);
}
break;
}
response = Response.ExceptionResponse(rejection);
}
if (!response.ExceptionFlag)
{
context.TrySetResult(response.Data);
}
else
{
context.TrySetException(response.Exception);
}
}
private bool GetUnordered()
{
if (RuntimeClient.Current == null) return false;
return RuntimeClient.Current.GrainTypeResolver != null && RuntimeClient.Current.GrainTypeResolver.IsUnordered(GrainId.GetTypeCode());
}
#endregion
/// <summary>
/// Internal implementation of Cast operation for grain references
/// Called from generated code.
/// </summary>
/// <param name="targetReferenceType">Type that this grain reference should be cast to</param>
/// <param name="grainRefCreatorFunc">Delegate function to create grain references of the target type</param>
/// <param name="grainRef">Grain reference to cast from</param>
/// <param name="interfaceId">Interface id value for the target cast type</param>
/// <returns>GrainReference that is usable as the target type</returns>
/// <exception cref="System.InvalidCastException">if the grain cannot be cast to the target type</exception>
protected internal static IAddressable CastInternal(
Type targetReferenceType,
Func<GrainReference, IAddressable> grainRefCreatorFunc,
IAddressable grainRef,
int interfaceId)
{
if (grainRef == null) throw new ArgumentNullException("grainRef");
Type sourceType = grainRef.GetType();
if (!typeof(IAddressable).IsAssignableFrom(targetReferenceType))
{
throw new InvalidCastException(String.Format("Target type must be derived from Orleans.IAddressable - cannot handle {0}", targetReferenceType));
}
else if (typeof(Grain).IsAssignableFrom(sourceType))
{
Grain grainClassRef = (Grain)grainRef;
GrainReference g = FromGrainId(grainClassRef.Data.Identity);
grainRef = g;
}
else if (!typeof(GrainReference).IsAssignableFrom(sourceType))
{
throw new InvalidCastException(String.Format("Grain reference object must an Orleans.GrainReference - cannot handle {0}", sourceType));
}
if (targetReferenceType.IsAssignableFrom(sourceType))
{
// Already compatible - no conversion or wrapping necessary
return grainRef;
}
// We have an untyped grain reference that may resolve eventually successfully -- need to enclose in an apprroately typed wrapper class
var grainReference = (GrainReference) grainRef;
var grainWrapper = (GrainReference) grainRefCreatorFunc(grainReference);
return grainWrapper;
}
private static String GetDebugContext(string interfaceName, string methodName, object[] arguments)
{
// String concatenation is approx 35% faster than string.Format here
//debugContext = String.Format("{0}:{1}()", this.InterfaceName, GetMethodName(this.InterfaceId, methodId));
var debugContext = new StringBuilder();
debugContext.Append(interfaceName);
debugContext.Append(":");
debugContext.Append(methodName);
if (USE_DEBUG_CONTEXT_PARAMS && arguments != null && arguments.Length > 0)
{
debugContext.Append("(");
debugContext.Append(Utils.EnumerableToString(arguments));
debugContext.Append(")");
}
else
{
debugContext.Append("()");
}
return debugContext.ToString();
}
private static void CheckForGrainArguments(object[] arguments)
{
foreach (var argument in arguments)
if (argument is Grain)
throw new ArgumentException(String.Format("Cannot pass a grain object {0} as an argument to a method. Pass this.AsReference<GrainInterface>() instead.", argument.GetType().FullName));
}
/// <summary> Serializer function for grain reference.</summary>
/// <seealso cref="SerializationManager"/>
[SerializerMethod]
protected internal static void SerializeGrainReference(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (GrainReference)obj;
stream.Write(input.GrainId);
if (input.IsSystemTarget)
{
stream.Write((byte)1);
stream.Write(input.SystemTargetSilo);
}
else
{
stream.Write((byte)0);
}
if (input.IsObserverReference)
{
input.observerId.SerializeToStream(stream);
}
// store as null, serialize as empty.
var genericArg = String.Empty;
if (input.HasGenericArgument)
genericArg = input.genericArguments;
stream.Write(genericArg);
}
/// <summary> Deserializer function for grain reference.</summary>
/// <seealso cref="SerializationManager"/>
[DeserializerMethod]
protected internal static object DeserializeGrainReference(Type t, BinaryTokenStreamReader stream)
{
GrainId id = stream.ReadGrainId();
SiloAddress silo = null;
GuidId observerId = null;
byte siloAddressPresent = stream.ReadByte();
if (siloAddressPresent != 0)
{
silo = stream.ReadSiloAddress();
}
bool expectObserverId = id.IsClient;
if (expectObserverId)
{
observerId = GuidId.DeserializeFromStream(stream);
}
// store as null, serialize as empty.
var genericArg = stream.ReadString();
if (String.IsNullOrEmpty(genericArg))
genericArg = null;
if (expectObserverId)
{
return NewObserverGrainReference(id, observerId);
}
return FromGrainId(id, genericArg, silo);
}
/// <summary> Copier function for grain reference. </summary>
/// <seealso cref="SerializationManager"/>
[CopierMethod]
protected internal static object CopyGrainReference(object original)
{
return (GrainReference)original;
}
private const string GRAIN_REFERENCE_STR = "GrainReference";
private const string SYSTEM_TARGET_STR = "SystemTarget";
private const string OBSERVER_ID_STR = "ObserverId";
private const string GENERIC_ARGUMENTS_STR = "GenericArguments";
/// <summary>Returns a string representation of this reference.</summary>
public override string ToString()
{
if (IsSystemTarget)
{
return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo);
}
if (IsObserverReference)
{
return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId);
}
return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId,
!HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments));
}
internal string ToDetailedString()
{
if (IsSystemTarget)
{
return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo);
}
if (IsObserverReference)
{
return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString());
}
return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(),
!HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments));
}
/// <summary> Get the key value for this grain, as a string. </summary>
public string ToKeyString()
{
if (IsObserverReference)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString());
}
if (IsSystemTarget)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString());
}
if (HasGenericArgument)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments);
}
return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString());
}
public static GrainReference FromKeyString(string key)
{
if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "GrainReference.FromKeyString cannot parse null key");
string trimmed = key.Trim();
string grainIdStr;
int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length;
int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR + "=", StringComparison.Ordinal);
int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR + "=", StringComparison.Ordinal);
int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR + "=", StringComparison.Ordinal);
if (genericIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, genericIndex - grainIdIndex).Trim();
string genericStr = trimmed.Substring(genericIndex + (GENERIC_ARGUMENTS_STR + "=").Length);
if (String.IsNullOrEmpty(genericStr))
{
genericStr = null;
}
return FromGrainId(GrainId.FromParsableString(grainIdStr), genericStr);
}
else if (observerIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, observerIndex - grainIdIndex).Trim();
string observerIdStr = trimmed.Substring(observerIndex + (OBSERVER_ID_STR + "=").Length);
GuidId observerId = GuidId.FromParsableString(observerIdStr);
return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId);
}
else if (systemTargetIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, systemTargetIndex - grainIdIndex).Trim();
string systemTargetStr = trimmed.Substring(systemTargetIndex + (SYSTEM_TARGET_STR + "=").Length);
SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr);
return FromGrainId(GrainId.FromParsableString(grainIdStr), null, siloAddress);
}
else
{
grainIdStr = trimmed.Substring(grainIdIndex);
return FromGrainId(GrainId.FromParsableString(grainIdStr));
}
//return FromGrainId(GrainId.FromParsableString(grainIdStr), generic);
}
#region ISerializable Members
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Use the AddValue method to specify serialized values.
info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string));
if (IsSystemTarget)
{
info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string));
}
if (IsObserverReference)
{
info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string));
}
string genericArg = String.Empty;
if (HasGenericArgument)
genericArg = genericArguments;
info.AddValue("GenericArguments", genericArg, typeof(string));
}
// The special constructor is used to deserialize values.
protected GrainReference(SerializationInfo info, StreamingContext context)
{
// Reset the property value using the GetValue method.
var grainIdStr = info.GetString("GrainId");
GrainId = GrainId.FromParsableString(grainIdStr);
if (IsSystemTarget)
{
var siloAddressStr = info.GetString("SystemTargetSilo");
SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr);
}
if (IsObserverReference)
{
var observerIdStr = info.GetString(OBSERVER_ID_STR);
observerId = GuidId.FromParsableString(observerIdStr);
}
var genericArg = info.GetString("GenericArguments");
if (String.IsNullOrEmpty(genericArg))
genericArg = null;
genericArguments = genericArg;
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSubnetworksClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSubnetworkRequest request = new GetSubnetworkRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
Subnetwork = "subnetworkf55bf572",
};
Subnetwork expectedResponse = new Subnetwork
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Role = "role64e9a729",
CreationTimestamp = "creation_timestamp235e59a1",
PrivateIpv6GoogleAccess = "private_ipv6_google_access0dc5c953",
IpCidrRange = "ip_cidr_range745a04d3",
State = "state2e9ed39e",
SecondaryIpRanges =
{
new SubnetworkSecondaryRange(),
},
Region = "regionedb20d96",
ExternalIpv6Prefix = "external_ipv6_prefix2d3e744d",
EnableFlowLogs = false,
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
Ipv6CidrRange = "ipv6_cidr_range0b2dc35f",
Purpose = "purposebb6b064d",
LogConfig = new SubnetworkLogConfig(),
PrivateIpGoogleAccess = false,
Description = "description2cf9da67",
StackType = "stack_type3a495e39",
SelfLink = "self_link7e87f12d",
GatewayAddress = "gateway_address39dbeaef",
Ipv6AccessType = "ipv6_access_type7faa3985",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Subnetwork response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSubnetworkRequest request = new GetSubnetworkRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
Subnetwork = "subnetworkf55bf572",
};
Subnetwork expectedResponse = new Subnetwork
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Role = "role64e9a729",
CreationTimestamp = "creation_timestamp235e59a1",
PrivateIpv6GoogleAccess = "private_ipv6_google_access0dc5c953",
IpCidrRange = "ip_cidr_range745a04d3",
State = "state2e9ed39e",
SecondaryIpRanges =
{
new SubnetworkSecondaryRange(),
},
Region = "regionedb20d96",
ExternalIpv6Prefix = "external_ipv6_prefix2d3e744d",
EnableFlowLogs = false,
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
Ipv6CidrRange = "ipv6_cidr_range0b2dc35f",
Purpose = "purposebb6b064d",
LogConfig = new SubnetworkLogConfig(),
PrivateIpGoogleAccess = false,
Description = "description2cf9da67",
StackType = "stack_type3a495e39",
SelfLink = "self_link7e87f12d",
GatewayAddress = "gateway_address39dbeaef",
Ipv6AccessType = "ipv6_access_type7faa3985",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subnetwork>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Subnetwork responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subnetwork responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSubnetworkRequest request = new GetSubnetworkRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
Subnetwork = "subnetworkf55bf572",
};
Subnetwork expectedResponse = new Subnetwork
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Role = "role64e9a729",
CreationTimestamp = "creation_timestamp235e59a1",
PrivateIpv6GoogleAccess = "private_ipv6_google_access0dc5c953",
IpCidrRange = "ip_cidr_range745a04d3",
State = "state2e9ed39e",
SecondaryIpRanges =
{
new SubnetworkSecondaryRange(),
},
Region = "regionedb20d96",
ExternalIpv6Prefix = "external_ipv6_prefix2d3e744d",
EnableFlowLogs = false,
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
Ipv6CidrRange = "ipv6_cidr_range0b2dc35f",
Purpose = "purposebb6b064d",
LogConfig = new SubnetworkLogConfig(),
PrivateIpGoogleAccess = false,
Description = "description2cf9da67",
StackType = "stack_type3a495e39",
SelfLink = "self_link7e87f12d",
GatewayAddress = "gateway_address39dbeaef",
Ipv6AccessType = "ipv6_access_type7faa3985",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Subnetwork response = client.Get(request.Project, request.Region, request.Subnetwork);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSubnetworkRequest request = new GetSubnetworkRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
Subnetwork = "subnetworkf55bf572",
};
Subnetwork expectedResponse = new Subnetwork
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Role = "role64e9a729",
CreationTimestamp = "creation_timestamp235e59a1",
PrivateIpv6GoogleAccess = "private_ipv6_google_access0dc5c953",
IpCidrRange = "ip_cidr_range745a04d3",
State = "state2e9ed39e",
SecondaryIpRanges =
{
new SubnetworkSecondaryRange(),
},
Region = "regionedb20d96",
ExternalIpv6Prefix = "external_ipv6_prefix2d3e744d",
EnableFlowLogs = false,
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
Ipv6CidrRange = "ipv6_cidr_range0b2dc35f",
Purpose = "purposebb6b064d",
LogConfig = new SubnetworkLogConfig(),
PrivateIpGoogleAccess = false,
Description = "description2cf9da67",
StackType = "stack_type3a495e39",
SelfLink = "self_link7e87f12d",
GatewayAddress = "gateway_address39dbeaef",
Ipv6AccessType = "ipv6_access_type7faa3985",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subnetwork>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Subnetwork responseCallSettings = await client.GetAsync(request.Project, request.Region, request.Subnetwork, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subnetwork responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.Subnetwork, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicySubnetworkRequest request = new GetIamPolicySubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicySubnetworkRequest request = new GetIamPolicySubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicySubnetworkRequest request = new GetIamPolicySubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request.Project, request.Region, request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicySubnetworkRequest request = new GetIamPolicySubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicySubnetworkRequest request = new SetIamPolicySubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicySubnetworkRequest request = new SetIamPolicySubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicySubnetworkRequest request = new SetIamPolicySubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicySubnetworkRequest request = new SetIamPolicySubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsSubnetworkRequest request = new TestIamPermissionsSubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsSubnetworkRequest request = new TestIamPermissionsSubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsSubnetworkRequest request = new TestIamPermissionsSubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<Subnetworks.SubnetworksClient> mockGrpcClient = new moq::Mock<Subnetworks.SubnetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsSubnetworkRequest request = new TestIamPermissionsSubnetworkRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubnetworksClient client = new SubnetworksClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.AspNet.Identity
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Services.Query;
using Microsoft.AspNet.Identity;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Adxstudio.Xrm.Cms.SolutionVersions;
internal static class UserConstants
{
public static readonly Relationship ContactExternalIdentityRelationship = new Relationship("adx_contact_externalidentity");
public static readonly ColumnSet ExternalIdentityAttributes = new ColumnSet("adx_username", "adx_identityprovidername");
public static readonly EntityNodeColumn[] ContactAttributes =
{
new EntityNodeColumn("adx_identity_logonenabled", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_username", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_passwordhash", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_securitystamp", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_twofactorenabled", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_accessfailedcount", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_lockoutenabled", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_lockoutenddate", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_emailaddress1confirmed", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_identity_mobilephoneconfirmed", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("emailaddress1", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("mobilephone", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_profilealert", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_profilemodifiedon", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("firstname", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("lastname", BaseSolutionVersions.NaosAndOlderVersions),
new EntityNodeColumn("adx_preferredlanguageid", BaseSolutionVersions.CentaurusVersion),
};
}
public class CrmUserStore<TUser, TKey>
: CrmEntityStore<TUser, TKey>,
IUserPasswordStore<TUser, TKey>,
IUserEmailStore<TUser, TKey>,
IUserPhoneNumberStore<TUser, TKey>,
IUserSecurityStampStore<TUser, TKey>,
IUserTwoFactorStore<TUser, TKey>,
IUserLockoutStore<TUser, TKey>,
IUserLoginStore<TUser, TKey>
where TUser : CrmUser<TKey>, new()
where TKey : IEquatable<TKey>
{
public CrmUserStore(CrmDbContext context, CrmEntityStoreSettings settings)
: base("contact", "contactid", "adx_identity_username", context, settings)
{
}
protected override RetrieveRequest ToRetrieveRequest(EntityReference id)
{
// build the related entity queries
var externalIdentityFetch = new Fetch
{
Entity = new FetchEntity("adx_externalidentity", UserConstants.ExternalIdentityAttributes.Columns)
{
Filters = new[] { new Filter {
Conditions = GetActiveStateConditions().ToArray()
} }
}
};
var relatedEntitiesQuery = new RelationshipQueryCollection
{
{ UserConstants.ContactExternalIdentityRelationship, externalIdentityFetch.ToFetchExpression() },
};
// retrieve the contact by ID including its related entities
var request = new RetrieveRequest
{
Target = id,
ColumnSet = new ColumnSet(this.GetContactAttributes().ToArray()),
RelatedEntitiesQuery = relatedEntitiesQuery
};
return request;
}
protected override IEnumerable<OrganizationRequest> ToDeleteRequests(TUser model)
{
if (Settings.DeleteByStatusCode)
{
var entity = new Entity(LogicalName) { Id = ToGuid(model.Id) };
entity.SetAttributeValue("adx_identity_logonenabled", false);
yield return new UpdateRequest { Target = entity };
}
foreach (var request in base.ToDeleteRequests(model))
{
yield return request;
}
}
protected virtual IEnumerable<string> GetContactAttributes()
{
return UserConstants.ContactAttributes.ToFilteredColumns(this.BaseSolutionCrmVersion);
}
#region IUserPasswordStore
async Task IUserStore<TUser, TKey>.CreateAsync(TUser user)
{
user.LogonEnabled = true;
user.Id = await CreateAsync(user).WithCurrentCulture();
}
public virtual Task SetPasswordHashAsync(TUser user, string passwordHash)
{
ThrowIfDisposed();
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
public virtual Task<string> GetPasswordHashAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.PasswordHash);
}
public virtual Task<bool> HasPasswordAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(!string.IsNullOrWhiteSpace(user.PasswordHash));
}
#endregion
#region IUserEmailStore
public virtual Task SetEmailAsync(TUser user, string email)
{
ThrowIfDisposed();
user.Email = email;
return Task.FromResult(0);
}
public virtual Task<string> GetEmailAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.Email);
}
public virtual Task<bool> GetEmailConfirmedAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.EmailConfirmed);
}
public virtual Task SetEmailConfirmedAsync(TUser user, bool confirmed)
{
ThrowIfDisposed();
user.EmailConfirmed = confirmed;
return Task.FromResult(0);
}
public virtual Task<TUser> FindByEmailAsync(string email)
{
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(email)) throw new ArgumentException("The email {0} isn't valid.");
return FindByConditionAsync(new Condition("emailaddress1", ConditionOperator.Equal, email));
}
#endregion
#region IUserPhoneNumberStore
public virtual Task<string> GetPhoneNumberAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.PhoneNumber);
}
public virtual Task<bool> GetPhoneNumberConfirmedAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.PhoneNumberConfirmed);
}
public virtual Task SetPhoneNumberAsync(TUser user, string phoneNumber)
{
ThrowIfDisposed();
user.PhoneNumber = phoneNumber;
return Task.FromResult(0);
}
public virtual Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed)
{
ThrowIfDisposed();
user.PhoneNumberConfirmed = confirmed;
return Task.FromResult(0);
}
#endregion
#region IUserSecurityStampStore
public virtual Task<string> GetSecurityStampAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.SecurityStamp);
}
public virtual Task SetSecurityStampAsync(TUser user, string stamp)
{
ThrowIfDisposed();
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
#endregion
#region IUserTwoFactorStore
public virtual Task<bool> GetTwoFactorEnabledAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.TwoFactorEnabled);
}
public virtual Task SetTwoFactorEnabledAsync(TUser user, bool enabled)
{
ThrowIfDisposed();
user.TwoFactorEnabled = enabled;
return Task.FromResult(0);
}
#endregion
#region IUserLockoutStore
public virtual Task<int> GetAccessFailedCountAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.AccessFailedCount);
}
public virtual Task<bool> GetLockoutEnabledAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.LockoutEnabled);
}
public virtual Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user)
{
ThrowIfDisposed();
return Task.FromResult(user.LockoutEndDateUtc != null
? new DateTimeOffset(DateTime.SpecifyKind(user.LockoutEndDateUtc.Value, DateTimeKind.Utc))
: new DateTimeOffset());
}
public virtual Task<int> IncrementAccessFailedCountAsync(TUser user)
{
ThrowIfDisposed();
++user.AccessFailedCount;
return Task.FromResult(user.AccessFailedCount);
}
public virtual Task ResetAccessFailedCountAsync(TUser user)
{
ThrowIfDisposed();
user.AccessFailedCount = 0;
return Task.FromResult(0);
}
public virtual Task SetLockoutEnabledAsync(TUser user, bool enabled)
{
ThrowIfDisposed();
user.LockoutEnabled = enabled;
return Task.FromResult(0);
}
public virtual Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd)
{
ThrowIfDisposed();
user.LockoutEndDateUtc = lockoutEnd == DateTimeOffset.MinValue
? new DateTime?()
: lockoutEnd.UtcDateTime;
return Task.FromResult(0);
}
#endregion
#region IUserLoginStore
public virtual Task AddLoginAsync(TUser user, UserLoginInfo login)
{
ThrowIfDisposed();
user.AddLogin(login);
return Task.FromResult(0);
}
public virtual async Task<TUser> FindAsync(UserLoginInfo login)
{
ThrowIfDisposed();
if (login == null) throw new ArgumentNullException("login");
if (string.IsNullOrWhiteSpace(login.LoginProvider)) throw new ArgumentException("Invalid LoginProvider.");
if (string.IsNullOrWhiteSpace(login.ProviderKey)) throw new ArgumentException("Invalid ProviderKey.");
var entity = await FetchByConditionOnExternalIdentityAsync(
new Condition("adx_identityprovidername", ConditionOperator.Equal, login.LoginProvider),
new Condition("adx_username", ConditionOperator.Equal, login.ProviderKey)).WithCurrentCulture();
return ToModel(entity);
}
public virtual Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (ToGuid(user.Id) == Guid.Empty) throw new ArgumentException("Invalid user ID.");
return Task.FromResult<IList<UserLoginInfo>>(user.Logins.Select(ToUserLoginInfo).ToList());
}
public virtual Task RemoveLoginAsync(TUser user, UserLoginInfo login)
{
ThrowIfDisposed();
user.RemoveLogin(login);
return Task.FromResult(0);
}
private static UserLoginInfo ToUserLoginInfo(CrmUserLogin login)
{
return new UserLoginInfo(login.LoginProvider, login.ProviderKey);
}
protected virtual Task<Entity> FetchByConditionOnExternalIdentityAsync(params Condition[] conditions)
{
// fetch the contact by a custom condition on the external identity
var fetch = new Fetch
{
Entity = new FetchEntity(LogicalName)
{
Attributes = FetchAttribute.None,
Filters = new[] { new Filter {
Conditions = GetActiveEntityConditions().ToArray()
} },
Links = new[]
{
new Link { Name = "adx_externalidentity", FromAttribute = "adx_contactid", Filters = new[] {
new Filter {
Conditions = GetActiveStateConditions().Concat(conditions).ToArray()
}
} }
}
}
};
return FetchAsync(fetch);
}
#endregion
}
}
| |
using System;
using System.Reflection;
using NUnit.Framework;
using Shouldly;
using StructureMap.Graph;
using StructureMap.Testing.GenericWidgets;
using StructureMap.TypeRules;
namespace StructureMap.Testing
{
[TestFixture]
public class GenericsAcceptanceTester
{
public interface IService<T>
{
}
public interface IHelper<T>
{
}
public class Service<T> : IService<T>
{
private readonly IHelper<T> _helper;
public Service(IHelper<T> helper)
{
_helper = helper;
}
public IHelper<T> Helper
{
get { return _helper; }
}
}
public class Service2<T> : IService<T>
{
public Type GetT()
{
return typeof (T);
}
}
public class ServiceWithPlug<T> : IService<T>
{
private readonly IPlug<T> _plug;
public ServiceWithPlug(IPlug<T> plug)
{
_plug = plug;
}
public IPlug<T> Plug
{
get { return _plug; }
}
}
public class Helper<T> : IHelper<T>
{
}
[Test]
public void CanBuildAGenericObjectThatHasAnotherGenericObjectAsAChild()
{
var container = new Container(x =>
{
x.For(typeof (IService<>)).Use(typeof (Service<>));
x.For(typeof (IHelper<>)).Use(typeof (Helper<>));
});
container.GetInstance<IService<string>>()
.ShouldBeOfType<Service<string>>()
.Helper.ShouldBeOfType<Helper<string>>();
}
[Test]
public void CanCreatePluginFamilyForGenericTypeWithGenericParameter()
{
var family = new PluginFamily(typeof (IGenericService<int>));
}
[Test]
public void CanCreatePluginFamilyForGenericTypeWithoutGenericParameter()
{
var family = new PluginFamily(typeof (IGenericService<>));
}
[Test]
public void CanGetPluginFamilyFromPluginGraphWithNoParameters()
{
var builder = new PluginGraphBuilder();
var scanner = new AssemblyScanner();
scanner.Assembly(GetType().Assembly);
builder.AddScanner(scanner);
var graph = builder.Build();
graph.Families[typeof (IGenericService<int>)].ShouldBeTheSameAs(
graph.Families[typeof (IGenericService<int>)]);
graph.Families[typeof (IGenericService<string>)].ShouldBeTheSameAs(
graph.Families[typeof (IGenericService<string>)]);
graph.Families[typeof (IGenericService<>)].ShouldBeTheSameAs(
graph.Families[typeof (IGenericService<>)]);
}
[Test]
public void CanGetTheSameInstanceOfGenericInterfaceWithSingletonLifecycle()
{
var con = new Container(x =>
{
x.ForSingletonOf(typeof (IService<>)).Use(typeof (Service<>));
x.For(typeof (IHelper<>)).Use(typeof (Helper<>));
});
var first = con.GetInstance<IService<string>>();
var second = con.GetInstance<IService<string>>();
first.ShouldBeTheSameAs(second);
}
[Test]
public void CanPlugGenericConcreteClassIntoGenericInterfaceWithNoGenericParametersSpecified()
{
var canPlug = typeof (GenericService<>).CanBeCastTo(typeof (IGenericService<>));
canPlug.ShouldBeTrue();
}
[Test]
public void CanPlugConcreteNonGenericClassIntoGenericInterface()
{
typeof (NotSoGenericService).CanBeCastTo(typeof (IGenericService<>))
.ShouldBeTrue();
}
[Test]
public void Define_profile_with_generics_and_concrete_type()
{
var container = new Container(registry =>
{
registry.For(typeof (IHelper<>)).Use(typeof (Helper<>));
registry.Profile("1", x => x.For(typeof (IService<>)).Use(typeof (Service<>)));
registry.Profile("2", x => x.For(typeof (IService<>)).Use(typeof (Service2<>)));
});
container.GetProfile("1").GetInstance<IService<string>>().ShouldBeOfType<Service<string>>();
container.GetProfile("2").GetInstance<IService<string>>().ShouldBeOfType<Service2<string>>();
}
[Test]
public void Define_profile_with_generics_with_named_instance()
{
IContainer container = new Container(r =>
{
r.For(typeof (IService<>)).Add(typeof (Service<>)).Named("Service1");
r.For(typeof (IService<>)).Add(typeof (Service2<>)).Named("Service2");
r.For(typeof (IHelper<>)).Use(typeof (Helper<>));
r.Profile("1", x => x.For(typeof (IService<>)).Use("Service1"));
r.Profile("2", x => x.For(typeof (IService<>)).Use("Service2"));
});
container.GetProfile("1").GetInstance<IService<string>>().ShouldBeOfType<Service<string>>();
container.GetProfile("2").GetInstance<IService<int>>().ShouldBeOfType<Service2<int>>();
}
[Test]
public void GenericsTypeAndProfileOrMachine()
{
var container = new Container(registry =>
{
registry.For(typeof (IHelper<>)).Use(typeof (Helper<>));
registry.For(typeof (IService<>)).Use(typeof (Service<>)).Named("Default");
registry.For(typeof (IService<>)).Add(typeof (ServiceWithPlug<>)).Named("Plugged");
registry.For(typeof (IPlug<>)).Use(typeof (ConcretePlug<>));
registry.Profile("1", x => { x.For(typeof (IService<>)).Use("Default"); });
registry.Profile("2", x => { x.For(typeof (IService<>)).Use("Plugged"); });
});
container.GetProfile("1").GetInstance(typeof (IService<string>)).ShouldBeOfType<Service<string>>();
container.GetProfile("2").GetInstance(typeof (IService<string>))
.ShouldBeOfType<ServiceWithPlug<string>>();
container.GetProfile("1").GetInstance(typeof (IService<string>)).ShouldBeOfType<Service<string>>();
}
[Test]
public void GetGenericTypeByString()
{
var assem = Assembly.GetExecutingAssembly();
var type = assem.GetType("StructureMap.Testing.ITarget`2");
type.GetGenericTypeDefinition()
.ShouldBe(typeof (ITarget<,>));
}
[Test]
public void SmokeTestCanBeCaseWithImplementationOfANonGenericInterface()
{
GenericsPluginGraph.CanBeCast(typeof (ITarget<,>), typeof (DisposableTarget<,>)).ShouldBeTrue();
}
}
public class ComplexType<T>
{
private readonly int _age;
private readonly string _name;
public ComplexType(string name, int age)
{
_name = name;
_age = age;
}
public string Name
{
get { return _name; }
}
public int Age
{
get { return _age; }
}
[ValidationMethod]
public void Validate()
{
throw new ApplicationException("Break!");
}
}
public interface ITarget<T, U>
{
}
public class SpecificTarget<T, U> : ITarget<T, U>
{
}
public class DisposableTarget<T, U> : ITarget<T, U>, IDisposable
{
#region IDisposable Members
public void Dispose()
{
}
#endregion
}
public interface ITarget2<T, U, V>
{
}
public class SpecificTarget2<T, U, V> : ITarget2<T, U, V>
{
}
public interface IGenericService<T>
{
void DoSomething(T thing);
}
public class GenericService<T> : IGenericService<T>
{
#region IGenericService<T> Members
public void DoSomething(T thing)
{
throw new NotImplementedException();
}
#endregion
public Type GetGenericType()
{
return typeof (T);
}
}
public class NotSoGenericService : IGenericService<string>
{
public void DoSomething(string thing)
{
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using CreateThis.VR.UI.Interact;
using MeshEngine.Controller;
/* Some rules to keep in mind:
* 1. Unity3d GameObject.GetInstanceID() is a GUID and is therefore acceptable for comparisons and search operations.
* 2. A VerticesManager.Vertex.instance is NOT required (Face Delete mode and Flip Normal mode, for example), so some other GUID is necessary.
* 3. Each VerticesManager.Vertex.instance has only ONE VerticesManager.Vertex (1:1 relationship).
* 4. VerticesManager.Vertex.position is NOT unique.
*/
namespace MeshEngine {
public class Vertices {
public List<Vertex> vertices { get; private set; }
public Mesh mesh;
public bool hideVertices;
public bool verticesChanged;
private bool vertexInstancesCreated;
private List<GameObject> vertexInstancesPool;
private bool vertexInstancesSelectable;
private Dictionary<System.Guid, int> vertexIndex;
private Dictionary<int, int> vertexInstanceIndex;
public void DeactivateAndMoveToPool(GameObject vertexGameObject) {
vertexGameObject.SetActive(false);
vertexGameObject.transform.parent = null;
vertexInstancesPool.Add(vertexGameObject);
}
public GameObject InstantiateOrGetFromPool(Vector3 position, Quaternion rotation) {
if (vertexInstancesPool.Count > 0) {
int index = vertexInstancesPool.Count - 1;
GameObject vertexGameObject = vertexInstancesPool[index];
vertexInstancesPool.RemoveAt(index);
vertexGameObject.SetActive(true);
vertexGameObject.transform.position = position;
vertexGameObject.transform.rotation = rotation;
return vertexGameObject;
} else {
return GameObject.Instantiate(mesh.vertexPrefab, position, rotation);
}
}
public Vertices(Mesh mesh) {
this.mesh = mesh;
vertices = new List<Vertex>();
vertexInstancesCreated = false;
vertexInstancesPool = new List<GameObject>();
verticesChanged = false;
vertexIndex = new Dictionary<System.Guid, int>();
vertexInstanceIndex = new Dictionary<int, int>();
}
public string VerticesToString(Vector3[] vertices = null) {
List<string> result = new List<string>();
foreach (Vector3 vertex in vertices) {
result.Add(vertex.ToString());
}
return string.Join(",", result.ToArray());
}
public List<Vector3> GetVertexPositionsOfUnfinishedTriangles() {
int remainder = mesh.triangles.triangles.Count % 3;
//Debug.Log("GetVertexPositionsOfUnfinishedTriangles remainder=" + remainder + ",instance.newTriangles.Count=" + meshController.trianglesManager.triangles.Count);
if (remainder == 0) return new List<Vector3>();
List<int> triangleIndices = mesh.triangles.triangles.GetRange(mesh.triangles.triangles.Count - remainder, remainder);
List<Vector3> vertexPositions = new List<Vector3>();
foreach (int index in triangleIndices) {
vertexPositions.Add(vertices[index].position);
}
//Debug.Log("GetVertexPositionsOfUnfinishedTriangles remainder=" + remainder + ",triangleIndices.Count=" + triangleIndices.Count + ",vertexPositions.Count=" + vertexPositions.Count);
return vertexPositions;
}
public List<Vertex> ListVertexOfVector3Array(List<Vector3> positions, List<Vector2> uvs) {
List<Vertex> myVertices = new List<Vertex>();
for (int i = 0; i < positions.Count; i++) {
Vector3 position = positions[i];
Vertex vertex = new Vertex();
vertex.position = position;
if (i < uvs.Count) {
vertex.uv = uvs[i];
}
myVertices.Add(vertex);
}
return myVertices;
}
public GameObject CreateAndAddVertexInstanceByWorldPosition(Vector3 worldPosition) {
Vector3 localPosition = mesh.transform.InverseTransformPoint(worldPosition);
GameObject vertexInstance = CreateVertexInstanceByLocalPosition(localPosition);
AddVertexWithInstance(localPosition, vertexInstance);
return vertexInstance;
}
public GameObject CreateVertexInstanceByLocalPosition(Vector3 localPosition) {
Vector3 position = mesh.transform.TransformPoint(localPosition);
//Debug.Log("MeshController#CreateVertices localPosition="+localPosition+",position=" + position+",this.transform.position=" + this.transform.position);
GameObject vertexInstance = InstantiateOrGetFromPool(position, mesh.transform.rotation);
vertexInstance.transform.parent = mesh.transform;
vertexInstance.GetComponent<Selectable>().Initialize();
if (hideVertices) vertexInstance.SetActive(false);
VertexController vertexController = vertexInstance.GetComponent<VertexController>();
vertexController.SetSelectable(vertexInstancesSelectable);
vertexController.SetStickySelected(false);
vertexController.CreateFromLocalPosition(localPosition, mesh, false);
return vertexInstance;
}
public void CreateVertexInstances(bool selectUnfinishedTriangles = true) {
if (vertexInstancesCreated) return;
vertexInstanceIndex.Clear();
List<Vector3> positions = GetVertexPositionsOfUnfinishedTriangles();
for (int i = 0; i < vertices.Count; i++) {
Vector3 localPosition = vertices[i].position;
vertices[i].instance = CreateVertexInstanceByLocalPosition(localPosition);
vertexInstanceIndex.Add(vertices[i].instance.GetInstanceID(), i);
if (selectUnfinishedTriangles && positions.Contains(localPosition)) {
mesh.selection.SelectVertex(vertices[i].instance);
}
}
vertexInstancesCreated = true;
}
public void Clear() {
DeleteVertexInstances();
vertices.Clear();
vertexIndex.Clear();
vertexInstanceIndex.Clear();
verticesChanged = true;
mesh.persistence.changedSinceLastSave = true;
}
public void DeleteVertexInstances() {
GameObject[] vertices = GameObject.FindGameObjectsWithTag("Vertex");
foreach (GameObject vertex in vertices) {
DeactivateAndMoveToPool(vertex);
}
mesh.selection.ClearSelectedVertices();
vertexInstancesCreated = false;
}
public Vector3[] Vector3ArrayOfVertices(List<Vertex> myVertices) {
return myVertices.Select(x => x.position).ToArray();
}
public Vector3[] GetVerticesArray() {
return Vector3ArrayOfVertices(vertices);
}
private void BuildMeshVerticesAndUVs() {
Vector3[] meshVertices = new Vector3[vertices.Count];
Vector2[] meshUVs = new Vector2[vertices.Count];
for (int i = 0; i < vertices.Count; i++) {
meshVertices[i] = vertices[i].position;
meshUVs[i] = vertices[i].uv;
}
mesh.uMesh.vertices = meshVertices;
mesh.uMesh.uv = meshUVs;
}
public bool BuildVertices(bool rebuildWireframe = true) {
if (!verticesChanged) return false;
mesh.uMesh.Clear();
BuildMeshVerticesAndUVs();
mesh.triangles.trianglesChanged = true;
verticesChanged = false;
return true;
}
public int AddVertexWithInstance(Vector3 position, GameObject vertexInstance, bool buildVertices = true) {
Vertex vertex = new Vertex();
vertex.position = position;
vertex.instance = vertexInstance;
vertices.Add(vertex);
vertexIndex.Add(vertex.ID, vertices.Count - 1);
vertexInstanceIndex.Add(vertex.instance.GetInstanceID(), vertices.Count - 1);
int index = vertices.Count - 1;
verticesChanged = true;
mesh.persistence.changedSinceLastSave = true;
return index;
}
public int IndexOfInstance(GameObject vertexInstance) {
if (vertexInstanceIndex.ContainsKey(vertexInstance.GetInstanceID())) return vertexInstanceIndex[vertexInstance.GetInstanceID()];
return -1;
}
public Vertex VertexOfInstance(GameObject vertexInstance) {
int index = IndexOfInstance(vertexInstance);
if (index == -1) {
Debug.Log("VertexOfInstance index=-1, vertexInstance.GetInstanceID()=" + vertexInstance.GetInstanceID());
return null;
}
return vertices[index];
}
public bool SameVertex(Vertex a, Vertex b) {
if (a.ID == b.ID) return true;
return false;
}
public int IndexOfVertex(Vertex vertex) {
if (vertexIndex.ContainsKey(vertex.ID)) return vertexIndex[vertex.ID];
return -1;
}
public void ReplaceVertex(GameObject vertexInstance, Vector3 newPosition) {
int index = IndexOfInstance(vertexInstance);
if (index == -1) Debug.Log("ReplaceVertex index=-1, vertexInstance.GetInstanceID()=" + vertexInstance.GetInstanceID() + ", newPosition=" + newPosition);
Vertex vertex = vertices[index];
ReplaceVertexPositionAt(index, newPosition);
vertex.CallOnUpdateVertex();
}
public void ReplaceVertexPositionAt(int index, Vector3 position) {
//Debug.Log("MeshController: Replaced vertex[" + index + "]=" + vertex + " instance.mesh.vertices=" + instance.VerticesToString());
Vertex vertex = vertices[index];
vertices[index].position = position;
verticesChanged = true;
mesh.persistence.changedSinceLastSave = true;
//meshController.wireframe.UpdateVertex(vertex, position);
}
public void TruncateToCount(int count) {
for (int i = vertices.Count - 1; i >= count; i--) {
vertexIndex.Remove(vertices[i].ID);
vertexInstanceIndex.Remove(vertices[i].instance.GetInstanceID());
vertices.RemoveAt(i);
}
verticesChanged = true;
mesh.persistence.changedSinceLastSave = true;
}
public void SetVertices(List<Vertex> myVertices) {
vertices = myVertices;
RebuildVertexIndex();
}
public void RebuildVertexIndex() {
vertexIndex.Clear();
vertexInstanceIndex.Clear();
for (int i = 0; i < vertices.Count; i++) {
Vertex vertex = vertices[i];
vertexIndex.Add(vertex.ID, i);
if (vertex.instance) {
vertexInstanceIndex.Add(vertex.instance.GetInstanceID(), i);
}
}
}
public void RemoveVertex(Vertex vertex) {
int index = IndexOfVertex(vertex);
//Debug.Log("MeshController: Remove index=" + index + ",ID=" + vertex.instance.GetInstanceID());
if (index != -1) {
mesh.triangles.RemoveTrianglesWithVertexIndex(index);
mesh.selection.RemoveVertexByIndex(index);
mesh.selection.RemovedVerticesManagerVertexAtIndex(index);
}
vertices.Remove(vertex);
RebuildVertexIndex();
verticesChanged = true;
mesh.persistence.changedSinceLastSave = true;
}
public void RemoveByVertexInstance(GameObject vertexInstance) {
//Debug.Log("RemoveByVertexInstance ID="+vertexInstance.GetInstanceID());
RemoveVertex(VertexOfInstance(vertexInstance));
}
public void MergeFirstVertexToSecond(Vertex first, Vertex second) {
mesh.triangles.MoveAllTrianglesFromFirstToSecondVertex(first, second);
RemoveVertex(first);
if (first.instance != null) DeactivateAndMoveToPool(first.instance);
mesh.triangles.DeleteTriangleInstances();
mesh.triangles.CreateTriangleInstances();
}
public void MergeSelected() {
List<SelectedVertex> selectedVertices = mesh.selection.selectedVertices;
if (selectedVertices.Count != 2) return;
MergeFirstVertexToSecond(selectedVertices[0].vertex, selectedVertices[1].vertex);
mesh.selection.Clear();
}
public void UpdateAllVertexInstancesSelectable() {
foreach (Vertex vertex in vertices) {
GameObject vertexInstance = vertex.instance;
VertexController vertexController = vertexInstance.GetComponent<VertexController>();
vertexController.SetSelectable(vertexInstancesSelectable);
}
}
public void SetVertexInstancesSelectable(bool value) {
if (vertexInstancesSelectable == value) return;
vertexInstancesSelectable = value;
UpdateAllVertexInstancesSelectable();
}
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects
{
public unsafe class FileDialog : SimObject
{
public FileDialog()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.FileDialogCreateInstance());
}
public FileDialog(uint pId) : base(pId)
{
}
public FileDialog(string pName) : base(pName)
{
}
public FileDialog(IntPtr pObjPtr) : base(pObjPtr)
{
}
public FileDialog(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public FileDialog(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _FileDialogGetDefaultPath(IntPtr fileDialog);
private static _FileDialogGetDefaultPath _FileDialogGetDefaultPathFunc;
internal static IntPtr FileDialogGetDefaultPath(IntPtr fileDialog)
{
if (_FileDialogGetDefaultPathFunc == null)
{
_FileDialogGetDefaultPathFunc =
(_FileDialogGetDefaultPath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogGetDefaultPath"), typeof(_FileDialogGetDefaultPath));
}
return _FileDialogGetDefaultPathFunc(fileDialog);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _FileDialogSetDefaultPath(IntPtr fileDialog, string value);
private static _FileDialogSetDefaultPath _FileDialogSetDefaultPathFunc;
internal static void FileDialogSetDefaultPath(IntPtr fileDialog, string value)
{
if (_FileDialogSetDefaultPathFunc == null)
{
_FileDialogSetDefaultPathFunc =
(_FileDialogSetDefaultPath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogSetDefaultPath"), typeof(_FileDialogSetDefaultPath));
}
_FileDialogSetDefaultPathFunc(fileDialog, value);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _FileDialogGetDefaultFile(IntPtr fileDialog);
private static _FileDialogGetDefaultFile _FileDialogGetDefaultFileFunc;
internal static IntPtr FileDialogGetDefaultFile(IntPtr fileDialog)
{
if (_FileDialogGetDefaultFileFunc == null)
{
_FileDialogGetDefaultFileFunc =
(_FileDialogGetDefaultFile)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogGetDefaultFile"), typeof(_FileDialogGetDefaultFile));
}
return _FileDialogGetDefaultFileFunc(fileDialog);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _FileDialogSetDefaultFile(IntPtr fileDialog, string value);
private static _FileDialogSetDefaultFile _FileDialogSetDefaultFileFunc;
internal static void FileDialogSetDefaultFile(IntPtr fileDialog, string value)
{
if (_FileDialogSetDefaultFileFunc == null)
{
_FileDialogSetDefaultFileFunc =
(_FileDialogSetDefaultFile)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogSetDefaultFile"), typeof(_FileDialogSetDefaultFile));
}
_FileDialogSetDefaultFileFunc(fileDialog, value);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _FileDialogGetFileName(IntPtr fileDialog);
private static _FileDialogGetFileName _FileDialogGetFileNameFunc;
internal static IntPtr FileDialogGetFileName(IntPtr fileDialog)
{
if (_FileDialogGetFileNameFunc == null)
{
_FileDialogGetFileNameFunc =
(_FileDialogGetFileName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogGetFileName"), typeof(_FileDialogGetFileName));
}
return _FileDialogGetFileNameFunc(fileDialog);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _FileDialogSetFileName(IntPtr fileDialog, string value);
private static _FileDialogSetFileName _FileDialogSetFileNameFunc;
internal static void FileDialogSetFileName(IntPtr fileDialog, string value)
{
if (_FileDialogSetFileNameFunc == null)
{
_FileDialogSetFileNameFunc =
(_FileDialogSetFileName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogSetFileName"), typeof(_FileDialogSetFileName));
}
_FileDialogSetFileNameFunc(fileDialog, value);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _FileDialogGetFilters(IntPtr fileDialog);
private static _FileDialogGetFilters _FileDialogGetFiltersFunc;
internal static IntPtr FileDialogGetFilters(IntPtr fileDialog)
{
if (_FileDialogGetFiltersFunc == null)
{
_FileDialogGetFiltersFunc =
(_FileDialogGetFilters)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogGetFilters"), typeof(_FileDialogGetFilters));
}
return _FileDialogGetFiltersFunc(fileDialog);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _FileDialogSetFilters(IntPtr fileDialog, string value);
private static _FileDialogSetFilters _FileDialogSetFiltersFunc;
internal static void FileDialogSetFilters(IntPtr fileDialog, string value)
{
if (_FileDialogSetFiltersFunc == null)
{
_FileDialogSetFiltersFunc =
(_FileDialogSetFilters)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogSetFilters"), typeof(_FileDialogSetFilters));
}
_FileDialogSetFiltersFunc(fileDialog, value);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _FileDialogGetTitle(IntPtr fileDialog);
private static _FileDialogGetTitle _FileDialogGetTitleFunc;
internal static IntPtr FileDialogGetTitle(IntPtr fileDialog)
{
if (_FileDialogGetTitleFunc == null)
{
_FileDialogGetTitleFunc =
(_FileDialogGetTitle)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogGetTitle"), typeof(_FileDialogGetTitle));
}
return _FileDialogGetTitleFunc(fileDialog);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _FileDialogSetTitle(IntPtr fileDialog, string value);
private static _FileDialogSetTitle _FileDialogSetTitleFunc;
internal static void FileDialogSetTitle(IntPtr fileDialog, string value)
{
if (_FileDialogSetTitleFunc == null)
{
_FileDialogSetTitleFunc =
(_FileDialogSetTitle)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogSetTitle"), typeof(_FileDialogSetTitle));
}
_FileDialogSetTitleFunc(fileDialog, value);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _FileDialogGetChangePath(IntPtr fileDialog);
private static _FileDialogGetChangePath _FileDialogGetChangePathFunc;
internal static bool FileDialogGetChangePath(IntPtr fileDialog)
{
if (_FileDialogGetChangePathFunc == null)
{
_FileDialogGetChangePathFunc =
(_FileDialogGetChangePath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogGetChangePath"), typeof(_FileDialogGetChangePath));
}
return _FileDialogGetChangePathFunc(fileDialog);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _FileDialogSetChangePath(IntPtr fileDialog, bool value);
private static _FileDialogSetChangePath _FileDialogSetChangePathFunc;
internal static void FileDialogSetChangePath(IntPtr fileDialog, bool value)
{
if (_FileDialogSetChangePathFunc == null)
{
_FileDialogSetChangePathFunc =
(_FileDialogSetChangePath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogSetChangePath"), typeof(_FileDialogSetChangePath));
}
_FileDialogSetChangePathFunc(fileDialog, value);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _FileDialogCreateInstance();
private static _FileDialogCreateInstance _FileDialogCreateInstanceFunc;
internal static IntPtr FileDialogCreateInstance()
{
if (_FileDialogCreateInstanceFunc == null)
{
_FileDialogCreateInstanceFunc =
(_FileDialogCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogCreateInstance"), typeof(_FileDialogCreateInstance));
}
return _FileDialogCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _FileDialogExecute(IntPtr fileDialog);
private static _FileDialogExecute _FileDialogExecuteFunc;
internal static bool FileDialogExecute(IntPtr fileDialog)
{
if (_FileDialogExecuteFunc == null)
{
_FileDialogExecuteFunc =
(_FileDialogExecute)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"FileDialogExecute"), typeof(_FileDialogExecute));
}
return _FileDialogExecuteFunc(fileDialog);
}
}
#endregion
#region Properties
public string DefaultPath
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.FileDialogGetDefaultPath(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.FileDialogSetDefaultPath(ObjectPtr->ObjPtr, value);
}
}
public string DefaultFile
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.FileDialogGetDefaultFile(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.FileDialogSetDefaultFile(ObjectPtr->ObjPtr, value);
}
}
public string FileName
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.FileDialogGetFileName(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.FileDialogSetFileName(ObjectPtr->ObjPtr, value);
}
}
public string Filters
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.FileDialogGetFilters(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.FileDialogSetFilters(ObjectPtr->ObjPtr, value);
}
}
public string Title
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.FileDialogGetTitle(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.FileDialogSetTitle(ObjectPtr->ObjPtr, value);
}
}
public bool ChangePath
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.FileDialogGetChangePath(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.FileDialogSetChangePath(ObjectPtr->ObjPtr, value);
}
}
#endregion
#region Methods
public bool Execute()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.FileDialogExecute(ObjectPtr->ObjPtr);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using IL2CPU.Debug.Symbols;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
//using Dapper;
//using SQLinq.Dapper;
//using SQLinq;
using FIELD_INFO = IL2CPU.Debug.Symbols.FIELD_INFO;
namespace Cosmos.VS.DebugEngine.AD7.Impl
{
// An implementation of IDebugProperty2
// This interface represents a stack frame property, a program document property, or some other property.
// The property is usually the result of an expression evaluation.
//
// The sample engine only supports locals and parameters for functions that have symbols loaded.
class AD7Property : IDebugProperty2
{
private DebugLocalInfo m_variableInformation;
private AD7Process mProcess;
private AD7StackFrame mStackFrame;
private LOCAL_ARGUMENT_INFO mDebugInfo;
const uint mArrayLengthOffset = 8;
const uint mArrayFirstElementOffset = 16;
private const string NULL = "null";
protected Int32 OFFSET
{
get
{
return mDebugInfo.OFFSET;
}
}
public AD7Property(DebugLocalInfo localInfo, AD7Process process, AD7StackFrame stackFrame)
{
m_variableInformation = localInfo;
mProcess = process;
mStackFrame = stackFrame;
if (localInfo.IsLocal)
{
mDebugInfo = mStackFrame.mLocalInfos[m_variableInformation.Index];
}
else if (localInfo.IsReference)
{
mDebugInfo = new LOCAL_ARGUMENT_INFO()
{
TYPENAME = localInfo.Type,
NAME = localInfo.Name,
OFFSET = localInfo.Offset
};
}
else
{
mDebugInfo = mStackFrame.mArgumentInfos[m_variableInformation.Index];
}
}
public void ReadData<T>(ref DEBUG_PROPERTY_INFO propertyInfo, Func<byte[], int, T> ByteToTypeAction)
{
byte[] xData;
if (m_variableInformation.IsReference)
{
xData = mProcess.mDbgConnector.GetMemoryData(m_variableInformation.Pointer, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)));
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
return;
}
var xTypedIntValue = ByteToTypeAction(xData, 0);
propertyInfo.bstrValue = String.Format("{0}", xTypedIntValue);
}
else
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)));
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
return;
}
var xTypedIntValue = ByteToTypeAction(xData, 0);
propertyInfo.bstrValue = String.Format("{0}", xTypedIntValue);
}
}
public void ReadDataArray<T>(ref DEBUG_PROPERTY_INFO propertyInfo, string typeAsString)
{
byte[] xData;
// Get handle
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
// Get actual pointer
xData = mProcess.mDbgConnector.GetMemoryData(BitConverter.ToUInt32(xData, 0), 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xPointer = BitConverter.ToUInt32(xData, 0);
if (xPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xPointer + mArrayLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xDataLength = BitConverter.ToUInt32(xData, 0);
bool xIsTooLong = xDataLength > 512;
if (xIsTooLong)
{
xDataLength = 512;
}
if (xDataLength > 0)
{
if (this.m_variableInformation.Children.Count == 0)
{
for (int i = 0; i < xDataLength; i++)
{
DebugLocalInfo inf = new DebugLocalInfo();
inf.IsReference = true;
inf.Type = typeof(T).FullName;
inf.Offset = (int)(mArrayFirstElementOffset + (System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)) * i));
inf.Pointer = (uint)(xPointer + mArrayFirstElementOffset + (System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)) * i));
inf.Name = "[" + i.ToString() + "]";
this.m_variableInformation.Children.Add(new AD7Property(inf, this.mProcess, this.mStackFrame));
}
}
}
propertyInfo.bstrValue = String.Format(typeAsString + "[{0}] at 0x{1} ", xDataLength, xPointer.ToString("X"));
}
}
}
}
// Construct a DEBUG_PROPERTY_INFO representing this local or parameter.
public DEBUG_PROPERTY_INFO ConstructDebugPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields)
{
DEBUG_PROPERTY_INFO propertyInfo = new DEBUG_PROPERTY_INFO();
try
{
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME))
{
propertyInfo.bstrFullName = m_variableInformation.Name;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME))
{
propertyInfo.bstrName = m_variableInformation.Name;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_TYPE))
{
propertyInfo.bstrType = mDebugInfo.TYPENAME;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_TYPE;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE))
{
byte[] xData;
#region string
if (mDebugInfo.TYPENAME == typeof(string).FullName)
{
const uint xStringLengthOffset = 12;
const uint xStringFirstCharOffset = 16;
// Get handle
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
// Get actual pointer
xData = mProcess.mDbgConnector.GetMemoryData(BitConverter.ToUInt32(xData, 0), 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xStrPointer = BitConverter.ToUInt32(xData, 0);
if (xStrPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xStrPointer + xStringLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xStringLength = BitConverter.ToUInt32(xData, 0);
propertyInfo.bstrValue = "String of length: " + xStringLength;
if (xStringLength > 100)
{
propertyInfo.bstrValue = "For now, strings larger than 100 chars are not supported..";
}
else if (xStringLength == 0)
{
propertyInfo.bstrValue = "\"\"";
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xStrPointer + xStringFirstCharOffset, xStringLength * 2, 2);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
propertyInfo.bstrValue = "\"" + Encoding.Unicode.GetString(xData) + "\"";
}
}
}
}
}
}
#endregion
#warning TODO: String[]
#region byte
// Byte
else if (mDebugInfo.TYPENAME == typeof(byte).FullName)
{
ReadData<byte>(ref propertyInfo, new Func<byte[], int, byte>(delegate(byte[] barr, int ind) { return barr[ind]; }));
}
else if (mDebugInfo.TYPENAME == typeof(byte[]).FullName)
{
ReadDataArray<byte>(ref propertyInfo, "byte");
}
#endregion
#region sbyte
// SByte
else if (mDebugInfo.TYPENAME == typeof(sbyte).FullName)
{
ReadData<sbyte>(ref propertyInfo, new Func<byte[], int, sbyte>(delegate(byte[] barr, int ind) { return unchecked((sbyte)barr[ind]); }));
}
else if (mDebugInfo.TYPENAME == typeof(sbyte[]).FullName)
{
ReadDataArray<sbyte>(ref propertyInfo, "sbyte");
}
#endregion
#region char
else if (mDebugInfo.TYPENAME == typeof(char).FullName)
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 2);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
var xTypedCharValue = BitConverter.ToChar(xData, 0);
propertyInfo.bstrValue = String.Format("{0} '{1}'", (ushort)xTypedCharValue, xTypedCharValue);
}
}
else if (mDebugInfo.TYPENAME == typeof(char[]).FullName)
{
// Get handle
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
// Get actual pointer
xData = mProcess.mDbgConnector.GetMemoryData(BitConverter.ToUInt32(xData, 0), 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xArrayPointer = BitConverter.ToUInt32(xData, 0);
if (xArrayPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xArrayPointer + mArrayLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xDataLength = BitConverter.ToUInt32(xData, 0);
bool xIsTooLong = xDataLength > 512;
var xSB = new StringBuilder();
xSB.AppendFormat("Char[{0}] at 0x{1} {{ ", xDataLength, xArrayPointer.ToString("X"));
if (xIsTooLong)
{
xDataLength = 512;
}
if (xDataLength > 0)
{
xData = mProcess.mDbgConnector.GetMemoryData(xArrayPointer + mArrayFirstElementOffset, xDataLength * 2);
if (xData == null)
{
xSB.Append(String.Format("Error! Memory data received was null!"));
}
else
{
bool first = true;
for (int i = 0; (i / 2) < xDataLength; i += 2)
{
if (!first)
xSB.Append(", ");
char c = BitConverter.ToChar(xData, i);
xSB.Append('\'');
if (c == '\0')
{
xSB.Append("\\0");
}
else
{
xSB.Append(c);
}
xSB.Append('\'');
first = false;
}
}
}
if (xIsTooLong)
{
xSB.Append(", ..");
}
xSB.Append(" }");
propertyInfo.bstrValue = xSB.ToString();
}
}
}
}
#endregion
#region short
// Short
else if (mDebugInfo.TYPENAME == typeof(short).FullName)
{
ReadData<short>(ref propertyInfo, new Func<byte[], int, short>(BitConverter.ToInt16));
}
else if (mDebugInfo.TYPENAME == typeof(short[]).FullName)
{
ReadDataArray<short>(ref propertyInfo, "short");
}
#endregion
#region ushort
// UShort
else if (mDebugInfo.TYPENAME == typeof(ushort).FullName)
{
ReadData<ushort>(ref propertyInfo, new Func<byte[], int, ushort>(BitConverter.ToUInt16));
}
else if (mDebugInfo.TYPENAME == typeof(ushort[]).FullName)
{
ReadDataArray<ushort>(ref propertyInfo, "ushort");
}
#endregion
#region int
// Int32
else if (mDebugInfo.TYPENAME == typeof(int).FullName)
{
ReadData<int>(ref propertyInfo, new Func<byte[], int, int>(BitConverter.ToInt32));
}
else if (mDebugInfo.TYPENAME == typeof(int[]).FullName)
{
ReadDataArray<int>(ref propertyInfo, "int");
}
#endregion
#region uint
// UInt32
else if (mDebugInfo.TYPENAME == typeof(uint).FullName)
{
ReadData<uint>(ref propertyInfo, new Func<byte[], int, uint>(BitConverter.ToUInt32));
}
else if (mDebugInfo.TYPENAME == typeof(uint[]).FullName)
{
ReadDataArray<uint>(ref propertyInfo, "uint");
}
#endregion
#region long
// Long
else if (mDebugInfo.TYPENAME == typeof(long).FullName)
{
ReadData<long>(ref propertyInfo, new Func<byte[], int, long>(BitConverter.ToInt64));
}
else if (mDebugInfo.TYPENAME == typeof(long[]).FullName)
{
ReadDataArray<long>(ref propertyInfo, "long");
}
#endregion
#region ulong
// ULong
else if (mDebugInfo.TYPENAME == typeof(ulong).FullName)
{
ReadData<ulong>(ref propertyInfo, new Func<byte[], int, ulong>(BitConverter.ToUInt64));
}
else if (mDebugInfo.TYPENAME == typeof(ulong[]).FullName)
{
ReadDataArray<ulong>(ref propertyInfo, "ulong");
}
#endregion
#region float
// Float
else if (mDebugInfo.TYPENAME == typeof(float).FullName)
{
ReadData<float>(ref propertyInfo, new Func<byte[], int, float>(BitConverter.ToSingle));
}
else if (mDebugInfo.TYPENAME == typeof(float[]).FullName)
{
ReadDataArray<float>(ref propertyInfo, "float");
}
#endregion
#region double
// Double
else if (mDebugInfo.TYPENAME == typeof(double).FullName)
{
ReadData<double>(ref propertyInfo, new Func<byte[], int, double>(BitConverter.ToDouble));
}
else if (mDebugInfo.TYPENAME == typeof(double[]).FullName)
{
ReadDataArray<double>(ref propertyInfo, "double");
}
#endregion
#region bool
// Bool
else if (mDebugInfo.TYPENAME == typeof(bool).FullName)
{
ReadData<bool>(ref propertyInfo, new Func<byte[], int, bool>(BitConverter.ToBoolean));
}
else if (mDebugInfo.TYPENAME == typeof(bool[]).FullName)
{
ReadDataArray<bool>(ref propertyInfo, "bool");
}
#endregion
else
{
if (m_variableInformation.IsReference)
{
xData = mProcess.mDbgConnector.GetMemoryData(m_variableInformation.Pointer, 4, 4);
}
else
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
}
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
var xPointer = BitConverter.ToUInt32(xData, 0);
if (xPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
try
{
var mp = mProcess.mDebugInfoDb.GetFieldMap(mDebugInfo.TYPENAME);
foreach (string str in mp.FieldNames)
{
FIELD_INFO xFieldInfo;
xFieldInfo = mProcess.mDebugInfoDb.GetFieldInfoByName(str);
var inf = new DebugLocalInfo();
inf.IsReference = true;
inf.Type = xFieldInfo.TYPE;
inf.Offset = xFieldInfo.OFFSET;
inf.Pointer = (uint)(xPointer + xFieldInfo.OFFSET + 12);
inf.Name = GetFieldName(xFieldInfo);
this.m_variableInformation.Children.Add(new AD7Property(inf, this.mProcess, this.mStackFrame));
}
propertyInfo.bstrValue = String.Format("{0} (0x{1})", xPointer, xPointer.ToString("X").ToUpper());
}
catch (Exception ex)
{
if (ex.GetType().Name == "SQLiteException")
{
//Ignore but warn user
propertyInfo.bstrValue = "SQLiteException. Could not get type information for " + mDebugInfo.TYPENAME;
}
else
{
throw new Exception("Unexpected error in AD7Property.cs:459", ex);
}
}
}
}
}
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_ATTRIB))
{
// The sample does not support writing of values displayed in the debugger, so mark them all as read-only.
propertyInfo.dwAttrib = enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_VALUE_READONLY;
if (this.m_variableInformation.Children.Count > 0)
{
propertyInfo.dwAttrib |= enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_OBJ_IS_EXPANDABLE;
}
}
propertyInfo.pProperty = (IDebugProperty2)this;
propertyInfo.dwFields |= (enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP);
// If the debugger has asked for the property, or the property has children (meaning it is a pointer in the sample)
// then set the pProperty field so the debugger can call back when the children are enumerated.
//if (((dwFields & (uint)enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP) != 0)
//|| (this.m_variableInformation.child != null))
//{
// propertyInfo.pProperty = (IDebugProperty2)this;
// propertyInfo.dwFields |= (enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP);
//}
}
catch
{
}
return propertyInfo;
}
private static string GetFieldName(FIELD_INFO fInf)
{
string s = fInf.NAME;
int i = s.LastIndexOf('.');
if (i > 0)
{
s = s.Substring(i + 1, s.Length - i - 1);
return s;
}
return s;
}
#region IDebugProperty2 Members
// Enumerates the children of a property. This provides support for dereferencing pointers, displaying members of an array, or fields of a class or struct.
// The sample debugger only supports pointer dereferencing as children. This means there is only ever one child.
public int EnumChildren(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, ref System.Guid guidFilter, enum_DBG_ATTRIB_FLAGS dwAttribFilter, string pszNameFilter, uint dwTimeout, out IEnumDebugPropertyInfo2 ppEnum)
{
ppEnum = null;
if (this.m_variableInformation.Children.Count > 0)
{
List<DEBUG_PROPERTY_INFO> infs = new List<DEBUG_PROPERTY_INFO>();
foreach (AD7Property dp in m_variableInformation.Children)
{
infs.Add(dp.ConstructDebugPropertyInfo(dwFields));
}
ppEnum = new AD7PropertyEnum(infs.ToArray());
return VSConstants.S_OK;
}
//if (this.m_variableInformation.child != null)
//{
// DEBUG_PROPERTY_INFO[] properties = new DEBUG_PROPERTY_INFO[1];
// properties[0] = (new AD7Property(this.m_variableInformation.child)).ConstructDebugPropertyInfo(dwFields);
// ppEnum = new AD7PropertyEnum(properties);
// return VSConstants.S_OK;
//}
return VSConstants.S_FALSE;
}
// Returns the property that describes the most-derived property of a property
// This is called to support object oriented languages. It allows the debug engine to return an IDebugProperty2 for the most-derived
// object in a hierarchy. This engine does not support this.
public int GetDerivedMostProperty(out IDebugProperty2 ppDerivedMost)
{
throw new Exception("The method or operation is not implemented.");
}
// This method exists for the purpose of retrieving information that does not lend itself to being retrieved by calling the IDebugProperty2::GetPropertyInfo
// method. This includes information about custom viewers, managed type slots and other information.
// The sample engine does not support this.
public int GetExtendedInfo(ref System.Guid guidExtendedInfo, out object pExtendedInfo)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the memory bytes for a property value.
public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the memory context for a property value.
public int GetMemoryContext(out IDebugMemoryContext2 ppMemory)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the parent of a property.
// The sample engine does not support obtaining the parent of properties.
public int GetParent(out IDebugProperty2 ppParent)
{
throw new Exception("The method or operation is not implemented.");
}
// Fills in a DEBUG_PROPERTY_INFO structure that describes a property.
public int GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, uint dwTimeout, IDebugReference2[] rgpArgs, uint dwArgCount, DEBUG_PROPERTY_INFO[] pPropertyInfo)
{
pPropertyInfo[0] = new DEBUG_PROPERTY_INFO();
rgpArgs = null;
pPropertyInfo[0] = ConstructDebugPropertyInfo(dwFields);
return VSConstants.S_OK;
}
// Return an IDebugReference2 for this property. An IDebugReference2 can be thought of as a type and an address.
public int GetReference(out IDebugReference2 ppReference)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the size, in bytes, of the property value.
public int GetSize(out uint pdwSize)
{
throw new Exception("The method or operation is not implemented.");
}
// The debugger will call this when the user tries to edit the property's values
// the sample has set the read-only flag on its properties, so this should not be called.
public int SetValueAsReference(IDebugReference2[] rgpArgs, uint dwArgCount, IDebugReference2 pValue, uint dwTimeout)
{
throw new Exception("The method or operation is not implemented.");
}
// The debugger will call this when the user tries to edit the property's values in one of the debugger windows.
// the sample has set the read-only flag on its properties, so this should not be called.
public int SetValueAsString(string pszValue, uint dwRadix, uint dwTimeout)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using FluentAssertions;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.Tools.Test.Utilities;
using NuGet.Frameworks;
using Xunit;
namespace Microsoft.DotNet.Cli.Utils.Tests
{
public class GivenAProjectDependenciesCommandResolver
{
private static readonly string s_liveProjectDirectory =
Path.Combine(AppContext.BaseDirectory, "TestAssets/TestProjects/AppWithDirectDependency");
[Fact]
public void It_returns_null_when_CommandName_is_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = null,
CommandArguments = new string[] { "" },
ProjectDirectory = "/some/directory",
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_ProjectDirectory_is_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "command",
CommandArguments = new string[] { "" },
ProjectDirectory = null,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_Framework_is_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "command",
CommandArguments = new string[] { "" },
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = null
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_Configuration_is_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "command",
CommandArguments = new string[] { "" },
ProjectDirectory = s_liveProjectDirectory,
Configuration = null,
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_CommandName_does_not_exist_in_ProjectDependencies()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "nonexistent-command",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_a_CommandSpec_with_CoreHost_as_FileName_and_CommandName_in_Args_when_CommandName_exists_in_ProjectDependencies()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFile = Path.GetFileNameWithoutExtension(result.Path);
commandFile.Should().Be("corehost");
result.Args.Should().Contain(commandResolverArguments.CommandName);
}
[Fact]
public void It_escapes_CommandArguments_when_returning_a_CommandSpec()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "dotnet-hello",
CommandArguments = new[] { "arg with space" },
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain("\"arg with space\"");
}
[Fact]
public void It_passes_depsfile_arg_to_corehost_when_returning_a_commandspec()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain("--depsfile");
}
[Fact]
public void It_sets_depsfile_in_output_path_in_commandspec()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var outputDir = Path.Combine(AppContext.BaseDirectory, "outdir");
var commandResolverArguments = new CommandResolverArguments
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10,
OutputPath = outputDir
};
var buildCommand = new BuildCommand(
Path.Combine(s_liveProjectDirectory, "project.json"),
output: outputDir,
framework: FrameworkConstants.CommonFrameworks.NetCoreApp10.ToString())
.Execute().Should().Pass();
var projectContext = ProjectContext.Create(
s_liveProjectDirectory,
FrameworkConstants.CommonFrameworks.NetCoreApp10,
RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());
var depsFilePath =
projectContext.GetOutputPaths("Debug", outputPath: outputDir).RuntimeFiles.DepsJson;
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain($"--depsfile {depsFilePath}");
}
[Fact]
public void It_sets_depsfile_in_build_base_path_in_commandspec()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var buildBasePath = Path.Combine(AppContext.BaseDirectory, "basedir");
var commandResolverArguments = new CommandResolverArguments
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10,
BuildBasePath = buildBasePath
};
var buildCommand = new BuildCommand(
Path.Combine(s_liveProjectDirectory, "project.json"),
buildBasePath: buildBasePath,
framework: FrameworkConstants.CommonFrameworks.NetCoreApp10.ToString())
.Execute().Should().Pass();
var projectContext = ProjectContext.Create(
s_liveProjectDirectory,
FrameworkConstants.CommonFrameworks.NetCoreApp10,
RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());
var depsFilePath =
projectContext.GetOutputPaths("Debug", buildBasePath).RuntimeFiles.DepsJson;
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain($"--depsfile {depsFilePath}");
}
[Fact]
public void It_returns_a_CommandSpec_with_CommandName_in_Args_when_returning_a_CommandSpec_and_CommandArguments_are_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain("dotnet-hello");
}
private ProjectDependenciesCommandResolver SetupProjectDependenciesCommandResolver(
IEnvironmentProvider environment = null,
IPackagedCommandSpecFactory packagedCommandSpecFactory = null)
{
environment = environment ?? new EnvironmentProvider();
packagedCommandSpecFactory = packagedCommandSpecFactory ?? new PackagedCommandSpecFactory();
var projectDependenciesCommandResolver = new ProjectDependenciesCommandResolver(environment, packagedCommandSpecFactory);
return projectDependenciesCommandResolver;
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmFilterList
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmFilterList() : base()
{
Load += frmFilterList_Load;
FormClosed += frmFilterList_FormClosed;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.CheckedListBox withEventsField_lstFilter;
public System.Windows.Forms.CheckedListBox lstFilter {
get { return withEventsField_lstFilter; }
set {
if (withEventsField_lstFilter != null) {
withEventsField_lstFilter.ItemCheck -= lstFilter_ItemCheck;
withEventsField_lstFilter.KeyDown -= lstFilter_KeyDown;
withEventsField_lstFilter.KeyPress -= lstFilter_KeyPress;
}
withEventsField_lstFilter = value;
if (withEventsField_lstFilter != null) {
withEventsField_lstFilter.ItemCheck += lstFilter_ItemCheck;
withEventsField_lstFilter.KeyDown += lstFilter_KeyDown;
withEventsField_lstFilter.KeyPress += lstFilter_KeyPress;
}
}
}
public System.Windows.Forms.Button _cmdClick_4;
public System.Windows.Forms.Button _cmdClick_1;
public System.Windows.Forms.Button _cmdClick_2;
public System.Windows.Forms.Button _cmdClick_3;
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button1;
public System.Windows.Forms.ToolStripButton _tbStockItem_Button1 {
get { return withEventsField__tbStockItem_Button1; }
set {
if (withEventsField__tbStockItem_Button1 != null) {
withEventsField__tbStockItem_Button1.Click -= tbStockItem_ButtonClick;
}
withEventsField__tbStockItem_Button1 = value;
if (withEventsField__tbStockItem_Button1 != null) {
withEventsField__tbStockItem_Button1.Click += tbStockItem_ButtonClick;
}
}
}
private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button2;
public System.Windows.Forms.ToolStripButton _tbStockItem_Button2 {
get { return withEventsField__tbStockItem_Button2; }
set {
if (withEventsField__tbStockItem_Button2 != null) {
withEventsField__tbStockItem_Button2.Click -= tbStockItem_ButtonClick;
}
withEventsField__tbStockItem_Button2 = value;
if (withEventsField__tbStockItem_Button2 != null) {
withEventsField__tbStockItem_Button2.Click += tbStockItem_ButtonClick;
}
}
}
private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button3;
public System.Windows.Forms.ToolStripButton _tbStockItem_Button3 {
get { return withEventsField__tbStockItem_Button3; }
set {
if (withEventsField__tbStockItem_Button3 != null) {
withEventsField__tbStockItem_Button3.Click -= tbStockItem_ButtonClick;
}
withEventsField__tbStockItem_Button3 = value;
if (withEventsField__tbStockItem_Button3 != null) {
withEventsField__tbStockItem_Button3.Click += tbStockItem_ButtonClick;
}
}
}
private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button4;
public System.Windows.Forms.ToolStripButton _tbStockItem_Button4 {
get { return withEventsField__tbStockItem_Button4; }
set {
if (withEventsField__tbStockItem_Button4 != null) {
withEventsField__tbStockItem_Button4.Click -= tbStockItem_ButtonClick;
}
withEventsField__tbStockItem_Button4 = value;
if (withEventsField__tbStockItem_Button4 != null) {
withEventsField__tbStockItem_Button4.Click += tbStockItem_ButtonClick;
}
}
}
public System.Windows.Forms.ToolStrip tbStockItem;
public System.Windows.Forms.ImageList ilSelect;
public System.Windows.Forms.Label _lbl_2;
//Public WithEvents cmdClick As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmFilterList));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.lstFilter = new System.Windows.Forms.CheckedListBox();
this._cmdClick_4 = new System.Windows.Forms.Button();
this._cmdClick_1 = new System.Windows.Forms.Button();
this._cmdClick_2 = new System.Windows.Forms.Button();
this._cmdClick_3 = new System.Windows.Forms.Button();
this.txtSearch = new System.Windows.Forms.TextBox();
this.tbStockItem = new System.Windows.Forms.ToolStrip();
this._tbStockItem_Button1 = new System.Windows.Forms.ToolStripButton();
this._tbStockItem_Button2 = new System.Windows.Forms.ToolStripButton();
this._tbStockItem_Button3 = new System.Windows.Forms.ToolStripButton();
this._tbStockItem_Button4 = new System.Windows.Forms.ToolStripButton();
this.ilSelect = new System.Windows.Forms.ImageList();
this._lbl_2 = new System.Windows.Forms.Label();
//Me.cmdClick = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.tbStockItem.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.ClientSize = new System.Drawing.Size(293, 452);
this.Location = new System.Drawing.Point(3, 3);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmFilterList";
this.lstFilter.Size = new System.Drawing.Size(271, 379);
this.lstFilter.Location = new System.Drawing.Point(9, 63);
this.lstFilter.TabIndex = 7;
this.lstFilter.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lstFilter.BackColor = System.Drawing.SystemColors.Window;
this.lstFilter.CausesValidation = true;
this.lstFilter.Enabled = true;
this.lstFilter.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstFilter.IntegralHeight = true;
this.lstFilter.Cursor = System.Windows.Forms.Cursors.Default;
this.lstFilter.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.lstFilter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstFilter.Sorted = false;
this.lstFilter.TabStop = true;
this.lstFilter.Visible = true;
this.lstFilter.MultiColumn = false;
this.lstFilter.Name = "lstFilter";
this._cmdClick_4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdClick_4.Text = "&C";
this._cmdClick_4.Size = new System.Drawing.Size(103, 34);
this._cmdClick_4.Location = new System.Drawing.Point(360, 138);
this._cmdClick_4.TabIndex = 6;
this._cmdClick_4.TabStop = false;
this._cmdClick_4.BackColor = System.Drawing.SystemColors.Control;
this._cmdClick_4.CausesValidation = true;
this._cmdClick_4.Enabled = true;
this._cmdClick_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdClick_4.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdClick_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdClick_4.Name = "_cmdClick_4";
this._cmdClick_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdClick_1.Text = "&A";
this._cmdClick_1.Size = new System.Drawing.Size(103, 34);
this._cmdClick_1.Location = new System.Drawing.Point(357, 204);
this._cmdClick_1.TabIndex = 5;
this._cmdClick_1.TabStop = false;
this._cmdClick_1.BackColor = System.Drawing.SystemColors.Control;
this._cmdClick_1.CausesValidation = true;
this._cmdClick_1.Enabled = true;
this._cmdClick_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdClick_1.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdClick_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdClick_1.Name = "_cmdClick_1";
this._cmdClick_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdClick_2.Text = "&S";
this._cmdClick_2.Size = new System.Drawing.Size(103, 34);
this._cmdClick_2.Location = new System.Drawing.Point(360, 252);
this._cmdClick_2.TabIndex = 4;
this._cmdClick_2.TabStop = false;
this._cmdClick_2.BackColor = System.Drawing.SystemColors.Control;
this._cmdClick_2.CausesValidation = true;
this._cmdClick_2.Enabled = true;
this._cmdClick_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdClick_2.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdClick_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdClick_2.Name = "_cmdClick_2";
this._cmdClick_3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdClick_3.Text = "&U";
this._cmdClick_3.Size = new System.Drawing.Size(103, 34);
this._cmdClick_3.Location = new System.Drawing.Point(351, 303);
this._cmdClick_3.TabIndex = 3;
this._cmdClick_3.TabStop = false;
this._cmdClick_3.BackColor = System.Drawing.SystemColors.Control;
this._cmdClick_3.CausesValidation = true;
this._cmdClick_3.Enabled = true;
this._cmdClick_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdClick_3.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdClick_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdClick_3.Name = "_cmdClick_3";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(223, 19);
this.txtSearch.Location = new System.Drawing.Point(57, 42);
this.txtSearch.TabIndex = 1;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
this.tbStockItem.ShowItemToolTips = true;
this.tbStockItem.Size = new System.Drawing.Size(272, 40);
this.tbStockItem.Location = new System.Drawing.Point(9, 0);
this.tbStockItem.TabIndex = 0;
this.tbStockItem.ImageList = ilSelect;
this.tbStockItem.Name = "tbStockItem";
this._tbStockItem_Button1.Size = new System.Drawing.Size(68, 41);
this._tbStockItem_Button1.AutoSize = false;
this._tbStockItem_Button1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;
this._tbStockItem_Button1.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this._tbStockItem_Button1.Text = "&All";
this._tbStockItem_Button1.Name = "All";
this._tbStockItem_Button1.ImageIndex = 0;
this._tbStockItem_Button1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this._tbStockItem_Button2.Size = new System.Drawing.Size(68, 41);
this._tbStockItem_Button2.AutoSize = false;
this._tbStockItem_Button2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;
this._tbStockItem_Button2.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this._tbStockItem_Button2.Text = "&Selected";
this._tbStockItem_Button2.Name = "Selected";
this._tbStockItem_Button2.ImageIndex = 1;
this._tbStockItem_Button2.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this._tbStockItem_Button3.Size = new System.Drawing.Size(68, 41);
this._tbStockItem_Button3.AutoSize = false;
this._tbStockItem_Button3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;
this._tbStockItem_Button3.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this._tbStockItem_Button3.Text = "&Unselected";
this._tbStockItem_Button3.Name = "Unselected";
this._tbStockItem_Button3.ImageIndex = 2;
this._tbStockItem_Button3.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this._tbStockItem_Button4.Size = new System.Drawing.Size(68, 41);
this._tbStockItem_Button4.AutoSize = false;
this._tbStockItem_Button4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;
this._tbStockItem_Button4.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this._tbStockItem_Button4.Text = "&Clear All";
this._tbStockItem_Button4.Name = "clear";
this._tbStockItem_Button4.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.ilSelect.ImageSize = new System.Drawing.Size(20, 20);
this.ilSelect.TransparentColor = System.Drawing.Color.FromArgb(255, 0, 255);
this.ilSelect.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("ilSelect.ImageStream");
this.ilSelect.Images.SetKeyName(0, "");
this.ilSelect.Images.SetKeyName(1, "");
this.ilSelect.Images.SetKeyName(2, "");
this._lbl_2.Text = "Search:";
this._lbl_2.Size = new System.Drawing.Size(40, 13);
this._lbl_2.Location = new System.Drawing.Point(9, 48);
this._lbl_2.TabIndex = 2;
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = false;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this.Controls.Add(lstFilter);
this.Controls.Add(_cmdClick_4);
this.Controls.Add(_cmdClick_1);
this.Controls.Add(_cmdClick_2);
this.Controls.Add(_cmdClick_3);
this.Controls.Add(txtSearch);
this.Controls.Add(tbStockItem);
this.Controls.Add(_lbl_2);
this.tbStockItem.Items.Add(_tbStockItem_Button1);
this.tbStockItem.Items.Add(_tbStockItem_Button2);
this.tbStockItem.Items.Add(_tbStockItem_Button3);
this.tbStockItem.Items.Add(_tbStockItem_Button4);
//Me.cmdClick.SetIndex(_cmdClick_4, CType(4, Short))
//Me.cmdClick.SetIndex(_cmdClick_1, CType(1, Short))
//Me.cmdClick.SetIndex(_cmdClick_2, CType(2, Short))
//Me.cmdClick.SetIndex(_cmdClick_3, CType(3, Short))
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).EndInit()
this.tbStockItem.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using Nini.Config;
/*
* 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 copyrightD
* 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.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public struct MaterialAttributes
{
// Material type values that correspond with definitions for LSL
public enum Material : int
{
Stone = 0,
Metal,
Glass,
Wood,
Flesh,
Plastic,
Rubber,
Light,
// Hereafter are BulletSim additions
Avatar,
NumberOfTypes // the count of types in the enum.
}
// Names must be in the order of the above enum.
// These names must coorespond to the lower case field names in the MaterialAttributes
// structure as reflection is used to select the field to put the value in.
public static readonly string[] MaterialAttribs = { "Density", "Friction", "Restitution"};
public MaterialAttributes(string t, float d, float f, float r)
{
type = t;
density = d;
friction = f;
restitution = r;
}
public string type;
public float density;
public float friction;
public float restitution;
}
public static class BSMaterials
{
// Attributes for each material type
private static readonly MaterialAttributes[] Attributes;
// Map of material name to material type code
public static readonly Dictionary<string, MaterialAttributes.Material> MaterialMap;
static BSMaterials()
{
// Attribute sets for both the non-physical and physical instances of materials.
Attributes = new MaterialAttributes[(int)MaterialAttributes.Material.NumberOfTypes * 2];
// Map of name to type code.
MaterialMap = new Dictionary<string, MaterialAttributes.Material>();
MaterialMap.Add("Stone", MaterialAttributes.Material.Stone);
MaterialMap.Add("Metal", MaterialAttributes.Material.Metal);
MaterialMap.Add("Glass", MaterialAttributes.Material.Glass);
MaterialMap.Add("Wood", MaterialAttributes.Material.Wood);
MaterialMap.Add("Flesh", MaterialAttributes.Material.Flesh);
MaterialMap.Add("Plastic", MaterialAttributes.Material.Plastic);
MaterialMap.Add("Rubber", MaterialAttributes.Material.Rubber);
MaterialMap.Add("Light", MaterialAttributes.Material.Light);
MaterialMap.Add("Avatar", MaterialAttributes.Material.Avatar);
}
// This is where all the default material attributes are defined.
public static void InitializeFromDefaults(ConfigurationParameters parms)
{
// Values from http://wiki.secondlife.com/wiki/PRIM_MATERIAL
float dDensity = parms.defaultDensity;
float dFriction = parms.defaultFriction;
float dRestitution = parms.defaultRestitution;
Attributes[(int)MaterialAttributes.Material.Stone] =
new MaterialAttributes("stone",dDensity, 0.8f, 0.4f);
Attributes[(int)MaterialAttributes.Material.Metal] =
new MaterialAttributes("metal",dDensity, 0.3f, 0.4f);
Attributes[(int)MaterialAttributes.Material.Glass] =
new MaterialAttributes("glass",dDensity, 0.2f, 0.7f);
Attributes[(int)MaterialAttributes.Material.Wood] =
new MaterialAttributes("wood",dDensity, 0.6f, 0.5f);
Attributes[(int)MaterialAttributes.Material.Flesh] =
new MaterialAttributes("flesh",dDensity, 0.9f, 0.3f);
Attributes[(int)MaterialAttributes.Material.Plastic] =
new MaterialAttributes("plastic",dDensity, 0.4f, 0.7f);
Attributes[(int)MaterialAttributes.Material.Rubber] =
new MaterialAttributes("rubber",dDensity, 0.9f, 0.9f);
Attributes[(int)MaterialAttributes.Material.Light] =
new MaterialAttributes("light",dDensity, dFriction, dRestitution);
Attributes[(int)MaterialAttributes.Material.Avatar] =
new MaterialAttributes("avatar",3.5f, 0.2f, 0f);
Attributes[(int)MaterialAttributes.Material.Stone + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("stonePhysical",dDensity, 0.8f, 0.4f);
Attributes[(int)MaterialAttributes.Material.Metal + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("metalPhysical",dDensity, 0.3f, 0.4f);
Attributes[(int)MaterialAttributes.Material.Glass + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("glassPhysical",dDensity, 0.2f, 0.7f);
Attributes[(int)MaterialAttributes.Material.Wood + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("woodPhysical",dDensity, 0.6f, 0.5f);
Attributes[(int)MaterialAttributes.Material.Flesh + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("fleshPhysical",dDensity, 0.9f, 0.3f);
Attributes[(int)MaterialAttributes.Material.Plastic + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("plasticPhysical",dDensity, 0.4f, 0.7f);
Attributes[(int)MaterialAttributes.Material.Rubber + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("rubberPhysical",dDensity, 0.9f, 0.9f);
Attributes[(int)MaterialAttributes.Material.Light + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("lightPhysical",dDensity, dFriction, dRestitution);
Attributes[(int)MaterialAttributes.Material.Avatar + (int)MaterialAttributes.Material.NumberOfTypes] =
new MaterialAttributes("avatarPhysical",3.5f, 0.2f, 0f);
}
// Under the [BulletSim] section, one can change the individual material
// attribute values. The format of the configuration parameter is:
// <materialName><Attribute>["Physical"] = floatValue
// For instance:
// [BulletSim]
// StoneFriction = 0.2
// FleshRestitutionPhysical = 0.8
// Materials can have different parameters for their static and
// physical instantiations. When setting the non-physical value,
// both values are changed. Setting the physical value only changes
// the physical value.
public static void InitializefromParameters(IConfig pConfig)
{
foreach (KeyValuePair<string, MaterialAttributes.Material> kvp in MaterialMap)
{
string matName = kvp.Key;
foreach (string attribName in MaterialAttributes.MaterialAttribs)
{
string paramName = matName + attribName;
if (pConfig.Contains(paramName))
{
float paramValue = pConfig.GetFloat(paramName);
SetAttributeValue((int)kvp.Value, attribName, paramValue);
// set the physical value also
SetAttributeValue((int)kvp.Value + (int)MaterialAttributes.Material.NumberOfTypes, attribName, paramValue);
}
paramName += "Physical";
if (pConfig.Contains(paramName))
{
float paramValue = pConfig.GetFloat(paramName);
SetAttributeValue((int)kvp.Value + (int)MaterialAttributes.Material.NumberOfTypes, attribName, paramValue);
}
}
}
}
// Use reflection to set the value in the attribute structure.
private static void SetAttributeValue(int matType, string attribName, float val)
{
// Get the current attribute values for this material
MaterialAttributes thisAttrib = Attributes[matType];
// Find the field for the passed attribute name (eg, find field named 'friction')
FieldInfo fieldInfo = thisAttrib.GetType().GetField(attribName.ToLower());
if (fieldInfo != null)
{
fieldInfo.SetValue(thisAttrib, val);
// Copy new attributes back to array -- since MaterialAttributes is 'struct', passed by value, not reference.
Attributes[matType] = thisAttrib;
}
}
// Given a material type, return a structure of attributes.
public static MaterialAttributes GetAttributes(MaterialAttributes.Material type, bool isPhysical)
{
int ind = (int)type;
if (isPhysical) ind += (int)MaterialAttributes.Material.NumberOfTypes;
return Attributes[ind];
}
}
}
| |
//
// ScrollViewBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 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 System;
using Xwt.Backends;
namespace Xwt.GtkBackend
{
public class ScrollViewBackend: WidgetBackend, IScrollViewBackend
{
bool showBorder = true;
public ScrollViewBackend ()
{
Widget = new Gtk.ScrolledWindow ();
Widget.Show ();
}
protected new Gtk.ScrolledWindow Widget {
get { return (Gtk.ScrolledWindow)base.Widget; }
set { base.Widget = value; }
}
protected new IScrollViewEventSink EventSink {
get { return (IScrollViewEventSink)base.EventSink; }
}
Gtk.Widget currentChild;
public void SetChild (IWidgetBackend child)
{
RemoveChildPlacement (currentChild);
if (Widget.Child != null) {
if (Widget.Child is Gtk.Bin) {
Gtk.Bin vp = (Gtk.Bin) Widget.Child;
vp.Remove (vp.Child);
}
Widget.Remove (Widget.Child);
}
if (child != null) {
var w = currentChild = GetWidgetWithPlacement (child);
WidgetBackend wb = (WidgetBackend) child;
if (wb.EventSink.SupportsCustomScrolling ()) {
CustomViewPort vp = new CustomViewPort (wb.EventSink);
vp.Show ();
vp.Add (w);
Widget.Child = vp;
}
#if XWT_GTK3
else if (w is Gtk.IScrollable)
Widget.Child = w;
#else
// Gtk2 has no interface for natively scrollable widgets, therefore we manually check
// for types that should not be packed into a Viewport.
// see: https://developer.gnome.org/gtk2/stable/GtkScrolledWindow.html#gtk-scrolled-window-add-with-viewport
else if (w is Gtk.Viewport || w is Gtk.TreeView || w is Gtk.TextView || w is Gtk.Layout || w is WebKit.WebView)
Widget.Child = w;
#endif
else {
Gtk.Viewport vp = new Gtk.Viewport ();
vp.Show ();
vp.Add (w);
Widget.Child = vp;
}
}
UpdateBorder ();
}
public void SetChildSize (Size s)
{
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ScrollViewEvent) {
if (((ScrollViewEvent)eventId) == ScrollViewEvent.VisibleRectChanged) {
Widget.Hadjustment.ValueChanged += HandleValueChanged;
Widget.Vadjustment.ValueChanged += HandleValueChanged;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ScrollViewEvent) {
if (((ScrollViewEvent)eventId) == ScrollViewEvent.VisibleRectChanged) {
Widget.Hadjustment.ValueChanged -= HandleValueChanged;
Widget.Vadjustment.ValueChanged -= HandleValueChanged;
}
}
}
[GLib.ConnectBefore]
void HandleValueChanged (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnVisibleRectChanged ();
});
}
public Rectangle VisibleRect {
get {
double x = Widget.Hadjustment.Value;
double y = Widget.Vadjustment.Value;
return new Rectangle (x, y, Widget.Hadjustment.PageSize, Widget.Vadjustment.PageSize);
}
}
public bool BorderVisible {
get {
return Widget.ShadowType == Gtk.ShadowType.In;
}
set {
showBorder = value;
UpdateBorder ();
}
}
void UpdateBorder ()
{
var shadowType = showBorder ? Gtk.ShadowType.In : Gtk.ShadowType.None;
if (Widget.Child is Gtk.Viewport)
((Gtk.Viewport)Widget.Child).ShadowType = shadowType;
else
Widget.ShadowType = shadowType;
}
public ScrollPolicy VerticalScrollPolicy {
get {
return Widget.VscrollbarPolicy.ToXwtValue ();
}
set {
Widget.VscrollbarPolicy = value.ToGtkValue ();
}
}
public ScrollPolicy HorizontalScrollPolicy {
get {
return Widget.HscrollbarPolicy.ToXwtValue ();
}
set {
Widget.HscrollbarPolicy = value.ToGtkValue ();
}
}
public IScrollControlBackend CreateVerticalScrollControl ()
{
return new ScrollControltBackend (Widget.Vadjustment);
}
public IScrollControlBackend CreateHorizontalScrollControl ()
{
return new ScrollControltBackend (Widget.Hadjustment);
}
}
sealed class CustomViewPort: GtkViewPort
{
Gtk.Widget child;
IWidgetEventSink eventSink;
public CustomViewPort (IntPtr raw) : base (raw)
{
}
public CustomViewPort (IWidgetEventSink eventSink)
{
this.eventSink = eventSink;
}
protected override void OnAdded (Gtk.Widget widget)
{
base.OnAdded (widget);
child = widget;
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
if (child != null)
child.SizeAllocate (allocation);
}
protected override void OnSizeRequested (ref Gtk.Requisition requisition)
{
if (Child != null) {
requisition = Child.SizeRequest ();
} else {
requisition.Width = 0;
requisition.Height = 0;
}
}
protected override void OnSetScrollAdjustments (Gtk.Adjustment hadj, Gtk.Adjustment vadj)
{
var hsa = new ScrollAdjustmentBackend (hadj);
var vsa = new ScrollAdjustmentBackend (vadj);
eventSink.SetScrollAdjustments (hsa, vsa);
}
}
}
| |
using System;
using System.IO;
using Raksha.Asn1;
using Raksha.Crypto;
using Raksha.Security;
using Raksha.Utilities;
using Raksha.Utilities.Date;
namespace Raksha.Bcpg.OpenPgp
{
/// <remarks>A PGP signature object.</remarks>
public class PgpSignature
{
public const int BinaryDocument = 0x00;
public const int CanonicalTextDocument = 0x01;
public const int StandAlone = 0x02;
public const int DefaultCertification = 0x10;
public const int NoCertification = 0x11;
public const int CasualCertification = 0x12;
public const int PositiveCertification = 0x13;
public const int SubkeyBinding = 0x18;
public const int PrimaryKeyBinding = 0x19;
public const int DirectKey = 0x1f;
public const int KeyRevocation = 0x20;
public const int SubkeyRevocation = 0x28;
public const int CertificationRevocation = 0x30;
public const int Timestamp = 0x40;
private readonly SignaturePacket sigPck;
private readonly int signatureType;
private readonly TrustPacket trustPck;
private ISigner sig;
private byte lastb; // Initial value anything but '\r'
internal PgpSignature(
BcpgInputStream bcpgInput)
: this((SignaturePacket)bcpgInput.ReadPacket())
{
}
internal PgpSignature(
SignaturePacket sigPacket)
: this(sigPacket, null)
{
}
internal PgpSignature(
SignaturePacket sigPacket,
TrustPacket trustPacket)
{
if (sigPacket == null)
throw new ArgumentNullException("sigPacket");
this.sigPck = sigPacket;
this.signatureType = sigPck.SignatureType;
this.trustPck = trustPacket;
}
private void GetSig()
{
this.sig = SignerUtilities.GetSigner(
PgpUtilities.GetSignatureName(sigPck.KeyAlgorithm, sigPck.HashAlgorithm));
}
/// <summary>The OpenPGP version number for this signature.</summary>
public int Version
{
get { return sigPck.Version; }
}
/// <summary>The key algorithm associated with this signature.</summary>
public PublicKeyAlgorithmTag KeyAlgorithm
{
get { return sigPck.KeyAlgorithm; }
}
/// <summary>The hash algorithm associated with this signature.</summary>
public HashAlgorithmTag HashAlgorithm
{
get { return sigPck.HashAlgorithm; }
}
public void InitVerify(
PgpPublicKey pubKey)
{
lastb = 0;
if (sig == null)
{
GetSig();
}
try
{
sig.Init(false, pubKey.GetKey());
}
catch (InvalidKeyException e)
{
throw new PgpException("invalid key.", e);
}
}
public void Update(
byte b)
{
if (signatureType == CanonicalTextDocument)
{
doCanonicalUpdateByte(b);
}
else
{
sig.Update(b);
}
}
private void doCanonicalUpdateByte(
byte b)
{
if (b == '\r')
{
doUpdateCRLF();
}
else if (b == '\n')
{
if (lastb != '\r')
{
doUpdateCRLF();
}
}
else
{
sig.Update(b);
}
lastb = b;
}
private void doUpdateCRLF()
{
sig.Update((byte)'\r');
sig.Update((byte)'\n');
}
public void Update(
params byte[] bytes)
{
Update(bytes, 0, bytes.Length);
}
public void Update(
byte[] bytes,
int off,
int length)
{
if (signatureType == CanonicalTextDocument)
{
int finish = off + length;
for (int i = off; i != finish; i++)
{
doCanonicalUpdateByte(bytes[i]);
}
}
else
{
sig.BlockUpdate(bytes, off, length);
}
}
public bool Verify()
{
byte[] trailer = GetSignatureTrailer();
sig.BlockUpdate(trailer, 0, trailer.Length);
return sig.VerifySignature(GetSignature());
}
private void UpdateWithIdData(
int header,
byte[] idBytes)
{
this.Update(
(byte) header,
(byte)(idBytes.Length >> 24),
(byte)(idBytes.Length >> 16),
(byte)(idBytes.Length >> 8),
(byte)(idBytes.Length));
this.Update(idBytes);
}
private void UpdateWithPublicKey(
PgpPublicKey key)
{
byte[] keyBytes = GetEncodedPublicKey(key);
this.Update(
(byte) 0x99,
(byte)(keyBytes.Length >> 8),
(byte)(keyBytes.Length));
this.Update(keyBytes);
}
/// <summary>
/// Verify the signature as certifying the passed in public key as associated
/// with the passed in user attributes.
/// </summary>
/// <param name="userAttributes">User attributes the key was stored under.</param>
/// <param name="key">The key to be verified.</param>
/// <returns>True, if the signature matches, false otherwise.</returns>
public bool VerifyCertification(
PgpUserAttributeSubpacketVector userAttributes,
PgpPublicKey key)
{
UpdateWithPublicKey(key);
//
// hash in the userAttributes
//
try
{
MemoryStream bOut = new MemoryStream();
foreach (UserAttributeSubpacket packet in userAttributes.ToSubpacketArray())
{
packet.Encode(bOut);
}
UpdateWithIdData(0xd1, bOut.ToArray());
}
catch (IOException e)
{
throw new PgpException("cannot encode subpacket array", e);
}
this.Update(sigPck.GetSignatureTrailer());
return sig.VerifySignature(this.GetSignature());
}
/// <summary>
/// Verify the signature as certifying the passed in public key as associated
/// with the passed in ID.
/// </summary>
/// <param name="id">ID the key was stored under.</param>
/// <param name="key">The key to be verified.</param>
/// <returns>True, if the signature matches, false otherwise.</returns>
public bool VerifyCertification(
string id,
PgpPublicKey key)
{
UpdateWithPublicKey(key);
//
// hash in the id
//
UpdateWithIdData(0xb4, Strings.ToByteArray(id));
Update(sigPck.GetSignatureTrailer());
return sig.VerifySignature(GetSignature());
}
/// <summary>Verify a certification for the passed in key against the passed in master key.</summary>
/// <param name="masterKey">The key we are verifying against.</param>
/// <param name="pubKey">The key we are verifying.</param>
/// <returns>True, if the certification is valid, false otherwise.</returns>
public bool VerifyCertification(
PgpPublicKey masterKey,
PgpPublicKey pubKey)
{
UpdateWithPublicKey(masterKey);
UpdateWithPublicKey(pubKey);
Update(sigPck.GetSignatureTrailer());
return sig.VerifySignature(GetSignature());
}
/// <summary>Verify a key certification, such as revocation, for the passed in key.</summary>
/// <param name="pubKey">The key we are checking.</param>
/// <returns>True, if the certification is valid, false otherwise.</returns>
public bool VerifyCertification(
PgpPublicKey pubKey)
{
if (SignatureType != KeyRevocation
&& SignatureType != SubkeyRevocation)
{
throw new InvalidOperationException("signature is not a key signature");
}
UpdateWithPublicKey(pubKey);
Update(sigPck.GetSignatureTrailer());
return sig.VerifySignature(GetSignature());
}
public int SignatureType
{
get { return sigPck.SignatureType; }
}
/// <summary>The ID of the key that created the signature.</summary>
public long KeyId
{
get { return sigPck.KeyId; }
}
[Obsolete("Use 'CreationTime' property instead")]
public DateTime GetCreationTime()
{
return CreationTime;
}
/// <summary>The creation time of this signature.</summary>
public DateTime CreationTime
{
get { return DateTimeUtilities.UnixMsToDateTime(sigPck.CreationTime); }
}
public byte[] GetSignatureTrailer()
{
return sigPck.GetSignatureTrailer();
}
/// <summary>
/// Return true if the signature has either hashed or unhashed subpackets.
/// </summary>
public bool HasSubpackets
{
get
{
return sigPck.GetHashedSubPackets() != null
|| sigPck.GetUnhashedSubPackets() != null;
}
}
public PgpSignatureSubpacketVector GetHashedSubPackets()
{
return createSubpacketVector(sigPck.GetHashedSubPackets());
}
public PgpSignatureSubpacketVector GetUnhashedSubPackets()
{
return createSubpacketVector(sigPck.GetUnhashedSubPackets());
}
private PgpSignatureSubpacketVector createSubpacketVector(SignatureSubpacket[] pcks)
{
return pcks == null ? null : new PgpSignatureSubpacketVector(pcks);
}
public byte[] GetSignature()
{
MPInteger[] sigValues = sigPck.GetSignature();
byte[] signature;
if (sigValues != null)
{
if (sigValues.Length == 1) // an RSA signature
{
signature = sigValues[0].Value.ToByteArrayUnsigned();
}
else
{
try
{
signature = new DerSequence(
new DerInteger(sigValues[0].Value),
new DerInteger(sigValues[1].Value)).GetEncoded();
}
catch (IOException e)
{
throw new PgpException("exception encoding DSA sig.", e);
}
}
}
else
{
signature = sigPck.GetSignatureBytes();
}
return signature;
}
// TODO Handle the encoding stuff by subclassing BcpgObject?
public byte[] GetEncoded()
{
MemoryStream bOut = new MemoryStream();
Encode(bOut);
return bOut.ToArray();
}
public void Encode(
Stream outStream)
{
BcpgOutputStream bcpgOut = BcpgOutputStream.Wrap(outStream);
bcpgOut.WritePacket(sigPck);
if (trustPck != null)
{
bcpgOut.WritePacket(trustPck);
}
}
private byte[] GetEncodedPublicKey(
PgpPublicKey pubKey)
{
try
{
return pubKey.publicPk.GetEncodedContents();
}
catch (IOException e)
{
throw new PgpException("exception preparing key.", e);
}
}
}
}
| |
// 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.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Internal;
using System.Reflection.Metadata.Tests;
using Xunit;
namespace System.Reflection.PortableExecutable.Tests
{
public class DebugDirectoryTests
{
[Fact]
public void NoDebugDirectory()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream))
{
var entries = reader.ReadDebugDirectory();
Assert.Empty(entries);
}
}
[Fact]
public void CodeView()
{
var peStream = new MemoryStream(Misc.Debug);
using (var reader = new PEReader(peStream))
{
ValidateCodeView(reader);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void CodeView_Loaded()
{
LoaderUtilities.LoadPEAndValidate(Misc.Debug, ValidateCodeView);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void CodeView_Loaded_FromStream()
{
LoaderUtilities.LoadPEAndValidate(Misc.Debug, ValidateCodeView, useStream: true);
}
private void ValidateCodeView(PEReader reader)
{
// dumpbin:
//
// Debug Directories
//
// Time Type Size RVA Pointer
// -------------- - ------------------------
// 5670C4E6 cv 11C 0000230C 50C Format: RSDS, { 0C426227-31E6-4EC2-BD5F-712C4D96C0AB}, 1, C:\Temp\Debug.pdb
var cvEntry = reader.ReadDebugDirectory().Single();
Assert.Equal(DebugDirectoryEntryType.CodeView, cvEntry.Type);
Assert.False(cvEntry.IsPortableCodeView);
Assert.Equal(0x050c, cvEntry.DataPointer);
Assert.Equal(0x230c, cvEntry.DataRelativeVirtualAddress);
Assert.Equal(0x011c, cvEntry.DataSize); // includes NUL padding
Assert.Equal(0, cvEntry.MajorVersion);
Assert.Equal(0, cvEntry.MinorVersion);
Assert.Equal(0x5670c4e6u, cvEntry.Stamp);
var cv = reader.ReadCodeViewDebugDirectoryData(cvEntry);
Assert.Equal(1, cv.Age);
Assert.Equal(new Guid("0C426227-31E6-4EC2-BD5F-712C4D96C0AB"), cv.Guid);
Assert.Equal(@"C:\Temp\Debug.pdb", cv.Path);
}
[Fact]
public void Deterministic()
{
var peStream = new MemoryStream(Misc.Deterministic);
using (var reader = new PEReader(peStream))
{
ValidateDeterministic(reader);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void Deterministic_Loaded()
{
LoaderUtilities.LoadPEAndValidate(Misc.Deterministic, ValidateDeterministic);
}
private void ValidateDeterministic(PEReader reader)
{
// dumpbin:
//
// Debug Directories
//
// Time Type Size RVA Pointer
// -------- ------- -------- -------- --------
// D2FC74D3 cv 32 00002338 538 Format: RSDS, {814C578F-7676-0263-4F8A-2D3E8528EAF1}, 1, C:\Temp\Deterministic.pdb
// 00000000 repro 0 00000000 0
var entries = reader.ReadDebugDirectory();
var cvEntry = entries[0];
Assert.Equal(DebugDirectoryEntryType.CodeView, cvEntry.Type);
Assert.False(cvEntry.IsPortableCodeView);
Assert.Equal(0x0538, cvEntry.DataPointer);
Assert.Equal(0x2338, cvEntry.DataRelativeVirtualAddress);
Assert.Equal(0x0032, cvEntry.DataSize); // no NUL padding
Assert.Equal(0, cvEntry.MajorVersion);
Assert.Equal(0, cvEntry.MinorVersion);
Assert.Equal(0xD2FC74D3u, cvEntry.Stamp);
var cv = reader.ReadCodeViewDebugDirectoryData(cvEntry);
Assert.Equal(1, cv.Age);
Assert.Equal(new Guid("814C578F-7676-0263-4F8A-2D3E8528EAF1"), cv.Guid);
Assert.Equal(@"C:\Temp\Deterministic.pdb", cv.Path);
var detEntry = entries[1];
Assert.Equal(DebugDirectoryEntryType.Reproducible, detEntry.Type);
Assert.False(detEntry.IsPortableCodeView);
Assert.Equal(0, detEntry.DataPointer);
Assert.Equal(0, detEntry.DataRelativeVirtualAddress);
Assert.Equal(0, detEntry.DataSize);
Assert.Equal(0, detEntry.MajorVersion);
Assert.Equal(0, detEntry.MinorVersion);
Assert.Equal(0u, detEntry.Stamp);
Assert.Equal(2, entries.Length);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void EmbeddedPortablePdb_Loaded()
{
LoaderUtilities.LoadPEAndValidate(PortablePdbs.DocumentsEmbeddedDll, ValidateEmbeddedPortablePdb);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void EmbeddedPortablePdb_Loaded_FromStream()
{
LoaderUtilities.LoadPEAndValidate(PortablePdbs.DocumentsEmbeddedDll, ValidateEmbeddedPortablePdb, useStream: true);
}
private void ValidateEmbeddedPortablePdb(PEReader reader)
{
var entries = reader.ReadDebugDirectory();
Assert.Equal(DebugDirectoryEntryType.CodeView, entries[0].Type);
Assert.Equal(DebugDirectoryEntryType.Reproducible, entries[1].Type);
Assert.Equal(DebugDirectoryEntryType.EmbeddedPortablePdb, entries[2].Type);
var provider = reader.ReadEmbeddedPortablePdbDebugDirectoryData(entries[2]);
var pdbReader = provider.GetMetadataReader();
var document = pdbReader.GetDocument(pdbReader.Documents.First());
Assert.Equal(@"C:\Documents.cs", pdbReader.GetString(document.Name));
}
[Fact]
public void DebugDirectoryData_Errors()
{
var reader = new PEReader(new MemoryStream(Misc.Members));
Assert.Throws<ArgumentException>("entry", () => reader.ReadCodeViewDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.Coff, 0, 0, 0)));
Assert.Throws<BadImageFormatException>(() => reader.ReadCodeViewDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.CodeView, 0, 0, 0)));
Assert.Throws<ArgumentException>("entry", () => reader.ReadEmbeddedPortablePdbDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.Coff, 0, 0, 0)));
Assert.Throws<BadImageFormatException>(() => reader.ReadEmbeddedPortablePdbDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)));
}
[Fact]
public void ValidateEmbeddedPortablePdbVersion()
{
// major version (Portable PDB format):
PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0));
PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0101, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0));
PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0xffff, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0));
Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0000, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)));
Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x00ff, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)));
// minor version (Embedded blob format):
Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0101, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)));
Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0000, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)));
Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x00ff, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)));
Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0200, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)));
}
[Fact]
public void CodeView_PathPadding()
{
var bytes = ImmutableArray.Create(new byte[]
{
(byte)'R', (byte)'S', (byte)'D', (byte)'S', // signature
0x6E, 0xE6, 0x88, 0x3C, 0xB9, 0xE0, 0x08, 0x45, 0x92, 0x90, 0x11, 0xE0, 0xDB, 0x51, 0xA1, 0xC5, // GUID
0x01, 0x00, 0x00, 0x00, // age
(byte)'x', 0x00, 0x20, 0xff, // path
});
using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length))
{
Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path);
}
using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 1))
{
Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path);
}
using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 2))
{
Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path);
}
using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 3))
{
Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path);
}
using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 4))
{
Assert.Equal("", PEReader.DecodeCodeViewDebugDirectoryData(block).Path);
}
}
[Fact]
public void CodeView_Errors()
{
var bytes = ImmutableArray.Create(new byte[]
{
(byte)'R', (byte)'S', (byte)'D', (byte)'S', // signature
0x6E, 0xE6, 0x88, 0x3C, 0xB9, 0xE0, 0x08, 0x45, 0x92, 0x90, 0x11, 0xE0, 0xDB, 0x51, 0xA1, 0xC5, // GUID
0x01, 0x00, 0x00, 0x00, // age
(byte)'x', 0x00, // path
});
using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, 1))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block));
}
using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, 4))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block));
}
using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 3))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block));
}
}
[Fact]
public void EmbeddedPortablePdb_Errors()
{
var bytes1 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x42, // signature
0xFF, 0xFF, 0xFF, 0xFF, // uncompressed size
0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data
});
using (var block = new ByteArrayMemoryProvider(bytes1).GetMemoryBlock(0, bytes1.Length))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
var bytes2 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x42, // signature
0x09, 0x00, 0x00, 0x00, // uncompressed size
0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data
});
using (var block = new ByteArrayMemoryProvider(bytes2).GetMemoryBlock(0, bytes2.Length))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
var bytes3 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x42, // signature
0x00, 0x00, 0x00, 0x00, // uncompressed size
0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data
});
using (var block = new ByteArrayMemoryProvider(bytes3).GetMemoryBlock(0, bytes3.Length))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
var bytes4 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x42, // signature
0xff, 0xff, 0xff, 0x7f, // uncompressed size
0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data
});
using (var block = new ByteArrayMemoryProvider(bytes4).GetMemoryBlock(0, bytes4.Length))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
var bytes5 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x42, // signature
0x08, 0x00, 0x00, 0x00, // uncompressed size
0xEF, 0xFF, 0x4F, 0xFF, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data
});
using (var block = new ByteArrayMemoryProvider(bytes4).GetMemoryBlock(0, bytes4.Length))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
var bytes6 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x43, // signature
0x08, 0x00, 0x00, 0x00, // uncompressed size
0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data
});
using (var block = new ByteArrayMemoryProvider(bytes6).GetMemoryBlock(0, bytes6.Length))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
var bytes7 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x43, // signature
0x08, 0x00, 0x00,
});
using (var block = new ByteArrayMemoryProvider(bytes7).GetMemoryBlock(0, bytes7.Length))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
var bytes8 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x43, // signature
0x08, 0x00, 0x00,
});
using (var block = new ByteArrayMemoryProvider(bytes8).GetMemoryBlock(0, bytes8.Length))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
var bytes9 = ImmutableArray.Create(new byte[]
{
0x4D, 0x50, 0x44, 0x43, // signature
0x08, 0x00, 0x00, 0x00
});
using (var block = new ByteArrayMemoryProvider(bytes9).GetMemoryBlock(0, 1))
{
Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block));
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SingleObjectTransfer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.File;
/// <summary>
/// Represents a single object transfer operation.
/// </summary>
#if BINARY_SERIALIZATION
[Serializable]
#else
[KnownType(typeof(AzureBlobDirectoryLocation))]
[KnownType(typeof(AzureBlobLocation))]
[KnownType(typeof(AzureFileDirectoryLocation))]
[KnownType(typeof(AzureFileLocation))]
[KnownType(typeof(DirectoryLocation))]
[KnownType(typeof(FileLocation))]
[KnownType(typeof(StreamLocation))]
// StreamLocation intentionally omitted because it is not serializable
[KnownType(typeof(UriLocation))]
[DataContract]
#endif // BINARY_SERIALIZATION
internal class SingleObjectTransfer : Transfer
{
private const string TransferJobName = "TransferJob";
private const string ShouldTransferCheckedName = "ShouldTransferChecked";
/// <summary>
/// Internal transfer job.
/// </summary>
#if !BINARY_SERIALIZATION
[DataMember]
#endif
private TransferJob transferJob;
private bool shouldTransferChecked = false;
/// <summary>
/// Initializes a new instance of the <see cref="SingleObjectTransfer"/> class.
/// This constructor will check whether source and destination is valid for the operation:
/// Uri is only valid for non-staging copy.
/// cannot copy from local file/stream to local file/stream
/// </summary>
/// <param name="source">Transfer source.</param>
/// <param name="dest">Transfer destination.</param>
/// <param name="transferMethod">Transfer method, see <see cref="TransferMethod"/> for detail available methods.</param>
public SingleObjectTransfer(TransferLocation source, TransferLocation dest, TransferMethod transferMethod)
: base(source, dest, transferMethod)
{
Debug.Assert(source != null && dest != null);
Debug.Assert(
source.Type == TransferLocationType.FilePath || source.Type == TransferLocationType.Stream ||
source.Type == TransferLocationType.AzureBlob || source.Type == TransferLocationType.AzureFile ||
source.Type == TransferLocationType.SourceUri);
Debug.Assert(
dest.Type == TransferLocationType.FilePath || dest.Type == TransferLocationType.Stream ||
dest.Type == TransferLocationType.AzureBlob || dest.Type == TransferLocationType.AzureFile ||
dest.Type == TransferLocationType.SourceUri);
Debug.Assert(!((source.Type == TransferLocationType.FilePath || source.Type == TransferLocationType.Stream) &&
(dest.Type == TransferLocationType.FilePath || dest.Type == TransferLocationType.Stream)));
if (source.Type == TransferLocationType.AzureBlob && dest.Type == TransferLocationType.AzureBlob)
{
CloudBlob sourceBlob = (source as AzureBlobLocation).Blob;
CloudBlob destBlob = (dest as AzureBlobLocation).Blob;
if (sourceBlob.BlobType != destBlob.BlobType)
{
throw new InvalidOperationException(Resources.SourceAndDestinationBlobTypeDifferent);
}
if (StorageExtensions.Equals(sourceBlob, destBlob))
{
throw new InvalidOperationException(Resources.SourceAndDestinationLocationCannotBeEqualException);
}
}
if (source.Type == TransferLocationType.AzureFile && dest.Type == TransferLocationType.AzureFile)
{
CloudFile sourceFile = (source as AzureFileLocation).AzureFile;
CloudFile destFile = (dest as AzureFileLocation).AzureFile;
if (string.Equals(sourceFile.SnapshotQualifiedUri.Host, destFile.SnapshotQualifiedUri.Host, StringComparison.OrdinalIgnoreCase) &&
string.Equals(sourceFile.SnapshotQualifiedUri.PathAndQuery, destFile.SnapshotQualifiedUri.PathAndQuery, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(Resources.SourceAndDestinationLocationCannotBeEqualException);
}
}
this.transferJob = new TransferJob(this);
}
#if !BINARY_SERIALIZATION
/// <summary>
/// Initializes a deserialized SingleObjectTransfer
/// </summary>
/// <param name="context"></param>
[OnDeserialized]
private void OnDeserializedCallback(StreamingContext context)
{
this.transferJob.Transfer = this;
}
#endif
#if BINARY_SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="SingleObjectTransfer"/> class.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected SingleObjectTransfer(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.transferJob = (TransferJob)info.GetValue(TransferJobName, typeof(TransferJob));
this.shouldTransferChecked = info.GetBoolean(ShouldTransferCheckedName);
this.transferJob.Transfer = this;
}
#endif // BINARY_SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="SingleObjectTransfer"/> class.
/// </summary>
/// <param name="other">Another <see cref="SingleObjectTransfer"/> object. </param>
private SingleObjectTransfer(SingleObjectTransfer other)
: base(other)
{
this.ProgressTracker = other.ProgressTracker.Copy();
this.transferJob = other.transferJob.Copy();
this.transferJob.Transfer = this;
}
#if BINARY_SERIALIZATION
/// <summary>
/// Serializes the object.
/// </summary>
/// <param name="info">Serialization info object.</param>
/// <param name="context">Streaming context.</param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(TransferJobName, this.transferJob, typeof(TransferJob));
info.AddValue(ShouldTransferCheckedName, this.shouldTransferChecked);
}
#endif // BINARY_SERIALIZATION
public bool ShouldTransferChecked
{
get
{
return this.shouldTransferChecked;
}
set
{
this.shouldTransferChecked = value;
}
}
public AzureFileDirectorySDDLCache SDDLCache
{
get;
set;
}
/// <summary>
/// Creates a copy of current transfer object.
/// </summary>
/// <returns>A copy of current transfer object.</returns>
public override Transfer Copy()
{
return new SingleObjectTransfer(this);
}
public void UpdateProgressLock(ReaderWriterLockSlim uploadLock)
{
this.transferJob.ProgressUpdateLock = uploadLock;
}
/// <summary>
/// Execute the transfer asynchronously.
/// </summary>
/// <param name="scheduler">Transfer scheduler</param>
/// <param name="cancellationToken">Token that can be used to cancel the transfer.</param>
/// <returns>A task representing the transfer operation.</returns>
public override async Task ExecuteAsync(TransferScheduler scheduler, CancellationToken cancellationToken)
{
if (this.transferJob.Status == TransferJobStatus.Finished ||
this.transferJob.Status == TransferJobStatus.Skipped)
{
return;
}
TransferEventArgs eventArgs = new TransferEventArgs(this.Source.Instance, this.Destination.Instance);
eventArgs.StartTime = DateTime.UtcNow;
if (this.transferJob.Status == TransferJobStatus.Failed)
{
// Resuming a failed transfer job
if (string.IsNullOrEmpty(this.transferJob.CopyId))
{
this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Transfer);
}
else
{
this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Monitor);
}
}
try
{
await scheduler.ExecuteJobAsync(this.transferJob, cancellationToken);
if (TransferJobStatus.SkippedDueToShouldNotTransfer != this.transferJob.Status)
{
eventArgs.EndTime = DateTime.UtcNow;
this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Finished);
if (this.Context != null)
{
this.Context.OnTransferSuccess(eventArgs);
}
}
}
catch (TransferException exception)
{
eventArgs.EndTime = DateTime.UtcNow;
eventArgs.Exception = exception;
if (exception.ErrorCode == TransferErrorCode.NotOverwriteExistingDestination)
{
// transfer skipped
this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Skipped);
if (this.Context != null)
{
this.Context.OnTransferSkipped(eventArgs);
}
throw;
}
else if (exception.ErrorCode == TransferErrorCode.FailedCheckingShouldTransfer)
{
throw;
}
else
{
this.OnTransferFailed(eventArgs);
throw;
}
}
catch (Exception ex)
{
eventArgs.EndTime = DateTime.UtcNow;
eventArgs.Exception = ex;
this.OnTransferFailed(eventArgs);
throw;
}
this.Journal?.RemoveTransfer(this);
}
public void OnTransferFailed(Exception ex)
{
TransferEventArgs eventArgs = new TransferEventArgs(this.Source.Instance, this.Destination.Instance);
eventArgs.StartTime = DateTime.UtcNow;
eventArgs.EndTime = DateTime.UtcNow;
eventArgs.Exception = ex;
this.OnTransferFailed(eventArgs);
}
private void OnTransferFailed(TransferEventArgs eventArgs)
{
// transfer failed
this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Failed);
if (this.Context != null)
{
this.Context.OnTransferFailed(eventArgs);
}
}
public bool IsValid()
{
if(Source is FileLocation
&& (Source as FileLocation).RelativePath != null
&& (Source as FileLocation).RelativePath.Length > Constants.MaxRelativePathLength)
{
return false;
}
return true;
}
}
}
| |
<?cs # THIS CREATES A CLASS OR INTERFACE PAGE FROM .java FILES ?>
<?cs include:"macros.cs" ?>
<?cs include:"macros_override.cs" ?>
<?cs
####################
# MACRO FUNCTION USED ONLY IN THIS TEMPLATE TO GENERATE API REFERENCE
# FIRST, THE FUNCTIONS FOR THE SUMMARY AT THE TOP OF THE PAGE
####################
?>
<?cs
# Prints the table cells for the summary of methods.
?><?cs def:write_method_summary(methods, included) ?>
<?cs set:count = #1 ?>
<?cs each:method = methods ?>
<?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?>
<tr class="api apilevel-<?cs var:method.since ?>" >
<?cs # leave out this cell if there is no return type = if constructors ?>
<?cs if:subcount(method.returnType) ?>
<td><code>
<?cs var:method.abstract ?>
<?cs var:method.default ?>
<?cs var:method.static ?>
<?cs var:method.final ?>
<?cs call:type_link(method.generic) ?>
<?cs call:type_link(method.returnType) ?></code>
</td>
<?cs /if ?>
<td width="100%">
<code>
<?cs call:cond_link(method.name, toroot, method.href, included) ?>(<?cs call:parameter_list(method.params, 0) ?>)
</code>
<?cs if:subcount(method.shortDescr) || subcount(method.deprecated) ?>
<p><?cs call:short_descr(method) ?>
<?cs call:show_annotations_list(method) ?></p>
<?cs /if ?>
</td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs
# Print the table cells for the summary of fields.
?><?cs def:write_field_summary(fields, included) ?>
<?cs set:count = #1 ?>
<?cs each:field=fields ?>
<tr class="api apilevel-<?cs var:field.since ?>" >
<td><code>
<?cs var:field.scope ?>
<?cs var:field.static ?>
<?cs var:field.final ?>
<?cs call:type_link(field.type) ?></code></td>
<td width="100%">
<code><?cs call:cond_link(field.name, toroot, field.href, included) ?></code>
<p><?cs call:short_descr(field) ?>
<?cs call:show_annotations_list(field) ?></p>
</td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs
# Print the table cells for the summary of constants
?><?cs def:write_constant_summary(fields, included) ?>
<?cs set:count = #1 ?>
<?cs each:field=fields ?>
<tr class="api apilevel-<?cs var:field.since ?>" >
<td><code><?cs call:type_link(field.type) ?></code></td>
<td width="100%">
<code><?cs call:cond_link(field.name, toroot, field.href, included) ?></code>
<p><?cs call:short_descr(field) ?>
<?cs call:show_annotations_list(field) ?></p>
</td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs
# Print the table cells for the summary of attributes
?><?cs def:write_attr_summary(attrs, included) ?>
<?cs set:count = #1 ?>
<?cs each:attr=attrs ?>
<tr class="api apilevel-<?cs var:attr.since ?>" >
<td><?cs if:included ?><a href="<?cs var:toroot ?><?cs var:attr.href ?>"><?cs /if
?><code><?cs var:attr.name ?></code><?cs if:included ?></a><?cs /if ?></td>
<td width="100%">
<?cs call:short_descr(attr) ?>
<?cs call:show_annotations_list(attr) ?>
</td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs
# Print the table cells for the inner classes
?><?cs def:write_inners_summary(classes) ?>
<?cs set:count = #1 ?>
<?cs each:cl=class.inners ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td class="jd-typecol"><code>
<?cs var:cl.scope ?>
<?cs var:cl.static ?>
<?cs var:cl.final ?>
<?cs var:cl.abstract ?>
<?cs var:cl.kind ?></code></td>
<td class="jd-descrcol" width="100%">
<code><?cs call:type_link(cl.type) ?></code>
<p><?cs call:short_descr(cl) ?>
<?cs call:show_annotations_list(cl) ?></p>
</td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs
###################
# END OF FUNCTIONS FOR API SUMMARY
# START OF FUNCTIONS FOR THE API DETAILS
###################
?>
<?cs
# Print the table cells for the summary of constants
?>
<?cs def:write_field_details(fields) ?>
<?cs each:field=fields ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?>
<A NAME="<?cs var:field.anchor ?>"></A>
<?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?>
<div class="api apilevel-<?cs var:field.since ?>">
<h3 class="api-name"><?cs var:field.name ?></h3>
<div class="api-level">
<?cs call:since_tags(field) ?>
<?cs call:federated_refs(field) ?>
</div>
<pre class="api-signature no-pretty-print">
<?cs if:subcount(field.scope) ?><?cs var:field.scope
?> <?cs /if ?><?cs if:subcount(field.static) ?><?cs var:field.static
?> <?cs /if ?><?cs if:subcount(field.final) ?><?cs var:field.final
?> <?cs /if ?><?cs if:subcount(field.type) ?><?cs call:type_link(field.type)
?> <?cs /if ?><?cs var:field.name ?></pre>
<?cs call:show_annotations_list(field) ?>
<?cs call:description(field) ?>
<?cs if:subcount(field.constantValue) ?>
<p>Constant Value:
<?cs if:field.constantValue.isString ?>
<?cs var:field.constantValue.str ?>
<?cs else ?>
<?cs var:field.constantValue.dec ?>
(<?cs var:field.constantValue.hex ?>)
<?cs /if ?>
<?cs /if ?>
</div>
<?cs /each ?>
<?cs /def ?>
<?cs def:write_method_details(methods) ?>
<?cs each:method=methods ?>
<?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?>
<A NAME="<?cs var:method.anchor ?>"></A>
<?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?>
<div class="api apilevel-<?cs var:method.since ?>">
<h3 class="api-name"><?cs var:method.name ?></h3>
<div class="api-level">
<div><?cs call:since_tags(method) ?></div>
<?cs call:federated_refs(method) ?>
</div>
<pre class="api-signature no-pretty-print">
<?cs if:subcount(method.scope) ?><?cs var:method.scope
?> <?cs /if ?><?cs if:subcount(method.static) ?><?cs var:method.static
?> <?cs /if ?><?cs if:subcount(method.final) ?><?cs var:method.final
?> <?cs /if ?><?cs if:subcount(method.abstract) ?><?cs var:method.abstract
?> <?cs /if ?><?cs if:subcount(method.returnType) ?><?cs call:type_link(method.returnType)
?> <?cs /if ?><?cs var:method.name ?> (<?cs call:parameter_list(method.params, 1) ?>)</pre>
<?cs call:show_annotations_list(method) ?>
<?cs call:description(method) ?>
</div>
<?cs /each ?>
<?cs /def ?>
<?cs def:write_attr_details(attrs) ?>
<?cs each:attr=attrs ?>
<?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?>
<A NAME="<?cs var:attr.anchor ?>"></A>
<h3 class="api-name"><?cs var:attr.name ?></h3>
<?cs call:show_annotations_list(attr) ?>
<?cs call:description(attr) ?>
<?cs if:subcount(attr.methods) ?>
<p><b>Related methods:</b></p>
<ul class="nolist">
<?cs each:m=attr.methods ?>
<li><a href="<?cs var:toroot ?><?cs var:m.href ?>"><?cs var:m.name ?></a></li>
<?cs /each ?>
</ul>
<?cs /if ?>
<?cs /each ?>
<?cs /def ?>
<?cs
#########################
# END OF MACROS
# START OF PAGE PRINTING
#########################
?>
<?cs include:"doctype.cs" ?>
<html<?cs if:devsite ?> devsite<?cs /if ?>>
<?cs include:"head_tag.cs" ?>
<?cs include:"body_tag.cs" ?>
<?cs include:"header.cs" ?>
<?cs include:"page_info.cs" ?>
<?cs # This DIV spans the entire document to provide scope for some scripts ?>
<div class="api apilevel-<?cs var:class.since ?>" id="jd-content">
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ======== START OF CLASS DATA ======== -->
<?cs
#
# Page header with class name and signature
#
?>
<h1 class="api-title"><?cs var:class.name ?></h1>
<p>
<code class="api-signature">
<?cs var:class.scope ?>
<?cs var:class.static ?>
<?cs var:class.final ?>
<?cs var:class.abstract ?>
<?cs var:class.kind ?>
<?cs var:class.name ?>
</code>
<br>
<?cs set:colspan = subcount(class.inheritance) ?>
<?cs each:supr = class.inheritance ?>
<code class="api-signature">
<?cs if:colspan == 2 ?>
extends <?cs call:type_link(supr.short_class) ?>
<?cs /if ?>
<?cs if:last(supr) && subcount(supr.interfaces) ?>
implements
<?cs each:t=supr.interfaces ?>
<?cs call:type_link(t) ?><?cs
if: name(t)!=subcount(supr.interfaces)-1
?>, <?cs /if ?>
<?cs /each ?>
<?cs /if ?>
<?cs set:colspan = colspan-1 ?>
</code>
<?cs /each ?>
</p><?cs
#
# Class inheritance tree
#
?><table class="jd-inheritance-table">
<?cs set:colspan = subcount(class.inheritance) ?>
<?cs each:supr = class.inheritance ?>
<tr>
<?cs loop:i = 1, (subcount(class.inheritance)-colspan), 1 ?>
<td class="jd-inheritance-space"> <?cs
if:(subcount(class.inheritance)-colspan) == i
?> ↳<?cs
/if ?></td>
<?cs /loop ?>
<td colspan="<?cs var:colspan ?>" class="jd-inheritance-class-cell"><?cs
if:colspan == 1
?><?cs call:class_name(class.qualifiedType) ?><?cs
else
?><?cs call:type_link(supr.class) ?><?cs
/if ?>
</td>
</tr>
<?cs set:colspan = colspan-1 ?>
<?cs /each ?>
</table><?cs
#
# Collapsible list of subclasses
#
?><?cs
if:subcount(class.subclasses.direct) && !class.subclasses.hidden ?>
<table class="jd-sumtable jd-sumtable-subclasses">
<tr><td style="border:none;margin:0;padding:0;">
<?cs call:expando_trigger("subclasses-direct", "closed") ?>Known Direct Subclasses
<?cs call:expandable_class_list("subclasses-direct", class.subclasses.direct, "list") ?>
</td></tr>
</table>
<?cs /if ?>
<?cs if:subcount(class.subclasses.indirect) && !class.subclasses.hidden ?>
<table class="jd-sumtable jd-sumtable-subclasses"><tr><td colspan="2" style="border:none;margin:0;padding:0;">
<?cs call:expando_trigger("subclasses-indirect", "closed") ?>Known Indirect Subclasses
<?cs call:expandable_class_list("subclasses-indirect", class.subclasses.indirect, "list") ?>
</td></tr></table><?cs
/if ?>
<?cs call:show_annotations_list(class) ?>
<br><hr><?cs
#
# The long-form class description.
#
?><?cs call:deprecated_warning(class) ?>
<?cs if:subcount(class.descr) ?>
<p><?cs call:tag_list(class.descr) ?></p>
<?cs /if ?>
<?cs call:see_also_tags(class.seeAlso) ?>
<?cs
#################
# CLASS SUMMARY
#################
?>
<?cs # make sure there is a summary view to display ?>
<?cs if:subcount(class.inners)
|| subcount(class.attrs)
|| inhattrs
|| subcount(class.enumConstants)
|| subcount(class.constants)
|| inhconstants
|| subcount(class.fields)
|| inhfields
|| subcount(class.ctors.public)
|| subcount(class.ctors.protected)
|| subcount(class.methods.public)
|| subcount(class.methods.protected)
|| inhmethods ?>
<h2 class="api-section">Summary</h2>
<?cs if:subcount(class.inners) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ======== NESTED CLASS SUMMARY ======== -->
<table id="nestedclasses" class="responsive">
<tr><th colspan="2"><h3>Nested classes</h3></th></tr>
<?cs call:write_inners_summary(class.inners) ?>
<?cs /if ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<?cs if:subcount(class.attrs) ?>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lattrs" class="responsive">
<tr><th colspan="2"><h3>XML attributes</h3></th></tr>
<?cs call:write_attr_summary(class.attrs, 1) ?>
<?cs /if ?>
<?cs # if there are inherited attrs, write the table ?>
<?cs if:inhattrs ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== FIELD SUMMARY =========== -->
<table id="inhattrs" class="responsive inhtable">
<tr><th><h3>Inherited XML attributes</h3></th></tr>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.attrs) ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td colspan="2">
<?cs call:expando_trigger("inherited-attrs-"+cl.qualified, "closed") ?>From
<?cs var:cl.kind ?>
<code>
<?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?>
</code>
<div id="inherited-attrs-<?cs var:cl.qualified ?>">
<div id="inherited-attrs-<?cs var:cl.qualified ?>-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-attrs-<?cs var:cl.qualified ?>-summary" style="display: none;">
<table class="jd-sumtable-expando">
<?cs call:write_attr_summary(cl.attrs, cl.included) ?></table>
</div>
</div>
</td></tr>
<?cs /if ?>
<?cs /each ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.enumConstants) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="enumconstants" class="responsive constants">
<tr><th colspan="2"><h3>Enum values</h3></th></tr>
<?cs set:count = #1 ?>
<?cs each:field=class.enumConstants ?>
<tr class="api apilevel-<?cs var:field.since ?>" >
<td><code><?cs call:type_link(field.type) ?></code> </td>
<td width="100%">
<code><?cs call:cond_link(field.name, toroot, field.href, cl.included) ?></code>
<p><?cs call:short_descr(field) ?>
<?cs call:show_annotations_list(field) ?></p>
</td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /if ?>
<?cs if:subcount(class.constants) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="constants" class="responsive constants">
<tr><th colspan="2"><h3>Constants</h3></th></tr>
<?cs call:write_constant_summary(class.constants, 1) ?>
</table>
<?cs /if ?>
<?cs # if there are inherited constants, write the table ?>
<?cs if:inhconstants ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="inhconstants" class="responsive constants inhtable">
<tr><th><h3>Inherited constants</h3></th></tr>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.constants) ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td>
<?cs call:expando_trigger("inherited-constants-"+cl.qualified, "closed") ?>From
<?cs var:cl.kind ?>
<code>
<?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?>
</code>
<div id="inherited-constants-<?cs var:cl.qualified ?>">
<div id="inherited-constants-<?cs var:cl.qualified ?>-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-<?cs var:cl.qualified ?>-summary" style="display: none;">
<table class="jd-sumtable-expando responsive">
<?cs call:write_constant_summary(cl.constants, cl.included) ?></table>
</div>
</div>
</td></tr>
<?cs /if ?>
<?cs /each ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.fields) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="responsive properties">
<tr><th colspan="2"><h3>Fields</h3></th></tr>
<?cs call:write_field_summary(class.fields, 1) ?>
</table>
<?cs /if ?>
<?cs # if there are inherited fields, write the table ?>
<?cs if:inhfields ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== FIELD SUMMARY =========== -->
<table id="inhfields" class="properties inhtable">
<tr><th><h3>Inherited fields</h3></th></tr>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.fields) ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td>
<?cs call:expando_trigger("inherited-fields-"+cl.qualified, "closed") ?>From
<?cs var:cl.kind ?>
<code>
<?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?>
</code>
<div id="inherited-fields-<?cs var:cl.qualified ?>">
<div id="inherited-fields-<?cs var:cl.qualified ?>-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-fields-<?cs var:cl.qualified ?>-summary" style="display: none;">
<table class="jd-sumtable-expando responsive">
<?cs call:write_field_summary(cl.fields, cl.included) ?></table>
</div>
</div>
</td></tr>
<?cs /if ?>
<?cs /each ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.ctors.public) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="responsive constructors">
<tr><th colspan="2"><h3>Public constructors</h3></th></tr>
<?cs call:write_method_summary(class.ctors.public, 1) ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.ctors.protected) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="proctors" class="responsive constructors">
<tr><th colspan="2"><h3>Protected constructors</h3></th></tr>
<?cs call:write_method_summary(class.ctors.protected, 1) ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.methods.public) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="responsive methods">
<tr><th colspan="2"><h3>Public methods</h3></th></tr>
<?cs call:write_method_summary(class.methods.public, 1) ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.methods.protected) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========== METHOD SUMMARY =========== -->
<table id="promethods" class="reponsive methods">
<tr><th colspan="2"><h3>Protected methods</h3></th></tr>
<?cs call:write_method_summary(class.methods.protected, 1) ?>
</table>
<?cs /if ?>
<?cs # if there are inherited methods, write the table ?>
<?cs if:inhmethods ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="methods inhtable">
<tr><th><h3>Inherited methods</h3></th></tr>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.methods) ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td colspan="2">
<?cs call:expando_trigger("inherited-methods-"+cl.qualified, "closed") ?>From
<?cs var:cl.kind ?>
<code>
<?cs if:cl.included ?>
<a href="<?cs var:toroot ?><?cs var:cl.link ?>"><?cs var:cl.qualified ?></a>
<?cs elif:cl.federated ?>
<a href="<?cs var:cl.link ?>"><?cs var:cl.qualified ?></a>
<?cs else ?>
<?cs var:cl.qualified ?>
<?cs /if ?>
</code>
<div id="inherited-methods-<?cs var:cl.qualified ?>">
<div id="inherited-methods-<?cs var:cl.qualified ?>-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-<?cs var:cl.qualified ?>-summary" style="display: none;">
<table class="jd-sumtable-expando responsive">
<?cs call:write_method_summary(cl.methods, cl.included) ?>
</table>
</div>
</div>
</td></tr>
<?cs /if ?>
<?cs /each ?>
</table>
<?cs /if ?>
<?cs /if ?>
<?cs
################
# CLASS DETAILS
################
?>
<!-- XML Attributes -->
<?cs if:subcount(class.attrs) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= FIELD DETAIL ======== -->
<h2 class="api-section">XML attributes</h2>
<?cs call:write_attr_details(class.attrs) ?>
<?cs /if ?>
<!-- Enum Values -->
<?cs if:subcount(class.enumConstants) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= ENUM CONSTANTS DETAIL ======== -->
<h2 class="api-section">Enum values</h2>
<?cs call:write_field_details(class.enumConstants) ?>
<?cs /if ?>
<!-- Constants -->
<?cs if:subcount(class.constants) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= ENUM CONSTANTS DETAIL ======== -->
<h2 class="api-section">Constants</h2>
<?cs call:write_field_details(class.constants) ?>
<?cs /if ?>
<!-- Fields -->
<?cs if:subcount(class.fields) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= FIELD DETAIL ======== -->
<h2 class="api-section">Fields</h2>
<?cs call:write_field_details(class.fields) ?>
<?cs /if ?>
<!-- Public ctors -->
<?cs if:subcount(class.ctors.public) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2 class="api-section">Public constructors</h2>
<?cs call:write_method_details(class.ctors.public) ?>
<?cs /if ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<?cs if:subcount(class.ctors.protected) ?>
<h2 class="api-section">Protected constructors</h2>
<?cs call:write_method_details(class.ctors.protected) ?>
<?cs /if ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<?cs if:subcount(class.methods.public) ?>
<h2 class="api-section">Public methods</h2>
<?cs call:write_method_details(class.methods.public) ?>
<?cs /if ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= METHOD DETAIL ======== -->
<?cs if:subcount(class.methods.protected) ?>
<h2 class="api-section">Protected methods</h2>
<?cs call:write_method_details(class.methods.protected) ?>
<?cs /if ?>
<?cs # the next two lines must be exactly like this to be parsed by eclipse ?>
<!-- ========= END OF CLASS DATA ========= -->
</div><!-- end jd-content -->
<?cs if:devsite ?>
<div class="data-reference-resources-wrapper">
<?cs if:subcount(class.package) ?>
<ul data-reference-resources>
<?cs call:list("Annotations", class.package.annotations) ?>
<?cs call:list("Interfaces", class.package.interfaces) ?>
<?cs call:list("Classes", class.package.classes) ?>
<?cs call:list("Enums", class.package.enums) ?>
<?cs call:list("Exceptions", class.package.exceptions) ?>
<?cs call:list("Errors", class.package.errors) ?>
</ul>
<?cs elif:subcount(package) ?>
<ul data-reference-resources>
<?cs call:class_link_list("Annotations", package.annotations) ?>
<?cs call:class_link_list("Interfaces", package.interfaces) ?>
<?cs call:class_link_list("Classes", package.classes) ?>
<?cs call:class_link_list("Enums", package.enums) ?>
<?cs call:class_link_list("Exceptions", package.exceptions) ?>
<?cs call:class_link_list("Errors", package.errors) ?>
</ul>
<?cs /if ?>
</div>
<?cs /if ?>
<?cs if:!devsite ?>
<?cs include:"footer.cs" ?>
<?cs include:"trailer.cs" ?>
<?cs /if ?>
</body>
</html>
| |
/*
* Swagger Petstore
*
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using IO.Swagger.Attributes;
using IO.Swagger.Models;
namespace IO.Swagger.Controllers
{
/// <summary>
///
/// </summary>
public class PetApiController : Controller
{
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name="body">Pet object that needs to be added to the store</param>
/// <response code="405">Invalid input</response>
[HttpPost]
[Route("/v2/pet")]
[ValidateModelState]
[SwaggerOperation("AddPet")]
public virtual IActionResult AddPet([FromBody]Pet body)
{
//TODO: Uncomment the next line to return response 405 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(405);
throw new NotImplementedException();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name="petId">Pet id to delete</param>
/// <param name="apiKey"></param>
/// <response code="400">Invalid ID supplied</response>
/// <response code="404">Pet not found</response>
[HttpDelete]
[Route("/v2/pet/{petId}")]
[ValidateModelState]
[SwaggerOperation("DeletePet")]
public virtual IActionResult DeletePet([FromRoute][Required]long? petId, [FromHeader]string apiKey)
{
//TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(400);
//TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(404);
throw new NotImplementedException();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>Multiple status values can be provided with comma separated strings</remarks>
/// <param name="status">Status values that need to be considered for filter</param>
/// <response code="200">successful operation</response>
/// <response code="400">Invalid status value</response>
[HttpGet]
[Route("/v2/pet/findByStatus")]
[ValidateModelState]
[SwaggerOperation("FindPetsByStatus")]
[SwaggerResponse(statusCode: 200, type: typeof(List<Pet>), description: "successful operation")]
public virtual IActionResult FindPetsByStatus([FromQuery][Required()]List<string> status)
{
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(200, default(List<Pet>));
//TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(400);
string exampleJson = null;
exampleJson = "<Pet>\n <id>123456789</id>\n <name>doggie</name>\n <photoUrls>\n <photoUrls>aeiou</photoUrls>\n </photoUrls>\n <tags>\n </tags>\n <status>aeiou</status>\n</Pet>";
exampleJson = "[ {\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}, {\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n} ]";
var example = exampleJson != null
? JsonConvert.DeserializeObject<List<Pet>>(exampleJson)
: default(List<Pet>);
//TODO: Change the data returned
return new ObjectResult(example);
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.</remarks>
/// <param name="tags">Tags to filter by</param>
/// <response code="200">successful operation</response>
/// <response code="400">Invalid tag value</response>
[HttpGet]
[Route("/v2/pet/findByTags")]
[ValidateModelState]
[SwaggerOperation("FindPetsByTags")]
[SwaggerResponse(statusCode: 200, type: typeof(List<Pet>), description: "successful operation")]
public virtual IActionResult FindPetsByTags([FromQuery][Required()]List<string> tags)
{
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(200, default(List<Pet>));
//TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(400);
string exampleJson = null;
exampleJson = "<Pet>\n <id>123456789</id>\n <name>doggie</name>\n <photoUrls>\n <photoUrls>aeiou</photoUrls>\n </photoUrls>\n <tags>\n </tags>\n <status>aeiou</status>\n</Pet>";
exampleJson = "[ {\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}, {\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n} ]";
var example = exampleJson != null
? JsonConvert.DeserializeObject<List<Pet>>(exampleJson)
: default(List<Pet>);
//TODO: Change the data returned
return new ObjectResult(example);
}
/// <summary>
/// Find pet by ID
/// </summary>
/// <remarks>Returns a single pet</remarks>
/// <param name="petId">ID of pet to return</param>
/// <response code="200">successful operation</response>
/// <response code="400">Invalid ID supplied</response>
/// <response code="404">Pet not found</response>
[HttpGet]
[Route("/v2/pet/{petId}")]
[ValidateModelState]
[SwaggerOperation("GetPetById")]
[SwaggerResponse(statusCode: 200, type: typeof(Pet), description: "successful operation")]
public virtual IActionResult GetPetById([FromRoute][Required]long? petId)
{
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(200, default(Pet));
//TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(400);
//TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(404);
string exampleJson = null;
exampleJson = "<Pet>\n <id>123456789</id>\n <name>doggie</name>\n <photoUrls>\n <photoUrls>aeiou</photoUrls>\n </photoUrls>\n <tags>\n </tags>\n <status>aeiou</status>\n</Pet>";
exampleJson = "{\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}";
var example = exampleJson != null
? JsonConvert.DeserializeObject<Pet>(exampleJson)
: default(Pet);
//TODO: Change the data returned
return new ObjectResult(example);
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name="body">Pet object that needs to be added to the store</param>
/// <response code="400">Invalid ID supplied</response>
/// <response code="404">Pet not found</response>
/// <response code="405">Validation exception</response>
[HttpPut]
[Route("/v2/pet")]
[ValidateModelState]
[SwaggerOperation("UpdatePet")]
public virtual IActionResult UpdatePet([FromBody]Pet body)
{
//TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(400);
//TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(404);
//TODO: Uncomment the next line to return response 405 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(405);
throw new NotImplementedException();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name="petId">ID of pet that needs to be updated</param>
/// <param name="name">Updated name of the pet</param>
/// <param name="status">Updated status of the pet</param>
/// <response code="405">Invalid input</response>
[HttpPost]
[Route("/v2/pet/{petId}")]
[ValidateModelState]
[SwaggerOperation("UpdatePetWithForm")]
public virtual IActionResult UpdatePetWithForm([FromRoute][Required]long? petId, [FromForm]string name, [FromForm]string status)
{
//TODO: Uncomment the next line to return response 405 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(405);
throw new NotImplementedException();
}
/// <summary>
/// uploads an image
/// </summary>
/// <param name="petId">ID of pet to update</param>
/// <param name="additionalMetadata">Additional data to pass to server</param>
/// <param name="file">file to upload</param>
/// <response code="200">successful operation</response>
[HttpPost]
[Route("/v2/pet/{petId}/uploadImage")]
[ValidateModelState]
[SwaggerOperation("UploadFile")]
[SwaggerResponse(statusCode: 200, type: typeof(ApiResponse), description: "successful operation")]
public virtual IActionResult UploadFile([FromRoute][Required]long? petId, [FromForm]string additionalMetadata, [FromForm]System.IO.Stream file)
{
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(200, default(ApiResponse));
string exampleJson = null;
exampleJson = "{\n \"code\" : 0,\n \"type\" : \"type\",\n \"message\" : \"message\"\n}";
var example = exampleJson != null
? JsonConvert.DeserializeObject<ApiResponse>(exampleJson)
: default(ApiResponse);
//TODO: Change the data returned
return new ObjectResult(example);
}
}
}
| |
// 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.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net
{
/// <summary>
/// <para>Acts as countdown timer, used to measure elapsed time over a sync operation.</para>
/// </summary>
internal static class TimerThread
{
/// <summary>
/// <para>Represents a queue of timers, which all have the same duration.</para>
/// </summary>
internal abstract class Queue
{
private readonly int _durationMilliseconds;
internal Queue(int durationMilliseconds)
{
_durationMilliseconds = durationMilliseconds;
}
/// <summary>
/// <para>The duration in milliseconds of timers in this queue.</para>
/// </summary>
internal int Duration => _durationMilliseconds;
/// <summary>
/// <para>Creates and returns a handle to a new timer with attached context.</para>
/// </summary>
internal abstract Timer CreateTimer(Callback callback, object context);
}
/// <summary>
/// <para>Represents a timer and provides a mechanism to cancel.</para>
/// </summary>
internal abstract class Timer : IDisposable
{
private readonly int _startTimeMilliseconds;
private readonly int _durationMilliseconds;
internal Timer(int durationMilliseconds)
{
_durationMilliseconds = durationMilliseconds;
_startTimeMilliseconds = Environment.TickCount;
}
/// <summary>
/// <para>The time (relative to Environment.TickCount) when the timer started.</para>
/// </summary>
internal int StartTime => _startTimeMilliseconds;
/// <summary>
/// <para>The time (relative to Environment.TickCount) when the timer will expire.</para>
/// </summary>
internal int Expiration => unchecked(_startTimeMilliseconds + _durationMilliseconds);
/// <summary>
/// <para>Cancels the timer. Returns true if the timer hasn't and won't fire; false if it has or will.</para>
/// </summary>
internal abstract bool Cancel();
/// <summary>
/// <para>Whether or not the timer has expired.</para>
/// </summary>
internal abstract bool HasExpired { get; }
public void Dispose() => Cancel();
}
/// <summary>
/// <para>Prototype for the callback that is called when a timer expires.</para>
/// </summary>
internal delegate void Callback(Timer timer, int timeNoticed, object context);
private const int ThreadIdleTimeoutMilliseconds = 30 * 1000;
private const int CacheScanPerIterations = 32;
private const int TickCountResolution = 15;
private static readonly LinkedList<WeakReference> s_queues = new LinkedList<WeakReference>();
private static readonly LinkedList<WeakReference> s_newQueues = new LinkedList<WeakReference>();
private static int s_threadState = (int)TimerThreadState.Idle; // Really a TimerThreadState, but need an int for Interlocked.
private static readonly AutoResetEvent s_threadReadyEvent = new AutoResetEvent(false);
private static readonly ManualResetEvent s_threadShutdownEvent = new ManualResetEvent(false);
private static readonly WaitHandle[] s_threadEvents = { s_threadShutdownEvent, s_threadReadyEvent };
private static int s_cacheScanIteration;
private static readonly Hashtable s_queuesCache = new Hashtable();
/// <summary>
/// <para>The possible states of the timer thread.</para>
/// </summary>
private enum TimerThreadState
{
Idle,
Running,
Stopped
}
/// <summary>
/// <para>Queue factory. Always synchronized.</para>
/// </summary>
internal static Queue GetOrCreateQueue(int durationMilliseconds)
{
if (durationMilliseconds == Timeout.Infinite)
{
return new InfiniteTimerQueue();
}
if (durationMilliseconds < 0)
{
throw new ArgumentOutOfRangeException(nameof(durationMilliseconds));
}
TimerQueue queue;
object key = durationMilliseconds; // Box once.
WeakReference weakQueue = (WeakReference)s_queuesCache[key];
if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null)
{
lock (s_newQueues)
{
weakQueue = (WeakReference)s_queuesCache[key];
if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null)
{
queue = new TimerQueue(durationMilliseconds);
weakQueue = new WeakReference(queue);
s_newQueues.AddLast(weakQueue);
s_queuesCache[key] = weakQueue;
// Take advantage of this lock to periodically scan the table for garbage.
if (++s_cacheScanIteration % CacheScanPerIterations == 0)
{
var garbage = new List<object>();
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = s_queuesCache.GetEnumerator();
while (e.MoveNext())
{
DictionaryEntry pair = e.Entry;
if (((WeakReference)pair.Value).Target == null)
{
garbage.Add(pair.Key);
}
}
for (int i = 0; i < garbage.Count; i++)
{
s_queuesCache.Remove(garbage[i]);
}
}
}
}
}
return queue;
}
/// <summary>
/// <para>Represents a queue of timers of fixed duration.</para>
/// </summary>
private class TimerQueue : Queue
{
// This is a GCHandle that holds onto the TimerQueue when active timers are in it.
// The TimerThread only holds WeakReferences to it so that it can be collected when the user lets go of it.
// But we don't want the user to HAVE to keep a reference to it when timers are active in it.
// It gets created when the first timer gets added, and cleaned up when the TimerThread notices it's empty.
// The TimerThread will always notice it's empty eventually, since the TimerThread will always wake up and
// try to fire the timer, even if it was cancelled and removed prematurely.
private IntPtr _thisHandle;
// This sentinel TimerNode acts as both the head and the tail, allowing nodes to go in and out of the list without updating
// any TimerQueue members. _timers.Next is the true head, and .Prev the true tail. This also serves as the list's lock.
private readonly TimerNode _timers;
/// <summary>
/// <para>Create a new TimerQueue. TimerQueues must be created while s_NewQueues is locked in
/// order to synchronize with Shutdown().</para>
/// </summary>
/// <param name="durationMilliseconds"></param>
internal TimerQueue(int durationMilliseconds) :
base(durationMilliseconds)
{
// Create the doubly-linked list with a sentinel head and tail so that this member never needs updating.
_timers = new TimerNode();
_timers.Next = _timers;
_timers.Prev = _timers;
}
/// <summary>
/// <para>Creates new timers. This method is thread-safe.</para>
/// </summary>
internal override Timer CreateTimer(Callback callback, object context)
{
TimerNode timer = new TimerNode(callback, context, Duration, _timers);
// Add this on the tail. (Actually, one before the tail - _timers is the sentinel tail.)
bool needProd = false;
lock (_timers)
{
if (!(_timers.Prev.Next == _timers))
{
NetEventSource.Fail(this, $"Tail corruption.");
}
// If this is the first timer in the list, we need to create a queue handle and prod the timer thread.
if (_timers.Next == _timers)
{
if (_thisHandle == IntPtr.Zero)
{
_thisHandle = (IntPtr)GCHandle.Alloc(this);
}
needProd = true;
}
timer.Next = _timers;
timer.Prev = _timers.Prev;
_timers.Prev.Next = timer;
_timers.Prev = timer;
}
// If, after we add the new tail, there is a chance that the tail is the next
// node to be processed, we need to wake up the timer thread.
if (needProd)
{
TimerThread.Prod();
}
return timer;
}
/// <summary>
/// <para>Called by the timer thread to fire the expired timers. Returns true if there are future timers
/// in the queue, and if so, also sets nextExpiration.</para>
/// </summary>
internal bool Fire(out int nextExpiration)
{
while (true)
{
// Check if we got to the end. If so, free the handle.
TimerNode timer = _timers.Next;
if (timer == _timers)
{
lock (_timers)
{
timer = _timers.Next;
if (timer == _timers)
{
if (_thisHandle != IntPtr.Zero)
{
((GCHandle)_thisHandle).Free();
_thisHandle = IntPtr.Zero;
}
nextExpiration = 0;
return false;
}
}
}
if (!timer.Fire())
{
nextExpiration = timer.Expiration;
return true;
}
}
}
}
/// <summary>
/// <para>A special dummy implementation for a queue of timers of infinite duration.</para>
/// </summary>
private class InfiniteTimerQueue : Queue
{
internal InfiniteTimerQueue() : base(Timeout.Infinite) { }
/// <summary>
/// <para>Always returns a dummy infinite timer.</para>
/// </summary>
internal override Timer CreateTimer(Callback callback, object context) => new InfiniteTimer();
}
/// <summary>
/// <para>Internal representation of an individual timer.</para>
/// </summary>
private class TimerNode : Timer
{
private TimerState _timerState;
private Callback _callback;
private object _context;
private object _queueLock;
private TimerNode _next;
private TimerNode _prev;
/// <summary>
/// <para>Status of the timer.</para>
/// </summary>
private enum TimerState
{
Ready,
Fired,
Cancelled,
Sentinel
}
internal TimerNode(Callback callback, object context, int durationMilliseconds, object queueLock) : base(durationMilliseconds)
{
if (callback != null)
{
_callback = callback;
_context = context;
}
_timerState = TimerState.Ready;
_queueLock = queueLock;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}");
}
// A sentinel node - both the head and tail are one, which prevent the head and tail from ever having to be updated.
internal TimerNode() : base(0)
{
_timerState = TimerState.Sentinel;
}
internal override bool HasExpired => _timerState == TimerState.Fired;
internal TimerNode Next
{
get { return _next; }
set { _next = value; }
}
internal TimerNode Prev
{
get { return _prev; }
set { _prev = value; }
}
/// <summary>
/// <para>Cancels the timer. Returns true if it hasn't and won't fire; false if it has or will, or has already been cancelled.</para>
/// </summary>
internal override bool Cancel()
{
if (_timerState == TimerState.Ready)
{
lock (_queueLock)
{
if (_timerState == TimerState.Ready)
{
// Remove it from the list. This keeps the list from getting too big when there are a lot of rapid creations
// and cancellations. This is done before setting it to Cancelled to try to prevent the Fire() loop from
// seeing it, or if it does, of having to take a lock to synchronize with the state of the list.
Next.Prev = Prev;
Prev.Next = Next;
// Just cleanup. Doesn't need to be in the lock but is easier to have here.
Next = null;
Prev = null;
_callback = null;
_context = null;
_timerState = TimerState.Cancelled;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime} Cancel (success)");
return true;
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime} Cancel (failure)");
return false;
}
/// <summary>
/// <para>Fires the timer if it is still active and has expired. Returns
/// true if it can be deleted, or false if it is still timing.</para>
/// </summary>
internal bool Fire()
{
if (_timerState == TimerState.Sentinel)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "TimerQueue tried to Fire a Sentinel.");
}
if (_timerState != TimerState.Ready)
{
return true;
}
// Must get the current tick count within this method so it is guaranteed not to be before
// StartTime, which is set in the constructor.
int nowMilliseconds = Environment.TickCount;
if (IsTickBetween(StartTime, Expiration, nowMilliseconds))
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Not firing ({StartTime} <= {nowMilliseconds} < {Expiration})");
return false;
}
bool needCallback = false;
lock (_queueLock)
{
if (_timerState == TimerState.Ready)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Firing ({StartTime} <= {nowMilliseconds} >= " + Expiration + ")");
_timerState = TimerState.Fired;
// Remove it from the list.
Next.Prev = Prev;
Prev.Next = Next;
Next = null;
Prev = null;
needCallback = _callback != null;
}
}
if (needCallback)
{
try
{
Callback callback = _callback;
object context = _context;
_callback = null;
_context = null;
callback(this, nowMilliseconds, context);
}
catch (Exception exception)
{
if (ExceptionCheck.IsFatal(exception))
throw;
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"exception in callback: {exception}");
// This thread is not allowed to go into user code, so we should never get an exception here.
// So, in debug, throw it up, killing the AppDomain. In release, we'll just ignore it.
#if DEBUG
throw;
#endif
}
}
return true;
}
}
/// <summary>
/// <para>A dummy infinite timer.</para>
/// </summary>
private class InfiniteTimer : Timer
{
internal InfiniteTimer() : base(Timeout.Infinite) { }
private int _cancelled;
internal override bool HasExpired => false;
/// <summary>
/// <para>Cancels the timer. Returns true the first time, false after that.</para>
/// </summary>
internal override bool Cancel() => Interlocked.Exchange(ref _cancelled, 1) == 0;
}
/// <summary>
/// <para>Internal mechanism used when timers are added to wake up / create the thread.</para>
/// </summary>
private static void Prod()
{
s_threadReadyEvent.Set();
TimerThreadState oldState = (TimerThreadState)Interlocked.CompareExchange(
ref s_threadState,
(int)TimerThreadState.Running,
(int)TimerThreadState.Idle);
if (oldState == TimerThreadState.Idle)
{
new Thread(new ThreadStart(ThreadProc)).Start();
}
}
/// <summary>
/// <para>Thread for the timer. Ignores all exceptions. If no activity occurs for a while,
/// the thread will shut down.</para>
/// </summary>
private static void ThreadProc()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null);
#if DEBUG
DebugThreadTracking.SetThreadSource(ThreadKinds.Timer);
using (DebugThreadTracking.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
// Set this thread as a background thread. On AppDomain/Process shutdown, the thread will just be killed.
Thread.CurrentThread.IsBackground = true;
// Keep a permanent lock on s_Queues. This lets for example Shutdown() know when this thread isn't running.
lock (s_queues)
{
// If shutdown was recently called, abort here.
if (Interlocked.CompareExchange(ref s_threadState, (int)TimerThreadState.Running, (int)TimerThreadState.Running) !=
(int)TimerThreadState.Running)
{
return;
}
bool running = true;
while (running)
{
try
{
s_threadReadyEvent.Reset();
while (true)
{
// Copy all the new queues to the real queues. Since only this thread modifies the real queues, it doesn't have to lock it.
if (s_newQueues.Count > 0)
{
lock (s_newQueues)
{
for (LinkedListNode<WeakReference> node = s_newQueues.First; node != null; node = s_newQueues.First)
{
s_newQueues.Remove(node);
s_queues.AddLast(node);
}
}
}
int now = Environment.TickCount;
int nextTick = 0;
bool haveNextTick = false;
for (LinkedListNode<WeakReference> node = s_queues.First; node != null; /* node = node.Next must be done in the body */)
{
TimerQueue queue = (TimerQueue)node.Value.Target;
if (queue == null)
{
LinkedListNode<WeakReference> next = node.Next;
s_queues.Remove(node);
node = next;
continue;
}
// Fire() will always return values that should be interpreted as later than 'now' (that is, even if 'now' is
// returned, it is 0x100000000 milliseconds in the future). There's also a chance that Fire() will return a value
// intended as > 0x100000000 milliseconds from 'now'. Either case will just cause an extra scan through the timers.
int nextTickInstance;
if (queue.Fire(out nextTickInstance) && (!haveNextTick || IsTickBetween(now, nextTick, nextTickInstance)))
{
nextTick = nextTickInstance;
haveNextTick = true;
}
node = node.Next;
}
// Figure out how long to wait, taking into account how long the loop took.
// Add 15 ms to compensate for poor TickCount resolution (want to guarantee a firing).
int newNow = Environment.TickCount;
int waitDuration = haveNextTick ?
(int)(IsTickBetween(now, nextTick, newNow) ?
Math.Min(unchecked((uint)(nextTick - newNow)), (uint)(int.MaxValue - TickCountResolution)) + TickCountResolution :
0) :
ThreadIdleTimeoutMilliseconds;
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Waiting for {waitDuration}ms");
int waitResult = WaitHandle.WaitAny(s_threadEvents, waitDuration, false);
// 0 is s_ThreadShutdownEvent - die.
if (waitResult == 0)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Awoke, cause: Shutdown");
running = false;
break;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Awoke, cause {(waitResult == WaitHandle.WaitTimeout ? "Timeout" : "Prod")}");
// If we timed out with nothing to do, shut down.
if (waitResult == WaitHandle.WaitTimeout && !haveNextTick)
{
Interlocked.CompareExchange(ref s_threadState, (int)TimerThreadState.Idle, (int)TimerThreadState.Running);
// There could have been one more prod between the wait and the exchange. Check, and abort if necessary.
if (s_threadReadyEvent.WaitOne(0, false))
{
if (Interlocked.CompareExchange(ref s_threadState, (int)TimerThreadState.Running, (int)TimerThreadState.Idle) ==
(int)TimerThreadState.Idle)
{
continue;
}
}
running = false;
break;
}
}
}
catch (Exception exception)
{
if (ExceptionCheck.IsFatal(exception))
throw;
if (NetEventSource.IsEnabled) NetEventSource.Error(null, exception);
// The only options are to continue processing and likely enter an error-loop,
// shut down timers for this AppDomain, or shut down the AppDomain. Go with shutting
// down the AppDomain in debug, and going into a loop in retail, but try to make the
// loop somewhat slow. Note that in retail, this can only be triggered by OutOfMemory or StackOverflow,
// or an exception thrown within TimerThread - the rest are caught in Fire().
#if !DEBUG
Thread.Sleep(1000);
#else
throw;
#endif
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Stop");
#if DEBUG
}
#endif
}
/// <summary>
/// <para>Helper for deciding whether a given TickCount is before or after a given expiration
/// tick count assuming that it can't be before a given starting TickCount.</para>
/// </summary>
private static bool IsTickBetween(int start, int end, int comparand)
{
// Assumes that if start and end are equal, they are the same time.
// Assumes that if the comparand and start are equal, no time has passed,
// and that if the comparand and end are equal, end has occurred.
return ((start <= comparand) == (end <= comparand)) != (start <= end);
}
}
}
| |
using System;
using System.Threading.Tasks;
using Baseline;
using Jasper.Attributes;
using Jasper.AzureServiceBus.Internal;
using Jasper.Transports;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Primitives;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace Jasper.AzureServiceBus.Tests
{
// SAMPLE: SettingAzureServiceBusOptions
public class JasperWithAzureServiceBusApp : JasperOptions
{
public JasperWithAzureServiceBusApp()
{
Endpoints.ConfigureAzureServiceBus(asb =>
{
asb.ConnectionString = "an Azure Service Bus connection string";
// The following properties would be set on all
// TopicClient, QueueClient, or SubscriptionClient
// objects created at runtime
asb.TransportType = TransportType.AmqpWebSockets;
asb.TokenProvider = new ManagedServiceIdentityTokenProvider();
asb.ReceiveMode = ReceiveMode.ReceiveAndDelete;
asb.RetryPolicy = RetryPolicy.NoRetry;
});
// Configure endpoints
Endpoints.PublishAllMessages().ToAzureServiceBusQueue("outgoing");
Endpoints.ListenToAzureServiceBusQueue("incoming");
}
}
// ENDSAMPLE
// SAMPLE: AzureServiceBus-AzureServiceBusTopicSendingApp
public class AzureServiceBusTopicSendingApp : JasperOptions
{
public AzureServiceBusTopicSendingApp()
{
Endpoints.ConfigureAzureServiceBus(asb =>
{
asb.ConnectionString = "an Azure Service Bus connection string";
});
// This directs Jasper to send all messages to
// an Azure Service Bus topic name derived from the
// message type
Endpoints.PublishAllMessages()
.ToAzureServiceBusTopics();
}
}
// ENDSAMPLE
public class MySpecialProtocol : ITransportProtocol<Message>
{
public Message WriteFromEnvelope(Envelope envelope)
{
throw new NotImplementedException();
}
public Envelope ReadEnvelope(Message message)
{
throw new NotImplementedException();
}
}
// SAMPLE: PublishAndSubscribeToAzureServiceBusQueue
internal class JasperConfig : JasperOptions
{
public JasperConfig()
{
// Publish all messages to an Azure Service Bus queue
Endpoints
.PublishAllMessages()
.ToAzureServiceBusQueue("pings")
// Optionally use the store and forward
// outbox mechanics against this endpoint
.Durably();
// Listen to incoming messages from an Azure Service Bus
// queue
Endpoints
.ListenToAzureServiceBusQueue("pongs");
}
public override void Configure(IHostEnvironment hosting, IConfiguration config)
{
var connectionString = config.GetConnectionString("azureservicebus");
Endpoints.ConfigureAzureServiceBus(connectionString);
}
}
// ENDSAMPLE
// SAMPLE: PublishAndSubscribeToAzureServiceBusQueueByUri
internal class JasperConfig2 : JasperOptions
{
public JasperConfig2()
{
// Publish all messages to an Azure Service Bus queue
Endpoints
.PublishAllMessages()
.To("asb://queue/pings");
// Listen to incoming messages from an Azure Service Bus
// queue
Endpoints
.ListenForMessagesFrom("asb://queue/pongs")
.UseForReplies();
}
public override void Configure(IHostEnvironment hosting, IConfiguration config)
{
var connectionString = config.GetConnectionString("azureservicebus");
Endpoints.ConfigureAzureServiceBus(connectionString);
}
}
// ENDSAMPLE
// SAMPLE: PublishAndSubscribeToAzureServiceBusTopic
internal class JasperConfig3 : JasperOptions
{
public JasperConfig3()
{
// Publish all messages to an Azure Service Bus queue
Endpoints
.PublishAllMessages()
.ToAzureServiceBusTopic("pings")
// Optionally use the store and forward
// outbox mechanics against this endpoint
.Durably();
// Listen to incoming messages from an Azure Service Bus
// queue
Endpoints
.ListenToAzureServiceBusTopic("pongs", "pong-subscription");
}
public override void Configure(IHostEnvironment hosting, IConfiguration config)
{
var connectionString = config.GetConnectionString("azureservicebus");
Endpoints.ConfigureAzureServiceBus(connectionString);
}
}
// ENDSAMPLE
// SAMPLE: PublishAndSubscribeToAzureServiceBusTopicByUri
internal class JasperConfig4 : JasperOptions
{
public JasperConfig4()
{
// Publish all messages to an Azure Service Bus queue
Endpoints
.PublishAllMessages()
.To("asb://topic/pings");
// Listen to incoming messages from an Azure Service Bus
// queue
Endpoints
.ListenForMessagesFrom("asb://topic/pongs/subscription/pong-subscription")
.UseForReplies();
}
public override void Configure(IHostEnvironment hosting, IConfiguration config)
{
var connectionString = config.GetConnectionString("azureservicebus");
Endpoints.ConfigureAzureServiceBus(connectionString);
}
}
// ENDSAMPLE
// SAMPLE: CustomAzureServiceBusProtocol
public class SpecialAzureServiceBusProtocol : DefaultAzureServiceBusProtocol
{
public override Message WriteFromEnvelope(Envelope envelope)
{
var message = base.WriteFromEnvelope(envelope);
// Override some properties from how
// Jasper itself would write them out
message.ReplyTo = "replies";
return message;
}
public override Envelope ReadEnvelope(Message message)
{
var envelope = base.ReadEnvelope(message);
if (message.ReplyTo.IsNotEmpty())
{
var uriString = "asb://topic/" + message.ReplyTo;
}
return envelope;
}
}
// ENDSAMPLE
// SAMPLE: PublishAndSubscribeToAzureServiceBusTopicAndCustomProtocol
internal class JasperConfig5 : JasperOptions
{
public JasperConfig5()
{
// Publish all messages to an Azure Service Bus queue
Endpoints
.PublishAllMessages()
.ToAzureServiceBusTopic("pings")
// Override the Azure Service Bus protocol
// because it's not a Jasper application on the other end
.Protocol<SpecialAzureServiceBusProtocol>()
// Optionally use the store and forward
// outbox mechanics against this endpoint
.Durably();
// Listen to incoming messages from an Azure Service Bus
// queue
Endpoints
.ListenToAzureServiceBusTopic("pongs", "pong-subscription");
}
public override void Configure(IHostEnvironment hosting, IConfiguration config)
{
var connectionString = config.GetConnectionString("azureservicebus");
Endpoints.ConfigureAzureServiceBus(connectionString);
}
}
// ENDSAMPLE
// SAMPLE: ItemCreatedWithTopic
[Topic("items")]
public class ItemCreated
{
public string Name { get; set; }
}
// ENDSAMPLE
public static class Sender
{
// SAMPLE: SendItemCreatedByTopic
public static async Task SendMessage(IMessagePublisher publisher)
{
await publisher.Send(new ItemCreated
{
Name = "NewItem"
});
}
// ENDSAMPLE
// SAMPLE: SendItemCreatedToTopic
public static async Task SendToTopic(IMessagePublisher publisher)
{
var @event = new ItemCreated
{
Name = "New Thing"
};
// This call sends the ItemCreated message to the
// "NorthAmerica" topic
await publisher.SendToTopic(@event, "NorthAmerica");
}
// ENDSAMPLE
// SAMPLE: SendLogMessageToTopic
public static async Task SendLogMessage(IMessagePublisher publisher)
{
var message = new LogMessage
{
Message = "Watch out!",
Priority = "High"
};
// In this sample, Jasper will route the LogMessage
// message to the "High" topic
await publisher.Send(message);
}
// ENDSAMPLE
}
// SAMPLE: LogMessageWithPriority
public class LogMessage
{
public string Message { get; set; }
public string Priority { get; set; }
}
// ENDSAMPLE
// SAMPLE: AppWithTopicNamingRule
public class PublishWithTopicRulesApp : JasperOptions
{
public PublishWithTopicRulesApp()
{
Endpoints.PublishAllMessages()
.ToAzureServiceBusTopics()
// This is setting up a topic name rule
// for any message of type that can be
// cast to LogMessage
.OutgoingTopicNameIs<LogMessage>(x => x.Priority);
}
public override void Configure(IHostEnvironment hosting, IConfiguration config)
{
var connectionString = config.GetConnectionString("azureservicebus");
Endpoints.ConfigureAzureServiceBus(connectionString);
}
}
// ENDSAMPLE
}
| |
/*
* @(#)AttrCheckImpl.java 1.11 2000/08/16
*
*/
using System;
namespace Comzept.Genesis.Tidy
{
/// <summary>
/// Check attribute values implementations
///
/// (c) 1998-2000 (W3C) MIT, INRIA, Keio University
/// See Tidy.java for the copyright notice.
/// Derived from <a href="http://www.w3.org/People/Raggett/tidy">
/// HTML Tidy Release 4 Aug 2000</a>
///
/// </summary>
/// <author> Dave Raggett dsr@w3.org
/// </author>
/// <author> Andy Quick ac.quick@sympatico.ca (translation to Java)
/// </author>
/// <version> 1.0, 1999/05/22
/// </version>
/// <version> 1.0.1, 1999/05/29
/// </version>
/// <version> 1.1, 1999/06/18 Java Bean
/// </version>
/// <version> 1.2, 1999/07/10 Tidy Release 7 Jul 1999
/// </version>
/// <version> 1.3, 1999/07/30 Tidy Release 26 Jul 1999
/// </version>
/// <version> 1.4, 1999/09/04 DOM support
/// </version>
/// <version> 1.5, 1999/10/23 Tidy Release 27 Sep 1999
/// </version>
/// <version> 1.6, 1999/11/01 Tidy Release 22 Oct 1999
/// </version>
/// <version> 1.7, 1999/12/06 Tidy Release 30 Nov 1999
/// </version>
/// <version> 1.8, 2000/01/22 Tidy Release 13 Jan 2000
/// </version>
/// <version> 1.9, 2000/06/03 Tidy Release 30 Apr 2000
/// </version>
/// <version> 1.10, 2000/07/22 Tidy Release 8 Jul 2000
/// </version>
/// <version> 1.11, 2000/08/16 Tidy Release 4 Aug 2000
/// </version>
public class AttrCheckImpl
{
public class CheckUrl : AttrCheck
{
public virtual void check(Lexer lexer, Node node, AttVal attval)
{
if (attval.value_Renamed == null)
Report.attrError(lexer, node, attval.attribute, Report.MISSING_ATTR_VALUE);
else if (lexer.configuration.FixBackslash)
{
attval.value_Renamed = attval.value_Renamed.Replace('\\', '/');
}
}
}
public class CheckScript : AttrCheck
{
public virtual void check(Lexer lexer, Node node, AttVal attval)
{
}
}
public class CheckAlign : AttrCheck
{
public virtual void check(Lexer lexer, Node node, AttVal attval)
{
System.String value_Renamed;
/* IMG, OBJECT, APPLET and EMBED use align for vertical position */
if (node.tag != null && ((node.tag.model & Dict.CM_IMG) != 0))
{
Comzept.Genesis.Tidy.AttrCheckImpl.getCheckValign().check(lexer, node, attval);
return ;
}
value_Renamed = attval.value_Renamed;
if (value_Renamed == null)
Report.attrError(lexer, node, attval.attribute, Report.MISSING_ATTR_VALUE);
else if (!(Lexer.wstrcasecmp(value_Renamed, "left") == 0 || Lexer.wstrcasecmp(value_Renamed, "center") == 0 || Lexer.wstrcasecmp(value_Renamed, "right") == 0 || Lexer.wstrcasecmp(value_Renamed, "justify") == 0))
Report.attrError(lexer, node, attval.value_Renamed, Report.BAD_ATTRIBUTE_VALUE);
}
}
public class CheckValign : AttrCheck
{
public virtual void check(Lexer lexer, Node node, AttVal attval)
{
System.String value_Renamed;
value_Renamed = attval.value_Renamed;
if (value_Renamed == null)
Report.attrError(lexer, node, attval.attribute, Report.MISSING_ATTR_VALUE);
else if (Lexer.wstrcasecmp(value_Renamed, "top") == 0 || Lexer.wstrcasecmp(value_Renamed, "middle") == 0 || Lexer.wstrcasecmp(value_Renamed, "bottom") == 0 || Lexer.wstrcasecmp(value_Renamed, "baseline") == 0)
{
/* all is fine */
}
else if (Lexer.wstrcasecmp(value_Renamed, "left") == 0 || Lexer.wstrcasecmp(value_Renamed, "right") == 0)
{
if (!(node.tag != null && ((node.tag.model & Dict.CM_IMG) != 0)))
Report.attrError(lexer, node, value_Renamed, Report.BAD_ATTRIBUTE_VALUE);
}
else if (Lexer.wstrcasecmp(value_Renamed, "texttop") == 0 || Lexer.wstrcasecmp(value_Renamed, "absmiddle") == 0 || Lexer.wstrcasecmp(value_Renamed, "absbottom") == 0 || Lexer.wstrcasecmp(value_Renamed, "textbottom") == 0)
{
lexer.versions &= Dict.VERS_PROPRIETARY;
Report.attrError(lexer, node, value_Renamed, Report.PROPRIETARY_ATTR_VALUE);
}
else
Report.attrError(lexer, node, value_Renamed, Report.BAD_ATTRIBUTE_VALUE);
}
}
public class CheckBool : AttrCheck
{
public virtual void check(Lexer lexer, Node node, AttVal attval)
{
}
}
public class CheckId : AttrCheck
{
public virtual void check(Lexer lexer, Node node, AttVal attval)
{
}
}
public class CheckName : AttrCheck
{
public virtual void check(Lexer lexer, Node node, AttVal attval)
{
}
}
public static AttrCheck getCheckUrl()
{
return _checkUrl;
}
public static AttrCheck getCheckScript()
{
return _checkScript;
}
public static AttrCheck getCheckAlign()
{
return _checkAlign;
}
public static AttrCheck getCheckValign()
{
return _checkValign;
}
public static AttrCheck getCheckBool()
{
return _checkBool;
}
public static AttrCheck getCheckId()
{
return _checkId;
}
public static AttrCheck getCheckName()
{
return _checkName;
}
private static AttrCheck _checkUrl = new CheckUrl();
private static AttrCheck _checkScript = new CheckScript();
private static AttrCheck _checkAlign = new CheckAlign();
private static AttrCheck _checkValign = new CheckValign();
private static AttrCheck _checkBool = new CheckBool();
private static AttrCheck _checkId = new CheckId();
private static AttrCheck _checkName = new CheckName();
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Json;
using System.Linq.Expressions;
using System.Reflection;
using NCDO.Extensions;
using NCDO.Interfaces;
using JsonPair = System.Collections.Generic.KeyValuePair<string, System.Json.JsonValue>;
using JsonPairEnumerable =
System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Json.JsonValue>>;
namespace NCDO.CDOMemory
{
public abstract class CDO_Record<T> : CDO_Record where T : CDO_Record, new()
{
#region Constructor
public CDO_Record(params JsonPair[] items): base(items)
{
}
public CDO_Record(JsonPairEnumerable items): base(items)
{
}
public CDO_Record()
{
}
#endregion
#region Overrides of CDO_Record
/// <inheritdoc />
public override string GetId()
{
if (!string.IsNullOrEmpty(PrimaryKeyName) && ContainsKey(PrimaryKeyName))
{
var id = this.Get(PrimaryKeyName).ToString();
if (_defaultPrimaryKeyValue == id)
{
return _id;
}
return id;
}
return base.GetId();
}
private string _defaultPrimaryKeyValue;
/// <inheritdoc />
public override string PrimaryKeyName
{
set
{
base.PrimaryKeyName = value;
_defaultPrimaryKeyValue = Default(value)?.ToString();
}
}
#endregion
public virtual S Default<S>(Expression<Func<T, S>> propertyExpression)
{
var property = propertyExpression.Body as UnaryExpression;
MemberExpression propExp =
(property?.Operand as MemberExpression) ?? propertyExpression.Body as MemberExpression;
var defaultValueAttribute = propExp?.Member.GetCustomAttribute<DefaultValueAttribute>();
var converter = TypeDescriptor.GetConverter(typeof(S));
return (S) converter.ConvertFromString(defaultValueAttribute?.Value.ToString());
}
protected virtual object Default(string propertyName)
{
var propInfo = GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
var defaultValueAttribute = propInfo?.GetCustomAttribute<DefaultValueAttribute>();
return defaultValueAttribute?.Value;
}
}
public class CDO_Record : JsonObject, ICloudDataRecord, IEquatable<CDO_Record>
{
internal Dictionary<string, JsonValue> _changeDict = new Dictionary<string, JsonValue>();
/// <summary>
/// An internal field for the CDO that is provided to find a given record in its memory.
/// </summary>
protected string _id = Guid.NewGuid().ToString();
#region Constructor
public CDO_Record(params JsonPair[] items) : base(items)
{
}
public CDO_Record(JsonPairEnumerable items) : base(items)
{
}
public CDO_Record()
{
}
#endregion
//redefine is needed to allow override by generic CDO_Record
public new virtual ICollection<string> Keys => base.Keys;
#region Implementation of ICloudDataRecord
/// <inheritdoc />
public JsonPairEnumerable Data => this;
public bool IsPrimaryKeyChanged => !string.IsNullOrEmpty(PrimaryKeyName) && _changeDict.ContainsKey(PrimaryKeyName);
public string GetChangedKeyValue => IsPrimaryKeyChanged ? _changeDict[PrimaryKeyName].AsString() : GetId();
/// <inheritdoc />
public void AcceptRowChanges()
{
_changeDict.Clear();
}
/// <inheritdoc />
public void Assign(IEnumerable<KeyValuePair<string, JsonValue>> values)
{
this.AddRange(values);
}
/// <inheritdoc />
public string GetErrorString()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public virtual string GetId() => string.IsNullOrEmpty(PrimaryKeyName) || !ContainsKey(PrimaryKeyName)
? _id
: this.Get(PrimaryKeyName).ToString();
public virtual void SetId(JsonValue value)
{
if (string.IsNullOrEmpty(PrimaryKeyName))
_id = value.AsString();
else this.Set(PrimaryKeyName, value);
}
public virtual string PrimaryKeyName { get; set; }
/// <inheritdoc />
public void RejectRowChanges()
{
foreach (var keyValuePair in _changeDict)
{
this[keyValuePair.Key] = keyValuePair.Value;
}
_changeDict.Clear();
}
/// <inheritdoc />
public bool IsPropertyChanged(string propertyName) => _changeDict.ContainsKey(propertyName);
#endregion
#region Implementation of INotifyPropertyChang(ing|ed)
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <inheritdoc />
public event PropertyChangingEventHandler PropertyChanging;
protected virtual void OnPropertyChanging(string propertyName)
{
PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName));
if (!_changeDict.ContainsKey(propertyName)) _changeDict.Add(propertyName, this[propertyName]);
}
public void Add(string key, JsonValue value, bool notify = true)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (notify && ContainsKey(key))
{
OnPropertyChanging(key);
base.Remove(key);
}
base[key] = value;
if (notify && IsPropertyChanged(key)) OnPropertyChanged(key);
}
public new void AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items)
{
if (items == null)
throw new ArgumentNullException(nameof(items));
foreach (KeyValuePair<string, JsonValue> keyValuePair in items)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
}
public new JsonValue this[string key]
{
get => base[key];
set
{
if (ContainsKey(key)) OnPropertyChanging(key);
base[key] = value;
if (IsPropertyChanged(key)) OnPropertyChanged(key);
}
}
#endregion
#region Implementation of IChangeTracking
/// <inheritdoc />
public void AcceptChanges()
{
AcceptRowChanges();
}
/// <inheritdoc />
public bool IsChanged => _changeDict.Count > 0;
#endregion
#region Equality members
/// <inheritdoc />
public virtual bool Equals(CDO_Record other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(GetId(), other.GetId());
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return Equals((CDO_Record) obj);
}
/// <inheritdoc />
public override int GetHashCode() => (GetId() != null ? GetId().GetHashCode() : 0);
#endregion
#region Status
public bool IsNew => !Int32.TryParse(GetId(), out int id) || id <= 0;
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* 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 QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Slippage;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Securities.Option;
using QuantConnect.Util;
namespace QuantConnect.Brokerages
{
/// <summary>
/// Provides a default implementation of <see cref="IBrokerageModel"/> that allows all orders and uses
/// the default transaction models
/// </summary>
public class DefaultBrokerageModel : IBrokerageModel
{
/// <summary>
/// The default markets for the backtesting brokerage
/// </summary>
public static readonly IReadOnlyDictionary<SecurityType, string> DefaultMarketMap = new Dictionary<SecurityType, string>
{
{SecurityType.Base, Market.USA},
{SecurityType.Equity, Market.USA},
{SecurityType.Option, Market.USA},
{SecurityType.Future, Market.USA},
{SecurityType.Forex, Market.FXCM},
{SecurityType.Cfd, Market.FXCM},
{SecurityType.Crypto, Market.Bitfinex}
}.ToReadOnlyDictionary();
/// <summary>
/// Gets or sets the account type used by this model
/// </summary>
public virtual AccountType AccountType
{
get;
private set;
}
/// <summary>
/// Gets a map of the default markets to be used for each security type
/// </summary>
public virtual IReadOnlyDictionary<SecurityType, string> DefaultMarkets
{
get { return DefaultMarketMap; }
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultBrokerageModel"/> class
/// </summary>
/// <param name="accountType">The type of account to be modelled, defaults to
/// <see cref="QuantConnect.AccountType.Margin"/></param>
public DefaultBrokerageModel(AccountType accountType = AccountType.Margin)
{
AccountType = accountType;
}
/// <summary>
/// Returns true if the brokerage could accept this order. This takes into account
/// order type, security type, and order size limits.
/// </summary>
/// <remarks>
/// For example, a brokerage may have no connectivity at certain times, or an order rate/size limit
/// </remarks>
/// <param name="security">The security being ordered</param>
/// <param name="order">The order to be processed</param>
/// <param name="message">If this function returns false, a brokerage message detailing why the order may not be submitted</param>
/// <returns>True if the brokerage could process the order, false otherwise</returns>
public virtual bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message)
{
message = null;
return true;
}
/// <summary>
/// Returns true if the brokerage would allow updating the order as specified by the request
/// </summary>
/// <param name="security">The security of the order</param>
/// <param name="order">The order to be updated</param>
/// <param name="request">The requested update to be made to the order</param>
/// <param name="message">If this function returns false, a brokerage message detailing why the order may not be updated</param>
/// <returns>True if the brokerage would allow updating the order, false otherwise</returns>
public virtual bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message)
{
message = null;
return true;
}
/// <summary>
/// Returns true if the brokerage would be able to execute this order at this time assuming
/// market prices are sufficient for the fill to take place. This is used to emulate the
/// brokerage fills in backtesting and paper trading. For example some brokerages may not perform
/// executions during extended market hours. This is not intended to be checking whether or not
/// the exchange is open, that is handled in the Security.Exchange property.
/// </summary>
/// <param name="security">The security being traded</param>
/// <param name="order">The order to test for execution</param>
/// <returns>True if the brokerage would be able to perform the execution, false otherwise</returns>
public virtual bool CanExecuteOrder(Security security, Order order)
{
return true;
}
/// <summary>
/// Applies the split to the specified order ticket
/// </summary>
/// <remarks>
/// This default implementation will update the orders to maintain a similar market value
/// </remarks>
/// <param name="tickets">The open tickets matching the split event</param>
/// <param name="split">The split event data</param>
public virtual void ApplySplit(List<OrderTicket> tickets, Split split)
{
// by default we'll just update the orders to have the same notional value
var splitFactor = split.SplitFactor;
tickets.ForEach(ticket => ticket.Update(new UpdateOrderFields
{
Quantity = (int?) (ticket.Quantity/splitFactor),
LimitPrice = ticket.OrderType.IsLimitOrder() ? ticket.Get(OrderField.LimitPrice)*splitFactor : (decimal?) null,
StopPrice = ticket.OrderType.IsStopOrder() ? ticket.Get(OrderField.StopPrice)*splitFactor : (decimal?) null
}));
}
/// <summary>
/// Gets the brokerage's leverage for the specified security
/// </summary>
/// <param name="security">The security's whose leverage we seek</param>
/// <returns>The leverage for the specified security</returns>
public decimal GetLeverage(Security security)
{
if (AccountType == AccountType.Cash)
{
return 1m;
}
switch (security.Type)
{
case SecurityType.Equity:
return 2m;
case SecurityType.Forex:
case SecurityType.Cfd:
return 50m;
case SecurityType.Crypto:
return 1m;
case SecurityType.Base:
case SecurityType.Commodity:
case SecurityType.Option:
case SecurityType.Future:
default:
return 1m;
}
}
/// <summary>
/// Gets a new fill model that represents this brokerage's fill behavior
/// </summary>
/// <param name="security">The security to get fill model for</param>
/// <returns>The new fill model for this brokerage</returns>
public virtual IFillModel GetFillModel(Security security)
{
return new ImmediateFillModel();
}
/// <summary>
/// Gets a new fee model that represents this brokerage's fee structure
/// </summary>
/// <param name="security">The security to get a fee model for</param>
/// <returns>The new fee model for this brokerage</returns>
public virtual IFeeModel GetFeeModel(Security security)
{
switch (security.Type)
{
case SecurityType.Base:
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
return new ConstantFeeModel(0m);
case SecurityType.Equity:
case SecurityType.Option:
case SecurityType.Future:
return new InteractiveBrokersFeeModel();
case SecurityType.Commodity:
default:
return new ConstantFeeModel(0m);
}
}
/// <summary>
/// Gets a new slippage model that represents this brokerage's fill slippage behavior
/// </summary>
/// <param name="security">The security to get a slippage model for</param>
/// <returns>The new slippage model for this brokerage</returns>
public virtual ISlippageModel GetSlippageModel(Security security)
{
switch (security.Type)
{
case SecurityType.Base:
case SecurityType.Equity:
return new ConstantSlippageModel(0);
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
return new ConstantSlippageModel(0);
case SecurityType.Commodity:
case SecurityType.Option:
case SecurityType.Future:
default:
return new ConstantSlippageModel(0);
}
}
/// <summary>
/// Gets a new settlement model for the security
/// </summary>
/// <param name="security">The security to get a settlement model for</param>
/// <param name="accountType">The account type</param>
/// <returns>The settlement model for this brokerage</returns>
public virtual ISettlementModel GetSettlementModel(Security security, AccountType accountType)
{
if (accountType == AccountType.Cash)
{
switch (security.Type)
{
case SecurityType.Equity:
return new DelayedSettlementModel(Equity.DefaultSettlementDays, Equity.DefaultSettlementTime);
case SecurityType.Option:
return new DelayedSettlementModel(Option.DefaultSettlementDays, Option.DefaultSettlementTime);
}
}
return new ImmediateSettlementModel();
}
}
}
| |
// 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.AcceptanceTestsBodyComplex
{
using Microsoft.Rest;
using Models;
/// <summary>
/// Inheritance operations.
/// </summary>
public partial class Inheritance : Microsoft.Rest.IServiceOperations<AutoRestComplexTestService>, IInheritance
{
/// <summary>
/// Initializes a new instance of the Inheritance class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Inheritance(AutoRestComplexTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types that extend others
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Siamese>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<Siamese>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Siamese>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that extend others
/// </summary>
/// <param name='complexBody'>
/// Please put a siamese with id=2, name="Siameee", color=green,
/// breed=persion, which hates 2 dogs, the 1st one named "Potato" with id=1
/// and food="tomato", and the 2nd one named "Tomato" with id=-1 and
/// food="french fries".
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutValidWithHttpMessagesAsync(Siamese complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.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 = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region Includes
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Daishi.Armor.Sample.Areas.HelpPage.Models;
#endregion
namespace Daishi.Armor.Sample.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 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 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;
var modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model)) {
var apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
var apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null) {
var sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel) model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) {
var apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try {
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) {
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) {
var invalidSample = sample as InvalidSample;
if (invalidSample != null) {
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Xml
{
using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
// This wrapper does not support seek.
// Constructors consume/emit byte order mark.
// Supports: UTF-8, Unicode, BigEndianUnicode
// ASSUMPTION ([....]): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers.
// ASSUMPTION ([....]): The byte buffer is large enough to hold the declaration
// ASSUMPTION ([....]): The buffer manipulation methods (FillBuffer/Compare/etc.) will only be used to parse the declaration
// during construction.
class EncodingStreamWrapper : Stream
{
enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None }
static readonly UTF8Encoding SafeUTF8 = new UTF8Encoding(false, false);
static readonly UnicodeEncoding SafeUTF16 = new UnicodeEncoding(false, false, false);
static readonly UnicodeEncoding SafeBEUTF16 = new UnicodeEncoding(true, false, false);
static readonly UTF8Encoding ValidatingUTF8 = new UTF8Encoding(false, true);
static readonly UnicodeEncoding ValidatingUTF16 = new UnicodeEncoding(false, false, true);
static readonly UnicodeEncoding ValidatingBEUTF16 = new UnicodeEncoding(true, false, true);
const int BufferLength = 128;
// UTF-8 is fastpath, so that's how these are stored
// Compare methods adapt to unicodes.
static readonly byte[] encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' };
static readonly byte[] encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' };
static readonly byte[] encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' };
static readonly byte[] encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' };
static readonly byte[] encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' };
SupportedEncoding encodingCode;
Encoding encoding;
Encoder enc;
Decoder dec;
bool isReading;
Stream stream;
char[] chars;
byte[] bytes;
int byteOffset;
int byteCount;
byte[] byteBuffer = new byte[1];
// Reading constructor
public EncodingStreamWrapper(Stream stream, Encoding encoding)
{
try
{
this.isReading = true;
this.stream = new BufferedStream(stream);
// Decode the expected encoding
SupportedEncoding expectedEnc = GetSupportedEncoding(encoding);
// Get the byte order mark so we can determine the encoding
// May want to try to delay allocating everything until we know the BOM
SupportedEncoding declEnc = ReadBOMEncoding(encoding == null);
// Check that the expected encoding matches the decl encoding.
if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc)
ThrowExpectedEncodingMismatch(expectedEnc, declEnc);
// Fastpath: UTF-8 BOM
if (declEnc == SupportedEncoding.UTF8)
{
// Fastpath: UTF-8 BOM, No declaration
FillBuffer(2);
if (bytes[byteOffset + 1] != '?' || bytes[byteOffset] != '<')
{
return;
}
FillBuffer(BufferLength);
CheckUTF8DeclarationEncoding(bytes, byteOffset, byteCount, declEnc, expectedEnc);
}
else
{
// Convert to UTF-8
EnsureBuffers();
FillBuffer((BufferLength - 1) * 2);
SetReadDocumentEncoding(declEnc);
CleanupCharBreak();
int count = this.encoding.GetChars(bytes, byteOffset, byteCount, chars, 0);
byteOffset = 0;
byteCount = ValidatingUTF8.GetBytes(chars, 0, count, bytes, 0);
// Check for declaration
if (bytes[1] == '?' && bytes[0] == '<')
{
CheckUTF8DeclarationEncoding(bytes, 0, byteCount, declEnc, expectedEnc);
}
else
{
// Declaration required if no out-of-band encoding
if (expectedEnc == SupportedEncoding.None)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlDeclarationRequired)));
}
}
}
catch (DecoderFallbackException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidBytes), ex));
}
}
void SetReadDocumentEncoding(SupportedEncoding e)
{
EnsureBuffers();
this.encodingCode = e;
this.encoding = GetEncoding(e);
}
static Encoding GetEncoding(SupportedEncoding e)
{
switch (e)
{
case SupportedEncoding.UTF8:
return ValidatingUTF8;
case SupportedEncoding.UTF16LE:
return ValidatingUTF16;
case SupportedEncoding.UTF16BE:
return ValidatingBEUTF16;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlEncodingNotSupported)));
}
}
static Encoding GetSafeEncoding(SupportedEncoding e)
{
switch (e)
{
case SupportedEncoding.UTF8:
return SafeUTF8;
case SupportedEncoding.UTF16LE:
return SafeUTF16;
case SupportedEncoding.UTF16BE:
return SafeBEUTF16;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlEncodingNotSupported)));
}
}
static string GetEncodingName(SupportedEncoding enc)
{
switch (enc)
{
case SupportedEncoding.UTF8:
return "utf-8";
case SupportedEncoding.UTF16LE:
return "utf-16LE";
case SupportedEncoding.UTF16BE:
return "utf-16BE";
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlEncodingNotSupported)));
}
}
static SupportedEncoding GetSupportedEncoding(Encoding encoding)
{
if (encoding == null)
return SupportedEncoding.None;
else if (encoding.WebName == ValidatingUTF8.WebName)
return SupportedEncoding.UTF8;
else if (encoding.WebName == ValidatingUTF16.WebName)
return SupportedEncoding.UTF16LE;
else if (encoding.WebName == ValidatingBEUTF16.WebName)
return SupportedEncoding.UTF16BE;
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlEncodingNotSupported)));
}
// Writing constructor
public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM)
{
this.isReading = false;
this.encoding = encoding;
this.stream = new BufferedStream(stream);
// Set the encoding code
this.encodingCode = GetSupportedEncoding(encoding);
if (encodingCode != SupportedEncoding.UTF8)
{
EnsureBuffers();
dec = ValidatingUTF8.GetDecoder();
enc = this.encoding.GetEncoder();
// Emit BOM
if (emitBOM)
{
byte[] bom = this.encoding.GetPreamble();
if (bom.Length > 0)
this.stream.Write(bom, 0, bom.Length);
}
}
}
SupportedEncoding ReadBOMEncoding(bool notOutOfBand)
{
int b1 = this.stream.ReadByte();
int b2 = this.stream.ReadByte();
int b3 = this.stream.ReadByte();
int b4 = this.stream.ReadByte();
// Premature end of stream
if (b4 == -1)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.UnexpectedEndOfFile)));
int preserve;
SupportedEncoding e = ReadBOMEncoding((byte)b1, (byte)b2, (byte)b3, (byte)b4, notOutOfBand, out preserve);
EnsureByteBuffer();
switch (preserve)
{
case 1:
bytes[0] = (byte)b4;
break;
case 2:
bytes[0] = (byte)b3;
bytes[1] = (byte)b4;
break;
case 4:
bytes[0] = (byte)b1;
bytes[1] = (byte)b2;
bytes[2] = (byte)b3;
bytes[3] = (byte)b4;
break;
}
byteCount = preserve;
return e;
}
static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve)
{
SupportedEncoding e = SupportedEncoding.UTF8; // Default
preserve = 0;
if (b1 == '<' && b2 != 0x00) // UTF-8, no BOM
{
e = SupportedEncoding.UTF8;
preserve = 4;
}
else if (b1 == 0xFF && b2 == 0xFE) // UTF-16 little endian
{
e = SupportedEncoding.UTF16LE;
preserve = 2;
}
else if (b1 == 0xFE && b2 == 0xFF) // UTF-16 big endian
{
e = SupportedEncoding.UTF16BE;
preserve = 2;
}
else if (b1 == 0x00 && b2 == '<') // UTF-16 big endian, no BOM
{
e = SupportedEncoding.UTF16BE;
if (notOutOfBand && (b3 != 0x00 || b4 != '?'))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlDeclMissing)));
preserve = 4;
}
else if (b1 == '<' && b2 == 0x00) // UTF-16 little endian, no BOM
{
e = SupportedEncoding.UTF16LE;
if (notOutOfBand && (b3 != '?' || b4 != 0x00))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlDeclMissing)));
preserve = 4;
}
else if (b1 == 0xEF && b2 == 0xBB) // UTF8 with BOM
{
// Encoding error
if (notOutOfBand && b3 != 0xBF)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlBadBOM)));
preserve = 1;
}
else // Assume UTF8
{
preserve = 4;
}
return e;
}
void FillBuffer(int count)
{
count -= byteCount;
while (count > 0)
{
int read = stream.Read(bytes, byteOffset + byteCount, count);
if (read == 0)
break;
byteCount += read;
count -= read;
}
}
void EnsureBuffers()
{
EnsureByteBuffer();
if (chars == null)
chars = new char[BufferLength];
}
void EnsureByteBuffer()
{
if (bytes != null)
return;
bytes = new byte[BufferLength * 4];
byteOffset = 0;
byteCount = 0;
}
static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc)
{
byte quot = 0;
int encEq = -1;
int max = offset + Math.Min(count, BufferLength);
// Encoding should be second "=", abort at first "?"
int i = 0;
int eq = 0;
for (i = offset + 2; i < max; i++) // Skip the "<?" so we don't get caught by the first "?"
{
if (quot != 0)
{
if (buffer[i] == quot)
{
quot = 0;
}
continue;
}
if (buffer[i] == (byte)'\'' || buffer[i] == (byte)'"')
{
quot = buffer[i];
}
else if (buffer[i] == (byte)'=')
{
if (eq == 1)
{
encEq = i;
break;
}
eq++;
}
else if (buffer[i] == (byte)'?') // Not legal character in a decl before second "="
{
break;
}
}
// No encoding found
if (encEq == -1)
{
if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlDeclarationRequired)));
return;
}
if (encEq < 28) // Earliest second "=" can appear
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlMalformedDecl)));
// Back off whitespace
for (i = encEq - 1; IsWhitespace(buffer[i]); i--);
// Check for encoding attribute
if (!Compare(encodingAttr, buffer, i - encodingAttr.Length + 1))
{
if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlDeclarationRequired)));
return;
}
// Move ahead of whitespace
for (i = encEq + 1; i < max && IsWhitespace(buffer[i]); i++);
// Find the quotes
if (buffer[i] != '\'' && buffer[i] != '"')
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlMalformedDecl)));
quot = buffer[i];
int q = i;
for (i = q + 1; buffer[i] != quot && i < max; ++i);
if (buffer[i] != quot)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlMalformedDecl)));
int encStart = q + 1;
int encCount = i - encStart;
// lookup the encoding
SupportedEncoding declEnc = e;
if (encCount == encodingUTF8.Length && CompareCaseInsensitive(encodingUTF8, buffer, encStart))
{
declEnc = SupportedEncoding.UTF8;
}
else if (encCount == encodingUnicodeLE.Length && CompareCaseInsensitive(encodingUnicodeLE, buffer, encStart))
{
declEnc = SupportedEncoding.UTF16LE;
}
else if (encCount == encodingUnicodeBE.Length && CompareCaseInsensitive(encodingUnicodeBE, buffer, encStart))
{
declEnc = SupportedEncoding.UTF16BE;
}
else if (encCount == encodingUnicode.Length && CompareCaseInsensitive(encodingUnicode, buffer, encStart))
{
if (e == SupportedEncoding.UTF8)
ThrowEncodingMismatch(SafeUTF8.GetString(buffer, encStart, encCount), SafeUTF8.GetString(encodingUTF8, 0, encodingUTF8.Length));
}
else
{
ThrowEncodingMismatch(SafeUTF8.GetString(buffer, encStart, encCount), e);
}
if (e != declEnc)
ThrowEncodingMismatch(SafeUTF8.GetString(buffer, encStart, encCount), e);
}
static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset)
{
for (int i = 0; i < key.Length; i++)
{
if (key[i] == buffer[offset + i])
continue;
if (key[i] != Char.ToLower((char)buffer[offset + i], System.Globalization.CultureInfo.InvariantCulture))
return false;
}
return true;
}
static bool Compare(byte[] key, byte[] buffer, int offset)
{
for (int i = 0; i < key.Length; i++)
{
if (key[i] != buffer[offset + i])
return false;
}
return true;
}
static bool IsWhitespace(byte ch)
{
return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r';
}
internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding)
{
if (count < 4)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.UnexpectedEndOfFile)));
try
{
int preserve;
ArraySegment<byte> seg;
SupportedEncoding expectedEnc = GetSupportedEncoding(encoding);
SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve);
if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc)
ThrowExpectedEncodingMismatch(expectedEnc, declEnc);
offset += 4 - preserve;
count -= 4 - preserve;
// Fastpath: UTF-8
char[] chars;
byte[] bytes;
Encoding localEnc;
if (declEnc == SupportedEncoding.UTF8)
{
// Fastpath: No declaration
if (buffer[offset + 1] != '?' || buffer[offset] != '<')
{
seg = new ArraySegment<byte>(buffer, offset, count);
return seg;
}
CheckUTF8DeclarationEncoding(buffer, offset, count, declEnc, expectedEnc);
seg = new ArraySegment<byte>(buffer, offset, count);
return seg;
}
// Convert to UTF-8
localEnc = GetSafeEncoding(declEnc);
int inputCount = Math.Min(count, BufferLength * 2);
chars = new char[localEnc.GetMaxCharCount(inputCount)];
int ccount = localEnc.GetChars(buffer, offset, inputCount, chars, 0);
bytes = new byte[ValidatingUTF8.GetMaxByteCount(ccount)];
int bcount = ValidatingUTF8.GetBytes(chars, 0, ccount, bytes, 0);
// Check for declaration
if (bytes[1] == '?' && bytes[0] == '<')
{
CheckUTF8DeclarationEncoding(bytes, 0, bcount, declEnc, expectedEnc);
}
else
{
// Declaration required if no out-of-band encoding
if (expectedEnc == SupportedEncoding.None)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlDeclarationRequired)));
}
seg = new ArraySegment<byte>(ValidatingUTF8.GetBytes(GetEncoding(declEnc).GetChars(buffer, offset, count)));
return seg;
}
catch (DecoderFallbackException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidBytes), e));
}
}
static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc))));
}
static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc)
{
ThrowEncodingMismatch(declEnc, GetEncodingName(enc));
}
static void ThrowEncodingMismatch(string declEnc, string docEnc)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlEncodingMismatch, declEnc, docEnc)));
}
// This stream wrapper does not support duplex
public override bool CanRead
{
get
{
if (!isReading)
return false;
return this.stream.CanRead;
}
}
// The encoding conversion and buffering breaks seeking.
public override bool CanSeek
{
get
{
return false;
}
}
// This stream wrapper does not support duplex
public override bool CanWrite
{
get
{
if (isReading)
return false;
return this.stream.CanWrite;
}
}
// The encoding conversion and buffering breaks seeking.
public override long Position
{
get
{
#pragma warning suppress 56503 // The contract for non seekable stream is to throw exception
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
set
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
}
public override void Close()
{
Flush();
base.Close();
this.stream.Close();
}
public override void Flush()
{
this.stream.Flush();
}
public override int ReadByte()
{
if (byteCount == 0 && encodingCode == SupportedEncoding.UTF8)
return this.stream.ReadByte();
if (Read(byteBuffer, 0, 1) == 0)
return -1;
return byteBuffer[0];
}
public override int Read(byte[] buffer, int offset, int count)
{
try
{
if (byteCount == 0)
{
if (encodingCode == SupportedEncoding.UTF8)
return this.stream.Read(buffer, offset, count);
// No more bytes than can be turned into characters
byteOffset = 0;
byteCount = this.stream.Read(bytes, byteCount, (chars.Length - 1) * 2);
// Check for end of stream
if (byteCount == 0)
return 0;
// Fix up incomplete chars
CleanupCharBreak();
// Change encoding
int charCount = this.encoding.GetChars(bytes, 0, byteCount, chars, 0);
byteCount = Encoding.UTF8.GetBytes(chars, 0, charCount, bytes, 0);
}
// Give them bytes
if (byteCount < count)
count = byteCount;
Buffer.BlockCopy(bytes, byteOffset, buffer, offset, count);
byteOffset += count;
byteCount -= count;
return count;
}
catch (DecoderFallbackException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidBytes), ex));
}
}
void CleanupCharBreak()
{
int max = byteOffset + byteCount;
// Read on 2 byte boundaries
if ((byteCount % 2) != 0)
{
int b = this.stream.ReadByte();
if (b < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.UnexpectedEndOfFile)));
bytes[max++] = (byte)b;
byteCount++;
}
// Don't cut off a surrogate character
int w;
if (encodingCode == SupportedEncoding.UTF16LE)
{
w = bytes[max - 2] + (bytes[max - 1] << 8);
}
else
{
w = bytes[max - 1] + (bytes[max - 2] << 8);
}
if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair
{
int b1 = this.stream.ReadByte();
int b2 = this.stream.ReadByte();
if (b2 < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.UnexpectedEndOfFile)));
bytes[max++] = (byte)b1;
bytes[max++] = (byte)b2;
byteCount += 2;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public override void WriteByte(byte b)
{
if (encodingCode == SupportedEncoding.UTF8)
{
this.stream.WriteByte(b);
return;
}
byteBuffer[0] = b;
Write(byteBuffer, 0, 1);
}
public override void Write(byte[] buffer, int offset, int count)
{
// Optimize UTF-8 case
if (encodingCode == SupportedEncoding.UTF8)
{
this.stream.Write(buffer, offset, count);
return;
}
while (count > 0)
{
int size = chars.Length < count ? chars.Length : count;
int charCount = dec.GetChars(buffer, offset, size, chars, 0, false);
byteCount = enc.GetBytes(chars, 0, charCount, bytes, 0, false);
this.stream.Write(bytes, 0, byteCount);
offset += size;
count -= size;
}
}
// Delegate properties
public override bool CanTimeout { get { return this.stream.CanTimeout; } }
public override long Length { get { return this.stream.Length; } }
public override int ReadTimeout
{
get { return this.stream.ReadTimeout; }
set { this.stream.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return this.stream.WriteTimeout; }
set { this.stream.WriteTimeout = value; }
}
// Delegate methods
public override void SetLength(long value)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
}
// Add format exceptions
// Do we need to modify the stream position/Seek to account for the buffer?
// ASSUMPTION ([....]): This class will only be used for EITHER reading OR writing.
#if NO
class UTF16Stream : Stream
{
const int BufferLength = 128;
Stream stream;
bool bigEndian;
byte[] streamBuffer;
int streamOffset;
int streamMax;
byte[] trailBytes = new byte[4];
int trailCount;
public UTF16Stream(Stream stream, bool bigEndian)
{
this.stream = stream;
this.bigEndian = bigEndian;
this.streamBuffer = byte[BufferLength];
}
public override void Close()
{
Flush();
base.Close();
this.stream.Close();
}
public override void Flush()
{
this.stream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
// Validate args
// Read what we can if we aren't sure we have enough for a single character
if (this.streamMax < 4)
this.streamMax += this.stream.Read(this.streamBuffer, streamOffset, streamBuffer.Length - this.streamMax);
int totalWritten = 0;
while (streamOffset < streamMax && count > 0)
{
int ch;
int read;
read = ReadUTF16Char(out ch, streamBuffer, streamOffset, streamBuffer.Length - streamMax);
if (read == 0)
break;
int written = WriteUTF8Char(ch, buffer, offset, count);
if (written == 0)
break;
totalWritten += written;
streamOffset += read;
offset += written;
count -= written;
}
// Shift down the leftover data
if (this.streamOffset > 0 && this.streamOffset < this.streamMax)
{
Buffer.BlockCopy(this.streamBuffer, this.streamOffset, this.streamBuffer, 0, this.streamMax - this.streamOffset);
this.streamMax -= this.streamOffset;
this.streamOffset = 0;
}
return totalWritten;
}
int ReadUTF8Char(out int ch, byte[] buffer, int offset, int count)
{
ch = -1;
if (buffer[offset] < 0x80)
{
ch = buffer[offset];
return 1;
}
int mask = buffer[offset] & 0xF0;
byte b1, b2, b3, b4;
if (mask == 0xC0)
{
if (count < 2)
return 0;
b1 = buffer[offset + 0];
b2 = buffer[offset + 1];
ch = ((b1 & 0x1F) << 6) + (b2 & 0x3F);
return 2;
}
else if (mask == 0xE0)
{
if (count < 3)
return 0;
b1 = buffer[offset + 0];
b2 = buffer[offset + 1];
b3 = buffer[offset + 2];
ch = ((((b1 & 0x0F) << 6) + (b2 & 0x3F)) << 6) + (b3 & 0x3F);
return 3;
}
else if (mask == 0xF0)
{
if (count < 4)
return 0;
b1 = buffer[offset + 0];
b2 = buffer[offset + 1];
b3 = buffer[offset + 2];
b4 = buffer[offset + 3];
ch = ((((((b1 & 0x0F) << 6) + (b2 & 0x3F)) << 6) + (b3 & 0x3F)) << 6) + (b4 & 0x3F);
return 4;
}
// Invalid
return 0;
}
int ReadUTF16Char(out int ch, byte[] buffer, int offset, int count)
{
ch = -1;
if (count < 2)
return 0;
int w1 = ReadEndian(buffer, offset);
if (w1 < 0xD800 || w1 > 0xDFFF)
{
ch = w1;
return 2;
}
if (count < 4)
return 0;
int w2 = ReadEndian(buffer, offset + 2);
ch = ((w1 & 0x03FF) << 10) + (w2 & 0x03FF);
return 4;
}
int ReadEndian(byte[] buffer, int offset)
{
if (bigEndian)
{
return (buffer[offset + 0] << 8) + buffer[offset + 1];
}
else
{
return (buffer[offset + 1] << 8) + buffer[offset + 0];
}
}
int WriteUTF8Char(int ch, byte[] buffer, int offset, int count)
{
if (ch < 0x80)
{
buffer[offset] = (byte)ch;
return 1;
}
else if (ch < 0x800)
{
if (count < 2)
return 0;
buffer[offset + 1] = 0x80 | (ch & 0x3F);
ch >>= 6;
buffer[offset + 0] = 0xC0 | ch;
return 2
}
else if (ch < 0x10000)
{
if (count < 3)
return 0;
buffer[offset + 2] = 0x80 | (ch & 0x3F);
ch >>= 6;
buffer[offset + 1] = 0x80 | (ch & 0x3F);
ch >>= 6;
buffer[offset + 0] = 0xE0 | ch;
return 3;
}
else if (ch <= 0x110000)
{
if (count < 4)
return 0;
buffer[offset + 3] = 0x80 | (ch & 0x3F);
ch >>= 6;
buffer[offset + 2] = 0x80 | (ch & 0x3F);
ch >>= 6;
buffer[offset + 1] = 0x80 | (ch & 0x3F);
ch >>= 6;
buffer[offset + 0] = 0xF0 | ch;
return 4;
}
// Invalid?
return 0;
}
int WriteUTF16Char(int ch, byte[] buffer, int offset, int count)
{
if (ch < 0x10000)
{
if (count < 2)
return 0;
WriteEndian(ch, buffer, offset);
return 2;
}
if (count < 4)
return 0;
ch -= 0x10000;
int w2 = 0xDC00 | (ch & 0x03FF);
int w1 = 0xD800 | ch >> 10;
WriteEndian(w1, buffer, offset);
WriteEndian(w2, buffer, offset + 2);
return 4;
}
void WriteEndian(int ch, byte[] buffer, int offset)
{
if (bigEndian)
{
buffer[offset + 1] = (byte)ch;
buffer[offset + 0] = ch >> 8;
}
else
{
buffer[offset + 0] = (byte)ch;
buffer[offset + 1] = ch >> 8;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
// Validate args
// Write the trail bytes
if (trailCount > 0)
{
int free = 4-trailCount;
int total = (count < free ? count : free) + trialCount;
Buffer.BlockCopy(buffer, offset, trailBytes, trailCount, total);
int c;
int r = ReadUTF8Char(out c, trailBuffer, 0, total);
if (r == 0 && count < free)
{
trailCount = total;
return;
}
int diff = r - trailCount;
offset += diff;
count -= diff;
streamOffset = WriteUTF16Char(c, streamBuffer, 0, streamBuffer.Length - streamOffset);
}
while (count > 0)
{
if (streamBuffer.Length - streamOffset < 4)
{
this.stream.Write(streamBuffer, 0, streamOffset);
streamOffset = 0;
}
int ch;
int read = ReadUTF8Char(out ch, buffer, offset, count);
if (read == 0)
break;
int written = WriteUTF16Char(ch, streamBuffer, streamOffset, streamBuffer.Length - streamOffset);
if (written == 0)
break;
streamOffset += written;
offset += read;
count -= read;
}
if (streamOffset > 0)
{
this.stream.Write(streamBuffer, 0, streamOffset);
streamOffset = 0;
}
// Save trailing bytes
if (count > 0)
{
Buffer.BlockCopy(buffer, offset, trailBytes, 0, count);
trailCount = count;
}
}
// Delegate properties
public override bool CanRead { get { return this.stream.CanRead; } }
public override bool CanSeek { get { return this.stream.CanSeek; } }
public override bool CanTimeout { get { return this.stream.CanTimeout; } }
public override bool CanWrite { get { return this.stream.CanWrite; } }
public override long Length { get { return this.stream.Length; } }
public override long Position
{
get { return this.stream.Position; }
set { this.stream.Position = value; }
}
public override int ReadTimeout
{
get { return this.stream.ReadTimeout; }
set { this.stream.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return this.stream.WriteTimeout; }
set { this.stream.WriteTimeout = value; }
}
// Delegate methods
public override long Seek(long offset, SeekOrigin origin)
{
return this.stream.Seek(offset, origin);
}
public override void SetLength(long value)
{
this.stream.SetLength(value);
}
}
#endif
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method001.method001;
using System;
public static class Helper
{
public static T Cast<T>(dynamic d)
{
return (T)d;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method001.method001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method001.method001;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic </Title>
// <Description>
// non-generic interface with generic member
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public interface IF1
{
int Foo<T>();
int Bar();
}
public class C : IF1
{
int IF1.Foo<T>()
{
return 0;
}
public int Bar()
{
return 1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new C();
int result = 0;
int error = 0;
try
{
result = d.Foo<int>();
System.Console.WriteLine("Should have thrown out runtime exception!");
error++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, ex.Message, "C", "Foo"))
{
error++;
}
}
var x = Helper.Cast<IF1>(d);
return error;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method002.method002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method002.method002;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic </Title>
// <Description>
// non-generic interface with generic member
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class TestClass
{
[Fact]
public void RunTest()
{
C.DynamicCSharpRunTest();
}
}
public interface IF1
{
int Foo<T>();
int Bar();
}
public struct C : IF1
{
int IF1.Foo<T>()
{
return 0;
}
public int Foo()
{
return 2;
}
public int Bar()
{
return 1;
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new C();
int result = 0;
int error = 0;
try
{
result = d.Foo<int>();
System.Console.WriteLine("Should have thrown out runtime exception!");
error++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
if (!ErrorVerifier.Verify(ErrorMessageId.HasNoTypeVars, ex.Message, "C.Foo()", ErrorVerifier.GetErrorElement(ErrorElementId.SK_METHOD)))
{
error++;
}
}
return error;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method003.method003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method003.method003;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic </Title>
// <Description>
// generic interface with non-generic member
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public interface IF1<T>
{
int Foo();
int Bar();
}
public class C : IF1<int>
{
int IF1<int>.Foo()
{
return 0;
}
public int Foo()
{
return 2;
}
public int Bar()
{
return 1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new C();
int result = 0;
int error = 0;
result = d.Foo();
if (result != 2)
error++;
var x = Helper.Cast<IF1<int>>(d);
try
{
Helper.Cast<IF1<double>>(d);
error++;
}
catch (InvalidCastException)
{
}
return error;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method004.method004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method004.method004;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic </Title>
// <Description>
// generic interface with generic member
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public interface IF1<T>
{
int Foo(T t);
int Bar();
}
public class C : IF1<int>
{
int IF1<int>.Foo(int i)
{
return 0;
}
public int Bar()
{
return 1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new C();
int result = 0;
int error = 0;
try
{
result = d.Foo(1);
error++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, ex.Message, "C", "Foo"))
{
error++;
}
}
var x = Helper.Cast<IF1<int>>(d);
try
{
Helper.Cast<IF1<double>>(d);
error++;
}
catch (InvalidCastException)
{
}
return error;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method005.method005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.method005.method005;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic </Title>
// <Description>
// generic interface with generic member
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public interface IF1<T>
{
int Foo<U>();
int Bar();
}
public class C : IF1<int>
{
int IF1<int>.Foo<U>()
{
return 0;
}
public int Bar()
{
return 1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new C();
int result = 0;
int error = 0;
try
{
result = d.Foo<int>();
error++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, ex.Message, "C", "Foo"))
{
error++;
}
}
var x = Helper.Cast<IF1<int>>(d);
try
{
Helper.Cast<IF1<double>>(d);
error++;
}
catch (InvalidCastException)
{
}
return error;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.contravariance001.contravariance001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.contravariance001.contravariance001;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic : variance</Title>
// <Description>
// contra-variance (negative)
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Animal
{
}
public class Tiger : Animal
{
}
public interface IF<in T>
{
int Foo(T t);
}
public class ContraVar<T> : IF<T>
{
int IF<T>.Foo(T t)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new ContraVar<Animal>();
int error = 0;
try
{
d.Foo();
error++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, ex.Message, "ContraVar<Animal>", "Foo"))
{
error++;
}
}
var x = Helper.Cast<IF<Tiger>>(d);
var y = Helper.Cast<IF<Animal>>(d);
return error;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.contravariance002.contravariance002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.contravariance002.contravariance002;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic : variance</Title>
// <Description>
// contra-variance (negative)
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Animal
{
}
public class Tiger : Animal
{
}
public interface IF<in T>
{
int Foo(T t);
}
public class ContraVar<T> : IF<T>
{
int IF<T>.Foo(T t)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new ContraVar<Tiger>();
int error = 0;
try
{
d.Foo();
error++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, ex.Message, "ContraVar<Tiger>", "Foo"))
{
error++;
}
}
try
{
var x = Helper.Cast<IF<Animal>>(d);
error++;
}
catch (InvalidCastException ex)
{
}
var y = Helper.Cast<IF<Tiger>>(d);
try
{
var z = ((IF<Animal>)d).Foo(new Animal());
error++;
}
catch (InvalidCastException ex)
{
}
return error;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.covariance001.covariance001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.covariance001.covariance001;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic : variance</Title>
// <Description>
// co-variance
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Animal
{
}
public class Tiger : Animal
{
}
public interface IF<out T>
{
T Foo();
}
public class CoVar<T> : IF<T> where T : new()
{
T IF<T>.Foo()
{
return new T();
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new CoVar<Tiger>();
int error = 0;
try
{
d.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, ex.Message, "CoVar<Tiger>", "Foo"))
{
error++;
}
}
var x = Helper.Cast<IF<Tiger>>(d);
var y = Helper.Cast<IF<Animal>>(d);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.covariance002.covariance002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.helper.helper;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.ExplicitImple.Generic.covariance002.covariance002;
// <Area> Dynamic -- explicitly implemented interface member</Area>
// <Title> Generic : variance</Title>
// <Description>
// co-variance
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Animal
{
}
public class Tiger : Animal
{
}
public interface IF<out T>
{
T Foo();
}
public class CoVar<T> : IF<T> where T : new()
{
T IF<T>.Foo()
{
return new T();
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new CoVar<Animal>();
int error = 0;
try
{
d.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
}
try
{
var x = Helper.Cast<IF<Tiger>>(d);
}
catch (InvalidCastException ex)
{
}
var y = Helper.Cast<IF<Animal>>(d);
try
{
var z = ((IF<Tiger>)d).Foo();
}
catch (InvalidCastException ex)
{
}
return error;
}
}
// </Code>
}
| |
// 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.ComponentModel
{
/// <summary>
/// Encapsulates zero or more components.
/// </summary>
public class Container : IContainer
{
private ISite[] _sites;
private int _siteCount;
private ComponentCollection _components;
private ContainerFilterService _filter;
private bool _checkedFilter;
private readonly object _syncObj = new object();
~Container() => Dispose(false);
/// <summary>
/// Adds the specified component to the <see cref='System.ComponentModel.Container'/>
/// The component is unnamed.
/// </summary>
public virtual void Add(IComponent component) => Add(component, null);
// Adds a component to the container.
/// <summary>
/// Adds the specified component to the <see cref='System.ComponentModel.Container'/> and assigns
/// a name to it.
/// </summary>
public virtual void Add(IComponent component, string name)
{
lock (_syncObj)
{
if (component == null)
{
return;
}
ISite site = component.Site;
if (site != null && site.Container == this)
{
return;
}
if (_sites == null)
{
_sites = new ISite[4];
}
else
{
// Validate that new components have either a null name or a unique one.
ValidateName(component, name);
if (_sites.Length == _siteCount)
{
ISite[] newSites = new ISite[_siteCount * 2];
Array.Copy(_sites, 0, newSites, 0, _siteCount);
_sites = newSites;
}
}
site?.Container.Remove(component);
ISite newSite = CreateSite(component, name);
_sites[_siteCount++] = newSite;
component.Site = newSite;
_components = null;
}
}
/// <summary>
/// Creates a Site <see cref='System.ComponentModel.ISite'/> for the given <see cref='System.ComponentModel.IComponent'/>
/// and assigns the given name to the site.
/// </summary>
protected virtual ISite CreateSite(IComponent component, string name)
{
return new Site(component, this, name);
}
/// <summary>
/// Disposes of the container. A call to the Dispose method indicates that
/// the user of the container has no further need for it.
///
/// The implementation of Dispose must:
///
/// (1) Remove any references the container is holding to other components.
/// This is typically accomplished by assigning null to any fields that
/// contain references to other components.
///
/// (2) Release any system resources that are associated with the container,
/// such as file handles, window handles, or database connections.
///
/// (3) Dispose of child components by calling the Dispose method of each.
///
/// Ideally, a call to Dispose will revert a container to the state it was
/// in immediately after it was created. However, this is not a requirement.
/// Following a call to its Dispose method, a container is permitted to raise
/// exceptions for operations that cannot meaningfully be performed.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (_syncObj)
{
while (_siteCount > 0)
{
ISite site = _sites[--_siteCount];
site.Component.Site = null;
site.Component.Dispose();
}
_sites = null;
_components = null;
}
}
}
protected virtual object GetService(Type service) => service == typeof(IContainer) ? this : null;
/// <summary>
/// Gets all the components in the <see cref='System.ComponentModel.Container'/>.
/// </summary>
public virtual ComponentCollection Components
{
get
{
lock (_syncObj)
{
if (_components == null)
{
IComponent[] result = new IComponent[_siteCount];
for (int i = 0; i < _siteCount; i++)
{
result[i] = _sites[i].Component;
}
_components = new ComponentCollection(result);
// At each component add, if we don't yet have a filter, look for one.
// Components may add filters.
if (_filter == null && _checkedFilter)
{
_checkedFilter = false;
}
}
if (!_checkedFilter)
{
_filter = GetService(typeof(ContainerFilterService)) as ContainerFilterService;
_checkedFilter = true;
}
if (_filter != null)
{
ComponentCollection filteredComponents = _filter.FilterComponents(_components);
if (filteredComponents != null)
{
_components = filteredComponents;
}
}
return _components;
}
}
}
/// <summary>
/// Removes a component from the <see cref='System.ComponentModel.Container'/>.
/// </summary>
public virtual void Remove(IComponent component) => Remove(component, false);
private void Remove(IComponent component, bool preserveSite)
{
lock (_syncObj)
{
ISite site = component?.Site;
if (site == null || site.Container != this)
{
return;
}
if (!preserveSite)
{
component.Site = null;
}
for (int i = 0; i < _siteCount; i++)
{
if (_sites[i] == site)
{
_siteCount--;
Array.Copy(_sites, i + 1, _sites, i, _siteCount - i);
_sites[_siteCount] = null;
_components = null;
break;
}
}
}
}
protected void RemoveWithoutUnsiting(IComponent component) => Remove(component, true);
/// <summary>
/// Validates that the given name is valid for a component. The default implementation
/// verifies that name is either null or unique compared to the names of other
/// components in the container.
/// </summary>
protected virtual void ValidateName(IComponent component, string name)
{
if (component == null)
{
throw new ArgumentNullException(nameof(component));
}
if (name != null)
{
for (int i = 0; i < Math.Min(_siteCount, _sites.Length); i++)
{
ISite s = _sites[i];
if (s?.Name != null && string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase) && s.Component != component)
{
InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(s.Component)[typeof(InheritanceAttribute)];
if (inheritanceAttribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly)
{
throw new ArgumentException(SR.Format(SR.DuplicateComponentName, name));
}
}
}
}
}
private class Site : ISite
{
private string _name;
internal Site(IComponent component, Container container, string name)
{
Component = component;
Container = container;
_name = name;
}
/// <summary>
/// The component sited by this component site.
/// </summary>
public IComponent Component { get; }
/// <summary>
/// The container in which the component is sited.
/// </summary>
public IContainer Container { get; }
public object GetService(Type service)
{
return ((service == typeof(ISite)) ? this : ((Container)Container).GetService(service));
}
/// <summary>
/// Indicates whether the component is in design mode.
/// </summary>
public bool DesignMode => false;
/// <summary>
/// The name of the component.
/// </summary>
public string Name
{
get => _name;
set
{
if (value == null || _name == null || !value.Equals(_name))
{
((Container)Container).ValidateName(Component, value);
_name = value;
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>Provides an <see langword='abstract '/>base class to
/// create new debugging and tracing switches.</para>
/// </devdoc>
public abstract class Switch
{
private readonly string _description;
private readonly string _displayName;
private int _switchSetting = 0;
private volatile bool _initialized = false;
private bool _initializing = false;
private volatile string _switchValueString = string.Empty;
private string _defaultValue;
private object _initializedLock;
private static List<WeakReference> s_switches = new List<WeakReference>();
private static int s_LastCollectionCount;
private StringDictionary _attributes;
private object InitializedLock
{
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
get
{
if (_initializedLock == null)
{
object o = new object();
Interlocked.CompareExchange<Object>(ref _initializedLock, o, null);
}
return _initializedLock;
}
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Diagnostics.Switch'/>
/// class.</para>
/// </devdoc>
protected Switch(string displayName, string description) : this(displayName, description, "0")
{
}
protected Switch(string displayName, string description, string defaultSwitchValue)
{
// displayName is used as a hashtable key, so it can never
// be null.
if (displayName == null) displayName = string.Empty;
_displayName = displayName;
_description = description;
// Add a weakreference to this switch and cleanup invalid references
lock (s_switches)
{
_pruneCachedSwitches();
s_switches.Add(new WeakReference(this));
}
_defaultValue = defaultSwitchValue;
}
private static void _pruneCachedSwitches()
{
lock (s_switches)
{
if (s_LastCollectionCount != GC.CollectionCount(2))
{
List<WeakReference> buffer = new List<WeakReference>(s_switches.Count);
for (int i = 0; i < s_switches.Count; i++)
{
Switch s = ((Switch)s_switches[i].Target);
if (s != null)
{
buffer.Add(s_switches[i]);
}
}
if (buffer.Count < s_switches.Count)
{
s_switches.Clear();
s_switches.AddRange(buffer);
s_switches.TrimExcess();
}
s_LastCollectionCount = GC.CollectionCount(2);
}
}
}
/// <devdoc>
/// <para>Gets a name used to identify the switch.</para>
/// </devdoc>
public string DisplayName
{
get
{
return _displayName;
}
}
/// <devdoc>
/// <para>Gets a description of the switch.</para>
/// </devdoc>
public string Description
{
get
{
return (_description == null) ? string.Empty : _description;
}
}
public StringDictionary Attributes
{
get
{
Initialize();
if (_attributes == null)
_attributes = new StringDictionary();
return _attributes;
}
}
/// <devdoc>
/// <para>
/// Indicates the current setting for this switch.
/// </para>
/// </devdoc>
protected int SwitchSetting
{
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "reviewed for thread-safety")]
get
{
if (!_initialized)
{
if (InitializeWithStatus())
OnSwitchSettingChanged();
}
return _switchSetting;
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "reviewed for thread-safety")]
set
{
bool didUpdate = false;
lock (InitializedLock)
{
_initialized = true;
if (_switchSetting != value)
{
_switchSetting = value;
didUpdate = true;
}
}
if (didUpdate)
{
OnSwitchSettingChanged();
}
}
}
protected internal virtual string[] GetSupportedAttributes() => null;
protected string Value
{
get
{
Initialize();
return _switchValueString;
}
set
{
Initialize();
_switchValueString = value;
OnValueChanged();
}
}
private void Initialize()
{
InitializeWithStatus();
}
private bool InitializeWithStatus()
{
if (!_initialized)
{
lock (InitializedLock)
{
if (_initialized || _initializing)
{
return false;
}
// This method is re-entrent during initialization, since calls to OnValueChanged() in subclasses could end up having InitializeWithStatus()
// called again, we don't want to get caught in an infinite loop.
_initializing = true;
_switchValueString = _defaultValue;
OnValueChanged();
_initialized = true;
_initializing = false;
}
}
return true;
}
/// <devdoc>
/// This method is invoked when a switch setting has been changed. It will
/// be invoked the first time a switch reads its value from the registry
/// or environment, and then it will be invoked each time the switch's
/// value is changed.
/// </devdoc>
protected virtual void OnSwitchSettingChanged()
{
}
protected virtual void OnValueChanged()
{
SwitchSetting = int.Parse(Value, CultureInfo.InvariantCulture);
}
internal static void RefreshAll()
{
lock (s_switches)
{
_pruneCachedSwitches();
for (int i = 0; i < s_switches.Count; i++)
{
Switch swtch = ((Switch)s_switches[i].Target);
if (swtch != null)
{
swtch.Refresh();
}
}
}
}
internal void Refresh()
{
lock (InitializedLock)
{
_initialized = false;
Initialize();
}
}
}
}
| |
namespace RFID_full
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.tagTxt = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.keyboardCheckBox = new System.Windows.Forms.CheckBox();
this.output1chk = new System.Windows.Forms.CheckBox();
this.ledChk = new System.Windows.Forms.CheckBox();
this.output0Chk = new System.Windows.Forms.CheckBox();
this.label5 = new System.Windows.Forms.Label();
this.outputsTxt = new System.Windows.Forms.TextBox();
this.versionTxt = new System.Windows.Forms.TextBox();
this.serialTxt = new System.Windows.Forms.TextBox();
this.nameTxt = new System.Windows.Forms.TextBox();
this.attachedTxt = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.antennaChk = new System.Windows.Forms.CheckBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.protoTxt = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.writeBox = new System.Windows.Forms.GroupBox();
this.label8 = new System.Windows.Forms.Label();
this.writeTagTxt = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.writeProtoCmb = new System.Windows.Forms.ComboBox();
this.writeBtn = new System.Windows.Forms.Button();
this.writeLockChk = new System.Windows.Forms.CheckBox();
this.groupBox2.SuspendLayout();
this.groupBox1.SuspendLayout();
this.writeBox.SuspendLayout();
this.SuspendLayout();
//
// groupBox2
//
this.groupBox2.Controls.Add(this.protoTxt);
this.groupBox2.Controls.Add(this.label7);
this.groupBox2.Controls.Add(this.tagTxt);
this.groupBox2.Controls.Add(this.label6);
this.groupBox2.Location = new System.Drawing.Point(12, 315);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(268, 74);
this.groupBox2.TabIndex = 3;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Tag Read";
//
// tagTxt
//
this.tagTxt.Location = new System.Drawing.Point(90, 19);
this.tagTxt.Name = "tagTxt";
this.tagTxt.ReadOnly = true;
this.tagTxt.Size = new System.Drawing.Size(172, 20);
this.tagTxt.TabIndex = 1;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(16, 22);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(59, 13);
this.label6.TabIndex = 0;
this.label6.Text = "Tag String:";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.keyboardCheckBox);
this.groupBox1.Controls.Add(this.output1chk);
this.groupBox1.Controls.Add(this.ledChk);
this.groupBox1.Controls.Add(this.output0Chk);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.outputsTxt);
this.groupBox1.Controls.Add(this.versionTxt);
this.groupBox1.Controls.Add(this.serialTxt);
this.groupBox1.Controls.Add(this.nameTxt);
this.groupBox1.Controls.Add(this.attachedTxt);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.antennaChk);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(268, 297);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "RFID Reader Info";
//
// keyboardCheckBox
//
this.keyboardCheckBox.AutoSize = true;
this.keyboardCheckBox.Location = new System.Drawing.Point(19, 270);
this.keyboardCheckBox.Name = "keyboardCheckBox";
this.keyboardCheckBox.Size = new System.Drawing.Size(148, 17);
this.keyboardCheckBox.TabIndex = 14;
this.keyboardCheckBox.Text = "Keyboard Output Enabled";
this.keyboardCheckBox.UseVisualStyleBackColor = true;
//
// output1chk
//
this.output1chk.AutoSize = true;
this.output1chk.Location = new System.Drawing.Point(133, 247);
this.output1chk.Name = "output1chk";
this.output1chk.Size = new System.Drawing.Size(67, 17);
this.output1chk.TabIndex = 13;
this.output1chk.Text = "Output 1";
this.output1chk.UseVisualStyleBackColor = true;
this.output1chk.CheckedChanged += new System.EventHandler(this.output1chk_CheckedChanged);
//
// ledChk
//
this.ledChk.AutoSize = true;
this.ledChk.Location = new System.Drawing.Point(19, 247);
this.ledChk.Name = "ledChk";
this.ledChk.Size = new System.Drawing.Size(86, 17);
this.ledChk.TabIndex = 12;
this.ledChk.Text = "Led Enabled";
this.ledChk.UseVisualStyleBackColor = true;
this.ledChk.CheckedChanged += new System.EventHandler(this.ledChk_CheckedChanged);
//
// output0Chk
//
this.output0Chk.AutoSize = true;
this.output0Chk.Location = new System.Drawing.Point(133, 224);
this.output0Chk.Name = "output0Chk";
this.output0Chk.Size = new System.Drawing.Size(67, 17);
this.output0Chk.TabIndex = 11;
this.output0Chk.Text = "Output 0";
this.output0Chk.UseVisualStyleBackColor = true;
this.output0Chk.CheckedChanged += new System.EventHandler(this.output0Chk_CheckedChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(16, 186);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(47, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Outputs:";
//
// outputsTxt
//
this.outputsTxt.Location = new System.Drawing.Point(85, 183);
this.outputsTxt.Name = "outputsTxt";
this.outputsTxt.ReadOnly = true;
this.outputsTxt.Size = new System.Drawing.Size(177, 20);
this.outputsTxt.TabIndex = 9;
//
// versionTxt
//
this.versionTxt.Location = new System.Drawing.Point(85, 147);
this.versionTxt.Name = "versionTxt";
this.versionTxt.ReadOnly = true;
this.versionTxt.Size = new System.Drawing.Size(177, 20);
this.versionTxt.TabIndex = 8;
//
// serialTxt
//
this.serialTxt.Location = new System.Drawing.Point(85, 113);
this.serialTxt.Name = "serialTxt";
this.serialTxt.ReadOnly = true;
this.serialTxt.Size = new System.Drawing.Size(177, 20);
this.serialTxt.TabIndex = 7;
//
// nameTxt
//
this.nameTxt.Location = new System.Drawing.Point(85, 56);
this.nameTxt.Multiline = true;
this.nameTxt.Name = "nameTxt";
this.nameTxt.ReadOnly = true;
this.nameTxt.Size = new System.Drawing.Size(177, 48);
this.nameTxt.TabIndex = 6;
//
// attachedTxt
//
this.attachedTxt.Location = new System.Drawing.Point(85, 27);
this.attachedTxt.Name = "attachedTxt";
this.attachedTxt.ReadOnly = true;
this.attachedTxt.Size = new System.Drawing.Size(177, 20);
this.attachedTxt.TabIndex = 5;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(16, 150);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(45, 13);
this.label4.TabIndex = 4;
this.label4.Text = "Version:";
//
// antennaChk
//
this.antennaChk.AutoSize = true;
this.antennaChk.Location = new System.Drawing.Point(19, 224);
this.antennaChk.Name = "antennaChk";
this.antennaChk.Size = new System.Drawing.Size(108, 17);
this.antennaChk.TabIndex = 3;
this.antennaChk.Text = "Antenna Enabled";
this.antennaChk.UseVisualStyleBackColor = true;
this.antennaChk.CheckedChanged += new System.EventHandler(this.antennaChk_CheckedChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(16, 116);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(56, 13);
this.label3.TabIndex = 2;
this.label3.Text = "Serial No.:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(16, 59);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(38, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Name:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(16, 30);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Attached:";
//
// protoTxt
//
this.protoTxt.Location = new System.Drawing.Point(90, 45);
this.protoTxt.Name = "protoTxt";
this.protoTxt.ReadOnly = true;
this.protoTxt.Size = new System.Drawing.Size(172, 20);
this.protoTxt.TabIndex = 3;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(16, 48);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(49, 13);
this.label7.TabIndex = 2;
this.label7.Text = "Protocol:";
//
// writeBox
//
this.writeBox.Controls.Add(this.writeLockChk);
this.writeBox.Controls.Add(this.writeBtn);
this.writeBox.Controls.Add(this.writeProtoCmb);
this.writeBox.Controls.Add(this.label8);
this.writeBox.Controls.Add(this.writeTagTxt);
this.writeBox.Controls.Add(this.label9);
this.writeBox.Location = new System.Drawing.Point(12, 395);
this.writeBox.Name = "writeBox";
this.writeBox.Size = new System.Drawing.Size(268, 104);
this.writeBox.TabIndex = 4;
this.writeBox.TabStop = false;
this.writeBox.Text = "Tag Write";
this.writeBox.Visible = false;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(16, 48);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(49, 13);
this.label8.TabIndex = 2;
this.label8.Text = "Protocol:";
//
// writeTagTxt
//
this.writeTagTxt.Location = new System.Drawing.Point(90, 19);
this.writeTagTxt.Name = "writeTagTxt";
this.writeTagTxt.Size = new System.Drawing.Size(172, 20);
this.writeTagTxt.TabIndex = 1;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(16, 22);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(59, 13);
this.label9.TabIndex = 0;
this.label9.Text = "Tag String:";
//
// writeProtoCmb
//
this.writeProtoCmb.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.writeProtoCmb.FormattingEnabled = true;
this.writeProtoCmb.Location = new System.Drawing.Point(90, 45);
this.writeProtoCmb.Name = "writeProtoCmb";
this.writeProtoCmb.Size = new System.Drawing.Size(172, 21);
this.writeProtoCmb.TabIndex = 3;
//
// writeBtn
//
this.writeBtn.Location = new System.Drawing.Point(187, 72);
this.writeBtn.Name = "writeBtn";
this.writeBtn.Size = new System.Drawing.Size(75, 23);
this.writeBtn.TabIndex = 4;
this.writeBtn.Text = "Write";
this.writeBtn.UseVisualStyleBackColor = true;
this.writeBtn.Click += new System.EventHandler(this.writeBtn_Click);
//
// writeLockChk
//
this.writeLockChk.AutoSize = true;
this.writeLockChk.Location = new System.Drawing.Point(90, 76);
this.writeLockChk.Name = "writeLockChk";
this.writeLockChk.Size = new System.Drawing.Size(50, 17);
this.writeLockChk.TabIndex = 5;
this.writeLockChk.Text = "Lock";
this.writeLockChk.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(290, 511);
this.Controls.Add(this.writeBox);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximumSize = new System.Drawing.Size(298, 545);
this.MinimumSize = new System.Drawing.Size(298, 433);
this.Name = "Form1";
this.Text = "RFID-full";
this.Load += new System.EventHandler(this.Form1_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.writeBox.ResumeLayout(false);
this.writeBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TextBox tagTxt;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox output1chk;
private System.Windows.Forms.CheckBox ledChk;
private System.Windows.Forms.CheckBox output0Chk;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox outputsTxt;
private System.Windows.Forms.TextBox versionTxt;
private System.Windows.Forms.TextBox serialTxt;
private System.Windows.Forms.TextBox nameTxt;
private System.Windows.Forms.TextBox attachedTxt;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox antennaChk;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox keyboardCheckBox;
private System.Windows.Forms.TextBox protoTxt;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.GroupBox writeBox;
private System.Windows.Forms.Button writeBtn;
private System.Windows.Forms.ComboBox writeProtoCmb;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox writeTagTxt;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.CheckBox writeLockChk;
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Internal;
using Results;
using Validators;
/// <summary>
/// Base class for entity validator classes.
/// </summary>
/// <typeparam name="T">The type of the object being validated</typeparam>
public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidationRule> {
readonly TrackingCollection<IValidationRule> nestedValidators = new TrackingCollection<IValidationRule>();
// Work-around for reflection bug in .NET 4.5
static Func<CascadeMode> s_cascadeMode = () => ValidatorOptions.CascadeMode;
Func<CascadeMode> cascadeMode = s_cascadeMode;
/// <summary>
/// Sets the cascade mode for all rules within this validator.
/// </summary>
public CascadeMode CascadeMode {
get { return cascadeMode(); }
set { cascadeMode = () => value; }
}
ValidationResult IValidator.Validate(object instance) {
instance.Guard("Cannot pass null to Validate.");
if(! ((IValidator)this).CanValidateInstancesOfType(instance.GetType())) {
throw new InvalidOperationException(string.Format("Cannot validate instances of type '{0}'. This validator can only validate instances of type '{1}'.", instance.GetType().Name, typeof(T).Name));
}
return Validate((T)instance);
}
Task<ValidationResult> IValidator.ValidateAsync(object instance, CancellationToken cancellation = new CancellationToken()) {
instance.Guard("Cannot pass null to Validate.");
if (!((IValidator) this).CanValidateInstancesOfType(instance.GetType())) {
throw new InvalidOperationException(string.Format("Cannot validate instances of type '{0}'. This validator can only validate instances of type '{1}'.", instance.GetType().Name, typeof (T).Name));
}
return ValidateAsync((T) instance, cancellation);
}
ValidationResult IValidator.Validate(ValidationContext context)
{
context.Guard("Cannot pass null to Validate");
var newContext = new ValidationContext<T>((T)context.InstanceToValidate, context.PropertyChain, context.Selector) {
IsChildContext = context.IsChildContext
};
return Validate(newContext);
}
Task<ValidationResult> IValidator.ValidateAsync(ValidationContext context, CancellationToken cancellation) {
context.Guard("Cannot pass null to Validate");
var newContext = new ValidationContext<T>((T) context.InstanceToValidate, context.PropertyChain, context.Selector) {
IsChildContext = context.IsChildContext
};
return ValidateAsync(newContext, cancellation);
}
/// <summary>
/// Validates the specified instance
/// </summary>
/// <param name="instance">The object to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
public virtual ValidationResult Validate(T instance) {
return Validate(new ValidationContext<T>(instance, new PropertyChain(), new DefaultValidatorSelector()));
}
/// <summary>
/// Validates the specified instance asynchronously
/// </summary>
/// <param name="instance">The object to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
public Task<ValidationResult> ValidateAsync(T instance, CancellationToken cancellation = new CancellationToken()) {
return ValidateAsync(new ValidationContext<T>(instance, new PropertyChain(), new DefaultValidatorSelector()), cancellation);
}
/// <summary>
/// Validates the specified instance.
/// </summary>
/// <param name="context">Validation Context</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
public virtual ValidationResult Validate(ValidationContext<T> context) {
context.Guard("Cannot pass null to Validate");
var failures = nestedValidators.SelectMany(x => x.Validate(context)).ToList();
return new ValidationResult(failures);
}
/// <summary>
/// Validates the specified instance asynchronously.
/// </summary>
/// <param name="context">Validation Context</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
public virtual Task<ValidationResult> ValidateAsync(ValidationContext<T> context, CancellationToken cancellation = new CancellationToken()) {
context.Guard("Cannot pass null to Validate");
var failures = new List<ValidationFailure>();
return TaskHelpers.Iterate(
nestedValidators
.Select(v => v.ValidateAsync(context, cancellation).Then(fs => failures.AddRange(fs), runSynchronously: true))
).Then(
() => new ValidationResult(failures)
);
}
/// <summary>
/// Adds a rule to the current validator.
/// </summary>
/// <param name="rule"></param>
public void AddRule(IValidationRule rule) {
nestedValidators.Add(rule);
}
/// <summary>
/// Creates a <see cref="IValidatorDescriptor" /> that can be used to obtain metadata about the current validator.
/// </summary>
public virtual IValidatorDescriptor CreateDescriptor() {
return new ValidatorDescriptor<T>(nestedValidators);
}
bool IValidator.CanValidateInstancesOfType(Type type) {
return typeof(T).IsAssignableFrom(type);
}
/// <summary>
/// Defines a validation rule for a specify property.
/// </summary>
/// <example>
/// RuleFor(x => x.Surname)...
/// </example>
/// <typeparam name="TProperty">The type of property being validated</typeparam>
/// <param name="expression">The expression representing the property to validate</param>
/// <returns>an IRuleBuilder instance on which validators can be defined</returns>
public IRuleBuilderInitial<T, TProperty> RuleFor<TProperty>(Expression<Func<T, TProperty>> expression) {
expression.Guard("Cannot pass null to RuleFor");
var rule = PropertyRule.Create(expression, () => CascadeMode);
AddRule(rule);
var ruleBuilder = new RuleBuilder<T, TProperty>(rule);
return ruleBuilder;
}
public IRuleBuilderInitial<T, TProperty> RuleForEach<TProperty>(Expression<Func<T, IEnumerable<TProperty>>> expression) {
expression.Guard("Cannot pass null to RuleForEach");
var rule = CollectionPropertyRule<TProperty>.Create(expression, () => CascadeMode);
AddRule(rule);
var ruleBuilder = new RuleBuilder<T, TProperty>(rule);
return ruleBuilder;
}
/// <summary>
/// Defines a custom validation rule using a lambda expression.
/// If the validation rule fails, it should return a instance of a <see cref="ValidationFailure">ValidationFailure</see>
/// If the validation rule succeeds, it should return null.
/// </summary>
/// <param name="customValidator">A lambda that executes custom validation rules.</param>
public void Custom(Func<T, ValidationFailure> customValidator) {
customValidator.Guard("Cannot pass null to Custom");
AddRule(new DelegateValidator<T>(x => new[] { customValidator(x) }));
}
/// <summary>
/// Defines a custom validation rule using a lambda expression.
/// If the validation rule fails, it should return an instance of <see cref="ValidationFailure">ValidationFailure</see>
/// If the validation rule succeeds, it should return null.
/// </summary>
/// <param name="customValidator">A lambda that executes custom validation rules</param>
public void Custom(Func<T, ValidationContext<T>, ValidationFailure> customValidator) {
customValidator.Guard("Cannot pass null to Custom");
AddRule(new DelegateValidator<T>((x, ctx) => new[] { customValidator(x, ctx) }));
}
/// <summary>
/// Defines a custom asynchronous validation rule using a lambda expression.
/// If the validation rule fails, it should asynchronously return a instance of a <see cref="ValidationFailure">ValidationFailure</see>
/// If the validation rule succeeds, it should return null.
/// </summary>
/// <param name="customValidator">A lambda that executes custom validation rules.</param>
public void CustomAsync(Func<T, Task<ValidationFailure>> customValidator) {
customValidator.Guard("Cannot pass null to Custom");
AddRule(new DelegateValidator<T>(x => customValidator(x).Then(f => new[] {f}.AsEnumerable(), runSynchronously: true)));
}
/// <summary>
/// Defines a custom asynchronous validation rule using a lambda expression.
/// If the validation rule fails, it should asynchronously return an instance of <see cref="ValidationFailure">ValidationFailure</see>
/// If the validation rule succeeds, it should return null.
/// </summary>
/// <param name="customValidator">A lambda that executes custom validation rules</param>
public void CustomAsync(Func<T, ValidationContext<T>, CancellationToken, Task<ValidationFailure>> customValidator) {
customValidator.Guard("Cannot pass null to Custom");
AddRule(new DelegateValidator<T>((x, ctx, cancel) => customValidator(x, ctx, cancel).Then(f => new[] {f}.AsEnumerable(), runSynchronously: true)));
}
/// <summary>
/// Defines a RuleSet that can be used to group together several validators.
/// </summary>
/// <param name="ruleSetName">The name of the ruleset.</param>
/// <param name="action">Action that encapsulates the rules in the ruleset.</param>
public void RuleSet(string ruleSetName, Action action) {
ruleSetName.Guard("A name must be specified when calling RuleSet.");
action.Guard("A ruleset definition must be specified when calling RuleSet.");
using (nestedValidators.OnItemAdded(r => r.RuleSet = ruleSetName)) {
action();
}
}
/// <summary>
/// Defines a condition that applies to several rules
/// </summary>
/// <param name="predicate">The condition that should apply to multiple rules</param>
/// <param name="action">Action that encapsulates the rules.</param>
/// <returns></returns>
public void When(Func<T, bool> predicate, Action action) {
var propertyRules = new List<IValidationRule>();
Action<IValidationRule> onRuleAdded = propertyRules.Add;
using(nestedValidators.OnItemAdded(onRuleAdded)) {
action();
}
// Must apply the predicate after the rule has been fully created to ensure any rules-specific conditions have already been applied.
propertyRules.ForEach(x => x.ApplyCondition(predicate.CoerceToNonGeneric()));
}
/// <summary>
/// Defines an inverse condition that applies to several rules
/// </summary>
/// <param name="predicate">The condition that should be applied to multiple rules</param>
/// <param name="action">Action that encapsulates the rules</param>
public void Unless(Func<T, bool> predicate, Action action) {
When(x => !predicate(x), action);
}
/// <summary>
/// Defines an asynchronous condition that applies to several rules
/// </summary>
/// <param name="predicate">The asynchronous condition that should apply to multiple rules</param>
/// <param name="action">Action that encapsulates the rules.</param>
/// <returns></returns>
public void WhenAsync(Func<T, Task<bool>> predicate, Action action)
{
var propertyRules = new List<IValidationRule>();
Action<IValidationRule> onRuleAdded = propertyRules.Add;
using (nestedValidators.OnItemAdded(onRuleAdded))
{
action();
}
// Must apply the predicate after the rule has been fully created to ensure any rules-specific conditions have already been applied.
propertyRules.ForEach(x => x.ApplyAsyncCondition(predicate.CoerceToNonGeneric()));
}
/// <summary>
/// Defines an inverse asynchronous condition that applies to several rules
/// </summary>
/// <param name="predicate">The asynchronous condition that should be applied to multiple rules</param>
/// <param name="action">Action that encapsulates the rules</param>
public void UnlessAsync(Func<T, Task<bool>> predicate, Action action)
{
WhenAsync(x => predicate(x).Then(y => !y), action);
}
/// <summary>
/// Returns an enumerator that iterates through the collection of validation rules.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<IValidationRule> GetEnumerator() {
return nestedValidators.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
public class DependentRules<T> : AbstractValidator<T> {
}
}
| |
// 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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Web.Script.Serialization;
namespace Microsoft.NodejsTools.SourceMapping
{
/// <summary>
/// Reads a V3 source map as documented at https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?hl=en_US&pli=1&pli=1
/// </summary>
internal class SourceMap
{
private readonly Dictionary<string, object> _mapInfo;
private readonly LineInfo[] _lines;
private readonly string[] _names, _sources;
private static Dictionary<char, int> _base64Mapping = BuildBase64Mapping();
/// <summary>
/// Index into the mappings for the starting column
/// </summary>
private const int SourceStartingIndex = 0;
/// <summary>
/// Index into the mappings for the sources list index (optional)
/// </summary>
private const int SourcesIndex = 1;
/// <summary>
/// Index into the mappings for the zero-based starting line (optional)
/// </summary>
private const int OriginalLineIndex = 2;
/// <summary>
/// Index into the mappings for the zero-based starting column (optional)
/// </summary>
private const int OriginalColumnIndex = 3;
/// <summary>
/// Index into the mappings of the names list
/// </summary>
private const int NamesIndex = 4;
/// <summary>
/// Creates a new source map from the given input. Raises InvalidOperationException
/// if the file is not supported or invalid.
/// </summary>
/// <param name="input"></param>
internal SourceMap(TextReader input)
{
var serializer = new JavaScriptSerializer();
this._mapInfo = serializer.Deserialize<Dictionary<string, object>>(input.ReadToEnd());
if (this.Version != 3)
{
throw new NotSupportedException("Only V3 source maps are supported");
}
object value;
if (this._mapInfo.TryGetValue("sources", out value))
{
var sourceRoot = this.SourceRoot;
var sources = value as ArrayList;
this._sources = sources.Cast<string>()
.Select(x => sourceRoot + x)
.ToArray();
}
else
{
this._sources = Array.Empty<string>();
}
if (this._mapInfo.TryGetValue("names", out value))
{
var names = value as ArrayList;
this._names = names.Cast<string>().ToArray();
}
else
{
this._names = Array.Empty<string>();
}
var lineInfos = new List<LineInfo>();
object mappingsObj;
if (this._mapInfo.TryGetValue("mappings", out mappingsObj) && mappingsObj is string)
{
var mappings = (string)mappingsObj;
var lines = mappings.Split(';');
// each ; separated section represents a line in the generated file
int sourceIndex = 0, originalLine = 0, originalColumn = 0, originalName = 0;
foreach (var line in lines)
{
if (line.Length == 0)
{
lineInfos.Add(new LineInfo(new SegmentInfo[0]));
continue;
}
var segments = line.Split(',');
// each , separated section represents a segment of the line
var generatedColumn = 0;
var segmentInfos = new List<SegmentInfo>();
foreach (var segment in segments)
{
// each segment is Base64 VLQ encoded
var info = DecodeVLQ(segment);
if (info.Length == 0)
{
throw new InvalidOperationException("invalid data in source map, no starting column");
}
generatedColumn += info[SourceStartingIndex];
if (SourcesIndex < info.Length)
{
sourceIndex += info[SourcesIndex];
}
if (OriginalLineIndex < info.Length)
{
originalLine += info[OriginalLineIndex];
}
if (OriginalColumnIndex < info.Length)
{
originalColumn += info[OriginalColumnIndex];
}
if (NamesIndex < info.Length)
{
originalName += info[NamesIndex];
}
segmentInfos.Add(
new SegmentInfo(
generatedColumn,
sourceIndex,
originalLine,
originalColumn,
originalName
)
);
}
lineInfos.Add(new LineInfo(segmentInfos.ToArray()));
}
}
this._lines = lineInfos.ToArray();
}
private const int VLQ_CONTINUATION_MASK = 0x20;
private const int VLQ_SHIFT = 5;
private int[] DecodeVLQ(string value)
{
var res = new List<int>();
var curPos = 0;
while (curPos < value.Length)
{
long intValue = 0;
int mappedValue, shift = 0;
do
{
if (curPos == value.Length)
{
throw new InvalidOperationException("invalid data in source map, continued value doesn't continue");
}
try
{
mappedValue = _base64Mapping[value[curPos++]];
}
catch (KeyNotFoundException)
{
throw new InvalidOperationException("invalid data in source map, base64 data out of range");
}
intValue |= (uint)((mappedValue & ~VLQ_CONTINUATION_MASK) << shift);
if (intValue > Int32.MaxValue)
{
throw new InvalidOperationException("invalid data in source map, value is outside of 32-bit range");
}
shift += VLQ_SHIFT;
} while ((mappedValue & VLQ_CONTINUATION_MASK) != 0);
// least significant bit is sign bit
if ((intValue & 0x01) != 0)
{
res.Add((int)-(intValue >> 1));
}
else
{
res.Add((int)(intValue >> 1));
}
}
return res.ToArray();
}
/// <summary>
/// Version number of the source map.
/// </summary>
internal int Version => GetValue("version", -1);
/// <summary>
/// Filename of the generated code
/// </summary>
internal string File => GetValue("file", string.Empty);
/// <summary>
/// Provides the root for the sources to save space, automatically
/// included in the Sources array so it's not public.
/// </summary>
private string SourceRoot => GetValue("sourceRoot", string.Empty);
/// <summary>
/// All of the filenames that were combined.
/// </summary>
internal ReadOnlyCollection<string> Sources => new ReadOnlyCollection<string>(this._sources);
/// <summary>
/// All of the variable/method names that appear in the code
/// </summary>
internal ReadOnlyCollection<string> Names => new ReadOnlyCollection<string>(this._names);
/// <summary>
/// Maps a location in the generated code into a location in the source code.
/// </summary>
internal bool TryMapPoint(int lineNo, int columnNo, out SourceMapInfo res)
{
if (lineNo < this._lines.Length)
{
var line = this._lines[lineNo];
for (var i = line.Segments.Length - 1; i >= 0; i--)
{
if (line.Segments[i].GeneratedColumn <= columnNo)
{
// we map to this column
res = new SourceMapInfo(
line.Segments[i].OriginalLine,
line.Segments[i].OriginalColumn,
line.Segments[i].SourceIndex < this.Sources.Count ? this.Sources[line.Segments[i].SourceIndex] : null,
line.Segments[i].OriginalName < this.Names.Count ? this.Names[line.Segments[i].OriginalName] : null
);
return true;
}
}
if (line.Segments.Length > 0)
{
// we map to this column
res = new SourceMapInfo(
line.Segments[0].OriginalLine,
line.Segments[0].OriginalColumn,
line.Segments[0].SourceIndex < this.Sources.Count ? this.Sources[line.Segments[0].SourceIndex] : null,
line.Segments[0].OriginalName < this.Names.Count ? this.Names[line.Segments[0].OriginalName] : null
);
return true;
}
}
res = default(SourceMapInfo);
return false;
}
/// <summary>
/// Maps a location in the generated code into a location in the source code.
/// </summary>
internal bool TryMapLine(int lineNo, out SourceMapInfo res)
{
if (lineNo < this._lines.Length)
{
var line = this._lines[lineNo];
if (line.Segments.Length > 0)
{
res = new SourceMapInfo(
line.Segments[0].OriginalLine,
0,
this.Sources[line.Segments[0].SourceIndex],
line.Segments[0].OriginalName < this.Names.Count ?
this.Names[line.Segments[0].OriginalName] :
null
);
return true;
}
}
res = default(SourceMapInfo);
return false;
}
/// <summary>
/// Maps a location in the source code into the generated code.
/// </summary>
internal bool TryMapPointBack(int lineNo, int columnNo, out SourceMapInfo res)
{
int? firstBestLine = null, secondBestLine = null;
for (var i = 0; i < this._lines.Length; i++)
{
var line = this._lines[i];
int? originalColumn = null;
foreach (var segment in line.Segments)
{
if (segment.OriginalLine == lineNo)
{
if (segment.OriginalColumn <= columnNo)
{
originalColumn = segment.OriginalColumn;
}
else if (originalColumn != null)
{
res = new SourceMapInfo(
i,
columnNo - originalColumn.Value,
this.File,
null
);
return true;
}
else
{
// code like:
// constructor(public greeting: string) { }
// gets compiled into:
// function Greeter(greeting) {
// this.greeting = greeting;
// }
// If we're going to pick a line out of here we'd rather pick the
// 2nd line where we're going to hit a breakpoint.
if (firstBestLine == null)
{
firstBestLine = i;
}
else if (secondBestLine == null && firstBestLine.Value != i)
{
secondBestLine = i;
}
}
}
else if (segment.OriginalLine > lineNo && firstBestLine != null)
{
// not a perfect matching on column (e.g. requested 0, mapping starts at 4)
res = new SourceMapInfo(secondBestLine ?? firstBestLine.Value, 0, this.File, null);
return true;
}
}
}
res = default(SourceMapInfo);
return false;
}
private T GetValue<T>(string name, T defaultValue)
{
object version;
if (this._mapInfo.TryGetValue(name, out version) && version is T)
{
return (T)version;
}
return defaultValue;
}
private static Dictionary<char, int> BuildBase64Mapping()
{
const string base64mapping = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var mapping = new Dictionary<char, int>();
for (var i = 0; i < base64mapping.Length; i++)
{
mapping[base64mapping[i]] = i;
}
return mapping;
}
private struct LineInfo
{
public readonly SegmentInfo[] Segments;
public LineInfo(SegmentInfo[] segments)
{
this.Segments = segments;
}
}
internal struct SegmentInfo
{
internal readonly int GeneratedColumn;
internal readonly int SourceIndex;
internal readonly int OriginalLine;
internal readonly int OriginalColumn;
internal readonly int OriginalName;
internal SegmentInfo(int generatedColumn, int sourceIndex, int originalLine, int originalColumn, int originalName)
{
this.GeneratedColumn = generatedColumn;
this.SourceIndex = sourceIndex;
this.OriginalLine = originalLine;
this.OriginalColumn = originalColumn;
this.OriginalName = originalName;
}
}
}
internal class SourceMapInfo
{
internal readonly int Line, Column;
internal readonly string FileName, Name;
internal SourceMapInfo(int line, int column, string filename, string name)
{
this.Line = line;
this.Column = column;
this.FileName = filename;
this.Name = name;
}
}
}
| |
namespace Xilium.CefGlue
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
/// <summary>
/// Provides information about the context menu state. The ethods of this class
/// can only be accessed on browser process the UI thread.
/// </summary>
public sealed unsafe partial class CefContextMenuParams
{
/// <summary>
/// Returns the X coordinate of the mouse where the context menu was invoked.
/// Coords are relative to the associated RenderView's origin.
/// </summary>
public int X
{
get { return cef_context_menu_params_t.get_xcoord(_self); }
}
/// <summary>
/// Returns the Y coordinate of the mouse where the context menu was invoked.
/// Coords are relative to the associated RenderView's origin.
/// </summary>
public int Y
{
get { return cef_context_menu_params_t.get_ycoord(_self); }
}
/// <summary>
/// Returns flags representing the type of node that the context menu was
/// invoked on.
/// </summary>
public CefContextMenuTypeFlags ContextMenuType
{
get { return cef_context_menu_params_t.get_type_flags(_self); }
}
/// <summary>
/// Returns the URL of the link, if any, that encloses the node that the
/// context menu was invoked on.
/// </summary>
public string LinkUrl
{
get
{
var n_result = cef_context_menu_params_t.get_link_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the link URL, if any, to be used ONLY for "copy link address". We
/// don't validate this field in the frontend process.
/// </summary>
public string UnfilteredLinkUrl
{
get
{
var n_result = cef_context_menu_params_t.get_unfiltered_link_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the source URL, if any, for the element that the context menu was
/// invoked on. Example of elements with source URLs are img, audio, and video.
/// </summary>
public string SourceUrl
{
get
{
var n_result = cef_context_menu_params_t.get_source_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns true if the context menu was invoked on an image which has
/// non-empty contents.
/// </summary>
public bool HasImageContents
{
get { return cef_context_menu_params_t.has_image_contents(_self) != 0; }
}
/// <summary>
/// Returns the URL of the top level page that the context menu was invoked on.
/// </summary>
public string PageUrl
{
get
{
var n_result = cef_context_menu_params_t.get_page_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the URL of the subframe that the context menu was invoked on.
/// </summary>
public string FrameUrl
{
get
{
var n_result = cef_context_menu_params_t.get_frame_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the character encoding of the subframe that the context menu was
/// invoked on.
/// </summary>
public string FrameCharset
{
get
{
var n_result = cef_context_menu_params_t.get_frame_charset(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the type of context node that the context menu was invoked on.
/// </summary>
public CefContextMenuMediaType MediaType
{
get { return cef_context_menu_params_t.get_media_type(_self); }
}
/// <summary>
/// Returns flags representing the actions supported by the media element, if
/// any, that the context menu was invoked on.
/// </summary>
public CefContextMenuMediaStateFlags MediaState
{
get { return cef_context_menu_params_t.get_media_state_flags(_self); }
}
/// <summary>
/// Returns the text of the selection, if any, that the context menu was
/// invoked on.
/// </summary>
public string SelectionText
{
get
{
var n_result = cef_context_menu_params_t.get_selection_text(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the text of the misspelled word, if any, that the context menu was
/// invoked on.
/// </summary>
public string GetMisspelledWord()
{
var n_result = cef_context_menu_params_t.get_misspelled_word(_self);
return cef_string_userfree.ToString(n_result);
}
/// <summary>
/// Returns the hash of the misspelled word, if any, that the context menu was
/// invoked on.
/// </summary>
public int GetMisspellingHash()
{
return cef_context_menu_params_t.get_misspelling_hash(_self);
}
/// <summary>
/// Returns true if suggestions exist, false otherwise. Fills in |suggestions|
/// from the spell check service for the misspelled word if there is one.
/// </summary>
public string[] GetDictionarySuggestions()
{
var n_suggestions = libcef.string_list_alloc();
cef_context_menu_params_t.get_dictionary_suggestions(_self, n_suggestions);
var suggestions = cef_string_list.ToArray(n_suggestions);
libcef.string_list_free(n_suggestions);
return suggestions;
}
/// <summary>
/// Returns true if the context menu was invoked on an editable node.
/// </summary>
public bool IsEditable
{
get { return cef_context_menu_params_t.is_editable(_self) != 0; }
}
/// <summary>
/// Returns true if the context menu was invoked on an editable node where
/// spell-check is enabled.
/// </summary>
public bool IsSpellCheckEnabled
{
get { return cef_context_menu_params_t.is_spell_check_enabled(_self) != 0; }
}
/// <summary>
/// Returns flags representing the actions supported by the editable node, if
/// any, that the context menu was invoked on.
/// </summary>
public CefContextMenuEditStateFlags EditState
{
get { return cef_context_menu_params_t.get_edit_state_flags(_self); }
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Augurk.Api;
using Augurk.Api.Indeces;
using Augurk.Api.Managers;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
using Xunit;
namespace Augurk.Test.Managers
{
/// <summary>
/// Contains tests for the <see cref="ProductManager" /> class.
/// </summary>
public class ProductManagerTests : RavenTestBase
{
private readonly ILogger<ProductManager> logger = Substitute.For<ILogger<ProductManager>>();
/// <summary>
/// Tests that the <see cref="ProductManager" /> can retrieved stored products.
/// </summary>
[Fact]
public async Task GetsProducts()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var pm = new ProductManager(documentStoreProvider, logger);
await pm.InsertOrUpdateProductDescriptionAsync("Product1", string.Empty);
await pm.InsertOrUpdateProductDescriptionAsync("Product2", string.Empty);
WaitForIndexing(documentStoreProvider.Store);
// Act (using a new instance)
var sut = new ProductManager(documentStoreProvider, logger);
var result = (await sut.GetProductsAsync())?.ToList();
// Assert
result.ShouldNotBeNull();
result.Count.ShouldBe(2);
result[0].Name.ShouldBe("Product1");
result[0].DisplayName.ShouldBe(result[0].Name);
result[1].Name.ShouldBe("Product2");
result[1].DisplayName.ShouldBe(result[1].Name);
}
/// <summary>
/// Tests that the <see cref="ProductManager" /> can retrieved stored products.
/// </summary>
[Fact]
public async Task GetsProductTitless()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("Product1", "Group", "Title", "Version");
await documentStoreProvider.StoreDbFeatureAsync("Product2", "Group", "Title", "Version");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new ProductManager(documentStoreProvider, logger);
var result = await sut.GetProductTitlesAsync();
// Assert
result.ShouldNotBeNull();
result.Count().ShouldBe(2);
result.SequenceEqual(new[] { "Product1", "Product2" }).ShouldBeTrue();
}
/// <summary>
/// Tests that the <see cref="ProductManager" /> class can retrieve a product description for a particular product.
/// </summary>
[Fact]
public async Task GetsProductDescription()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var product = new DbProduct
{
Name = "MyProduct",
DescriptionMarkdown = "# Hello World!",
};
await session.StoreAsync(product);
await session.SaveChangesAsync();
}
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new ProductManager(documentStoreProvider, logger);
var result = await sut.GetProductDescriptionAsync("MyProduct");
// Assert
result.ShouldNotBeNull();
result.ShouldBe("# Hello World!");
}
/// <summary>
/// Tests that the <see cref="ProductManager" /> class can insert a new product description.
/// </summary>
[Fact]
public async Task CanInsertProductDescription()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var identifier = new DbProduct { Name = "MyProduct" }.GetIdentifier();
// Act
var sut = new ProductManager(documentStoreProvider, logger);
await sut.InsertOrUpdateProductDescriptionAsync("MyProduct", "# Hello World!");
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var product = await session.LoadAsync<DbProduct>(identifier);
product.ShouldNotBeNull();
product.DescriptionMarkdown.ShouldBe("# Hello World!");
}
}
/// <summary>
/// Tests that the <see cref="ProductManager" /> class can update an existing product description.
/// </summary>
[Fact]
public async Task CanUpdateProductDescription()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var existingProduct = new DbProduct { Name = "MyProduct", DescriptionMarkdown = "# Hello World!" };
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
await session.StoreAsync(existingProduct, existingProduct.GetIdentifier());
}
// Act
var sut = new ProductManager(documentStoreProvider, logger);
await sut.InsertOrUpdateProductDescriptionAsync("MyProduct", "# MyProduct");
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var product = await session.LoadAsync<DbProduct>(existingProduct.GetIdentifier());
product.ShouldNotBeNull();
product.DescriptionMarkdown.ShouldBe("# MyProduct");
}
}
/// <summary>
/// Tests that the <see cref="ProductManager" /> class can delete features associated with a product.
/// </summary>
[Fact]
public async Task CanDeleteProduct()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var existingFeature1 = await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "0.0.0");
var existingFeature2 = await documentStoreProvider.StoreDbFeatureAsync("MyOtherProduct", "MyGroup", "MySecondFeature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new ProductManager(documentStoreProvider, logger);
await sut.DeleteProductAsync("MyProduct");
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var actualFeature1 = await session.LoadAsync<DbFeature>(existingFeature1.GetIdentifier());
var actualFeature2 = await session.LoadAsync<DbFeature>(existingFeature2.GetIdentifier());
actualFeature1.ShouldBeNull();
actualFeature2.ShouldNotBeNull();
}
}
/// <summary>
/// Tests that the <see cref="ProductManager" /> class can delete features associated with a particular product
/// at a specific version.
/// </summary>
[Fact]
public async Task CanDeleteProductVersion()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var existingFeature1 = await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "0.0.0");
var existingFeature2 = await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "1.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new ProductManager(documentStoreProvider, logger);
await sut.DeleteProductAsync("MyProduct", "0.0.0");
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var actualFeature = await session.LoadAsync<DbFeature>(existingFeature1.GetIdentifier());
actualFeature.Versions.ShouldBe(new [] {"1.0.0"});
}
}
/// <summary>
/// Tests that the <see cref="ProductManager" /> class can get all the available tags for
/// all features.
/// </summary>
[Fact]
public async Task CanGetTags()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var existingFeature1 = await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "0.0.0", "tag1", "tag2");
var existingFeature2 = await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MySecondFeature", "0.0.0", "tag2", "tag3");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new ProductManager(documentStoreProvider, logger);
var result = await sut.GetTagsAsync("MyProduct");
// Assert
result.ShouldNotBeNull();
result.Count().ShouldBe(3);
result.SequenceEqual(new List<string> { "tag1", "tag2", "tag3" });
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Policy;
using System.Threading;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.Prism.Composition.Tests.Modularity
{
[TestClass]
public class DirectoryModuleCatalogFixture
{
private const string ModulesDirectory1 = @".\DynamicModules\MocksModules1";
private const string ModulesDirectory2 = @".\DynamicModules\AttributedModules";
private const string ModulesDirectory3 = @".\DynamicModules\DependantModules";
private const string ModulesDirectory4 = @".\DynamicModules\MocksModules2";
private const string ModulesDirectory5 = @".\DynamicModules\ModulesMainDomain\";
private const string InvalidModulesDirectory = @".\Modularity";
public DirectoryModuleCatalogFixture()
{
}
[TestInitialize]
[TestCleanup]
public void CleanUpDirectories()
{
CompilerHelper.CleanUpDirectory(ModulesDirectory1);
CompilerHelper.CleanUpDirectory(ModulesDirectory2);
CompilerHelper.CleanUpDirectory(ModulesDirectory3);
CompilerHelper.CleanUpDirectory(ModulesDirectory4);
CompilerHelper.CleanUpDirectory(ModulesDirectory5);
CompilerHelper.CleanUpDirectory(InvalidModulesDirectory);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void NullPathThrows()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.Load();
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void EmptyPathThrows()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.Load();
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void NonExistentPathThrows()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = "NonExistentPath";
catalog.Load();
}
[TestMethod]
public void ShouldReturnAListOfModuleInfo()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual(1, modules.Length);
Assert.IsNotNull(modules[0].Ref);
StringAssert.StartsWith(modules[0].Ref, "file://");
Assert.IsTrue(modules[0].Ref.Contains(@"MockModuleA.dll"));
Assert.IsNotNull(modules[0].ModuleType);
StringAssert.Contains(modules[0].ModuleType, "Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA");
}
[TestMethod]
[DeploymentItem(@"Modularity\NotAValidDotNetDll.txt.dll", @".\Modularity")]
public void ShouldNotThrowWithNonValidDotNetAssembly()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = InvalidModulesDirectory;
try
{
catalog.Load();
}
catch (Exception)
{
Assert.Fail("Should not have thrown.");
}
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual(0, modules.Length);
}
[TestMethod]
[DeploymentItem(@"Modularity\NotAValidDotNetDll.txt.dll", InvalidModulesDirectory)]
public void LoadsValidAssembliesWhenInvalidDllsArePresent()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA.cs",
InvalidModulesDirectory + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = InvalidModulesDirectory;
try
{
catalog.Load();
}
catch (Exception)
{
Assert.Fail("Should not have thrown.");
}
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual(1, modules.Length);
Assert.IsNotNull(modules[0].Ref);
StringAssert.StartsWith(modules[0].Ref, "file://");
Assert.IsTrue(modules[0].Ref.Contains(@"MockModuleA.dll"));
Assert.IsNotNull(modules[0].ModuleType);
StringAssert.Contains(modules[0].ModuleType, "Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA");
}
[TestMethod]
public void ShouldNotThrowWithLoadFromByteAssemblies()
{
CompilerHelper.CleanUpDirectory(@".\CompileOutput\");
CompilerHelper.CleanUpDirectory(@".\IgnoreLoadFromByteAssembliesTestDir\");
var results = CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA.cs",
@".\CompileOutput\MockModuleA.dll");
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockAttributedModule.cs",
@".\IgnoreLoadFromByteAssembliesTestDir\MockAttributedModule.dll");
string path = @".\IgnoreLoadFromByteAssembliesTestDir";
AppDomain testDomain = null;
try
{
testDomain = CreateAppDomain();
RemoteDirectoryLookupCatalog remoteEnum = CreateRemoteDirectoryModuleCatalogInAppDomain(testDomain);
remoteEnum.LoadDynamicEmittedModule();
remoteEnum.LoadAssembliesByByte(@".\CompileOutput\MockModuleA.dll");
ModuleInfo[] infos = remoteEnum.DoEnumeration(path);
Assert.IsNotNull(
infos.FirstOrDefault(x => x.ModuleType.IndexOf("Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockAttributedModule") >= 0)
);
}
finally
{
if (testDomain != null)
AppDomain.Unload(testDomain);
}
}
[TestMethod]
public void ShouldGetModuleNameFromAttribute()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockAttributedModule.cs",
ModulesDirectory2 + @"\MockAttributedModule.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory2;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
Assert.AreEqual("TestModule", modules[0].ModuleName);
}
[TestMethod]
public void ShouldGetDependantModulesFromAttribute()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockDependencyModule.cs",
ModulesDirectory3 + @"\DependencyModule.dll");
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockDependantModule.cs",
ModulesDirectory3 + @"\DependantModule.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory3;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(2, modules.Length);
var dependantModule = modules.First(module => module.ModuleName == "DependantModule");
var dependencyModule = modules.First(module => module.ModuleName == "DependencyModule");
Assert.IsNotNull(dependantModule);
Assert.IsNotNull(dependencyModule);
Assert.IsNotNull(dependantModule.DependsOn);
Assert.AreEqual(1, dependantModule.DependsOn.Count);
Assert.AreEqual(dependencyModule.ModuleName, dependantModule.DependsOn[0]);
}
[TestMethod]
public void UseClassNameAsModuleNameWhenNotSpecifiedInAttribute()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual("MockModuleA", modules[0].ModuleName);
}
[TestMethod]
public void ShouldDefaultInitializationModeToWhenAvailable()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual(InitializationMode.WhenAvailable, modules[0].InitializationMode);
}
[TestMethod]
public void ShouldGetOnDemandFromAttribute()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockAttributedModule.cs",
ModulesDirectory3 + @"\MockAttributedModule.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory3;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
Assert.AreEqual(InitializationMode.OnDemand, modules[0].InitializationMode);
}
[TestMethod]
public void ShouldHonorStartupLoadedAttribute()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockStartupLoadedAttributedModule.cs",
ModulesDirectory3 + @"\MockStartupLoadedAttributedModule.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory3;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
Assert.AreEqual(InitializationMode.OnDemand, modules[0].InitializationMode);
}
[TestMethod]
public void ShouldNotLoadAssembliesInCurrentAppDomain()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory4 + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory4;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
// filtering out dynamic assemblies due to using a dynamic mocking framework.
Assembly loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.IsDynamic)
.Where(assembly => assembly.Location.Equals(modules[0].Ref, StringComparison.InvariantCultureIgnoreCase))
.FirstOrDefault();
Assert.IsNull(loadedAssembly);
}
[TestMethod]
public void ShouldNotGetModuleInfoForAnAssemblyAlreadyLoadedInTheMainDomain()
{
var assemblyPath = Assembly.GetCallingAssembly().Location;
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory5;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(0, modules.Length);
}
[TestMethod]
public void ShouldLoadAssemblyEvenIfTheyAreReferencingEachOther()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory4 + @"\MockModuleZZZ.dll");
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleReferencingOtherModule.cs",
ModulesDirectory4 + @"\MockModuleReferencingOtherModule.dll", ModulesDirectory4 + @"\MockModuleZZZ.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory4;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(2, modules.Count());
}
//Disabled Warning
// 'System.Security.Policy.Evidence.Count' is obsolete: '
// "Evidence should not be treated as an ICollection. Please use GetHostEnumerator and GetAssemblyEnumerator to
// iterate over the evidence to collect a count."'
#pragma warning disable 0618
[TestMethod]
public void CreateChildAppDomainHasParentEvidenceAndSetup()
{
TestableDirectoryModuleCatalog catalog = new TestableDirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory4;
catalog.Load();
Evidence parentEvidence = new Evidence();
AppDomainSetup parentSetup = new AppDomainSetup();
parentSetup.ApplicationName = "Test Parent";
AppDomain parentAppDomain = AppDomain.CreateDomain("Parent", parentEvidence, parentSetup);
AppDomain childDomain = catalog.BuildChildDomain(parentAppDomain);
Assert.AreEqual(parentEvidence.Count, childDomain.Evidence.Count);
Assert.AreEqual("Test Parent", childDomain.SetupInformation.ApplicationName);
Assert.AreNotEqual(AppDomain.CurrentDomain.Evidence.Count, childDomain.Evidence.Count);
Assert.AreNotEqual(AppDomain.CurrentDomain.SetupInformation.ApplicationName, childDomain.SetupInformation.ApplicationName);
}
#pragma warning restore 0618
[TestMethod]
public void ShouldLoadFilesEvenIfDynamicAssemblyExists()
{
CompilerHelper.CleanUpDirectory(@".\CompileOutput\");
CompilerHelper.CleanUpDirectory(@".\IgnoreDynamicGeneratedFilesTestDir\");
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockAttributedModule.cs",
@".\IgnoreDynamicGeneratedFilesTestDir\MockAttributedModule.dll");
string path = @".\IgnoreDynamicGeneratedFilesTestDir";
AppDomain testDomain = null;
try
{
testDomain = CreateAppDomain();
RemoteDirectoryLookupCatalog remoteEnum = CreateRemoteDirectoryModuleCatalogInAppDomain(testDomain);
remoteEnum.LoadDynamicEmittedModule();
ModuleInfo[] infos = remoteEnum.DoEnumeration(path);
Assert.IsNotNull(
infos.FirstOrDefault(x => x.ModuleType.IndexOf("Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockAttributedModule") >= 0)
);
}
finally
{
if (testDomain != null)
AppDomain.Unload(testDomain);
}
}
[TestMethod]
public void ShouldLoadAssemblyEvenIfIsExposingTypesFromAnAssemblyInTheGac()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockExposingTypeFromGacAssemblyModule.cs",
ModulesDirectory4 + @"\MockExposingTypeFromGacAssemblyModule.dll", @"System.Transactions.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory4;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Count());
}
[TestMethod]
public void ShouldNotFailWhenAlreadyLoadedAssembliesAreAlsoFoundOnTargetDirectory()
{
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
string filename = typeof(DirectoryModuleCatalog).Assembly.Location;
string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename));
File.Copy(filename, destinationFileName);
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
}
[TestMethod]
public void ShouldIgnoreAbstractClassesThatImplementIModule()
{
CompilerHelper.CleanUpDirectory(ModulesDirectory1);
CompilerHelper.CompileFile(@"Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules.MockAbstractModule.cs",
ModulesDirectory1 + @"\MockAbstractModule.dll");
string filename = typeof(DirectoryModuleCatalog).Assembly.Location;
string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename));
File.Copy(filename, destinationFileName);
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
Assert.AreEqual("MockInheritingModule", modules[0].ModuleName);
CompilerHelper.CleanUpDirectory(ModulesDirectory1);
}
private AppDomain CreateAppDomain()
{
Evidence evidence = AppDomain.CurrentDomain.Evidence;
AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
return AppDomain.CreateDomain("TestDomain", evidence, setup);
}
private RemoteDirectoryLookupCatalog CreateRemoteDirectoryModuleCatalogInAppDomain(AppDomain testDomain)
{
RemoteDirectoryLookupCatalog remoteEnum;
Type remoteEnumType = typeof(RemoteDirectoryLookupCatalog);
remoteEnum = (RemoteDirectoryLookupCatalog)testDomain.CreateInstanceFrom(
remoteEnumType.Assembly.Location, remoteEnumType.FullName).Unwrap();
return remoteEnum;
}
private class TestableDirectoryModuleCatalog : DirectoryModuleCatalog
{
public new AppDomain BuildChildDomain(AppDomain currentDomain)
{
return base.BuildChildDomain(currentDomain);
}
}
private class RemoteDirectoryLookupCatalog : MarshalByRefObject
{
public void LoadAssembliesByByte(string assemblyPath)
{
byte[] assemblyBytes = File.ReadAllBytes(assemblyPath);
AppDomain.CurrentDomain.Load(assemblyBytes);
}
public ModuleInfo[] DoEnumeration(string path)
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = path;
catalog.Load();
return catalog.Modules.ToArray();
}
public void LoadDynamicEmittedModule()
{
// create a dynamic assembly and module
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "DynamicBuiltAssembly";
AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder module = assemblyBuilder.DefineDynamicModule("DynamicBuiltAssembly.dll");
// create a new type
TypeBuilder typeBuilder = module.DefineType("DynamicBuiltType", TypeAttributes.Public | TypeAttributes.Class);
// Create the type
Type helloWorldType = typeBuilder.CreateType();
}
}
}
}
| |
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright holder is ArangoDB GmbH, Cologne, Germany
*/
namespace ArangoDB.Internal.VelocyStream
{
using global::ArangoDB.Velocypack;
/// <author>Mark - mark at arangodb.com</author>
public abstract class Connection
{
private static readonly org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger
(typeof(Connection
));
private static readonly byte[] PROTOCOL_HEADER = Sharpen.Runtime.getBytesForString
("VST/1.0\r\n\r\n");
private readonly string host;
private readonly int port;
private readonly int timeout;
private readonly bool useSsl;
private readonly javax.net.ssl.SSLContext sslContext;
private java.net.Socket socket;
private java.io.OutputStream outputStream;
private java.io.InputStream inputStream;
protected internal Connection(string host, int port, int timeout, bool useSsl, javax.net.ssl.SSLContext
sslContext)
: base()
{
this.host = host;
this.port = port;
this.timeout = timeout;
this.useSsl = useSsl;
this.sslContext = sslContext;
}
public virtual bool isOpen()
{
lock (this)
{
return this.socket != null && this.socket.isConnected() && !this.socket.isClosed();
}
}
/// <exception cref="System.IO.IOException"/>
public virtual void open()
{
lock (this)
{
if (this.isOpen())
{
return;
}
if (this.useSsl != null && this.useSsl)
{
if (this.sslContext != null)
{
this.socket = this.sslContext.getSocketFactory().createSocket();
}
else
{
this.socket = javax.net.ssl.SSLSocketFactory.getDefault().createSocket();
}
}
else
{
this.socket = javax.net.SocketFactory.getDefault().createSocket();
}
string host = this.host != null ? this.host : ArangoDBConstants
.DEFAULT_HOST;
int port = this.port != null ? this.port : ArangoDBConstants
.DEFAULT_PORT;
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(string.format("Open connection to addr=%s,port=%s", host, port));
}
this.socket.connect(new java.net.InetSocketAddress(host, port), this.timeout != null ? this.timeout
: ArangoDBConstants.DEFAULT_TIMEOUT);
this.socket.setKeepAlive(true);
this.socket.setTcpNoDelay(true);
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(string.format("Connected to %s", this.socket));
}
this.outputStream = new java.io.BufferedOutputStream(this.socket.getOutputStream());
this.inputStream = this.socket.getInputStream();
if (this.useSsl != null && this.useSsl)
{
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(string.format("Start Handshake on %s", this.socket));
}
((javax.net.ssl.SSLSocket)this.socket).startHandshake();
}
this.sendProtocolHeader();
}
}
public virtual void close()
{
lock (this)
{
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(string.format("Close connection %s", this.socket));
}
if (this.socket != null)
{
try
{
this.socket.close();
}
catch (System.IO.IOException e)
{
throw new ArangoDBException(e);
}
}
}
}
/// <exception cref="System.IO.IOException"/>
private void sendProtocolHeader()
{
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(string.format("Send velocystream protocol header to %s", this.socket));
}
this.outputStream.write(PROTOCOL_HEADER);
this.outputStream.flush();
}
protected internal virtual void writeIntern(Message
message, System.Collections.Generic.ICollection<Chunk
> chunks)
{
lock (this)
{
foreach (Chunk chunk in chunks)
{
try
{
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(string.format("Send chunk %s:%s from message %s", chunk.getChunk(),
chunk.isFirstChunk() ? 1 : 0, chunk.getMessageId()));
}
this.writeChunkHead(chunk);
int contentOffset = chunk.getContentOffset();
int contentLength = chunk.getContentLength();
VPackSlice head = message.getHead();
int headLength = head.getByteSize();
int written = 0;
if (contentOffset < headLength)
{
written = System.Math.min(contentLength, headLength - contentOffset);
this.outputStream.write(head.getBuffer(), contentOffset, written);
}
if (written < contentLength)
{
VPackSlice body = message.getBody();
this.outputStream.write(body.getBuffer(), contentOffset + written - headLength, contentLength
- written);
}
this.outputStream.flush();
}
catch (System.IO.IOException e)
{
throw new System.Exception(e);
}
}
}
}
/// <exception cref="System.IO.IOException"/>
private void writeChunkHead(Chunk chunk)
{
long messageLength = chunk.getMessageLength();
int headLength = messageLength > -1L ? ArangoDBConstants.CHUNK_MAX_HEADER_SIZE
: ArangoDBConstants.CHUNK_MIN_HEADER_SIZE;
int length = chunk.getContentLength() + headLength;
java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(headLength).order(java.nio.ByteOrder
.LITTLE_ENDIAN);
buffer.putInt(length);
buffer.putInt(chunk.getChunkX());
buffer.putLong(chunk.getMessageId());
if (messageLength > -1L)
{
buffer.putLong(messageLength);
}
this.outputStream.write((byte[])buffer.array());
}
/// <exception cref="System.IO.IOException"/>
protected internal virtual Chunk readChunk()
{
java.nio.ByteBuffer chunkHeadBuffer = this.readBytes(ArangoDBConstants
.CHUNK_MIN_HEADER_SIZE);
int length = chunkHeadBuffer.getInt();
int chunkX = chunkHeadBuffer.getInt();
long messageId = chunkHeadBuffer.getLong();
long messageLength;
int contentLength;
if ((1 == (chunkX & unchecked((int)0x1))) && (chunkX >> 1 > 1))
{
messageLength = this.readBytes(ArangoDBConstants.LONG_BYTES).getLong
();
contentLength = length - ArangoDBConstants.CHUNK_MAX_HEADER_SIZE;
}
else
{
messageLength = -1L;
contentLength = length - ArangoDBConstants.CHUNK_MIN_HEADER_SIZE;
}
Chunk chunk = new Chunk
(messageId, chunkX, messageLength, 0, contentLength);
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(string.format("Received chunk %s:%s from message %s", chunk.getChunk
(), chunk.isFirstChunk() ? 1 : 0, chunk.getMessageId()));
}
return chunk;
}
/// <exception cref="System.IO.IOException"/>
private java.nio.ByteBuffer readBytes(int len)
{
byte[] buf = new byte[len];
this.readBytesIntoBuffer(buf, 0, len);
return java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN);
}
/// <exception cref="System.IO.IOException"/>
protected internal virtual void readBytesIntoBuffer(byte[] buf, int off, int len)
{
for (int readed = 0; readed < len;)
{
int read = this.inputStream.read(buf, off + readed, len - readed);
if (read == -1)
{
throw new System.IO.IOException("Reached the end of the stream.");
}
else
{
readed += read;
}
}
}
}
}
| |
// 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.Collections.Specialized
{
/// <devdoc>
/// <para>
/// This is a simple implementation of IDictionary using a singly linked list. This
/// will be smaller and faster than a Hashtable if the number of elements is 10 or less.
/// This should not be used if performance is important for large numbers of elements.
/// </para>
/// </devdoc>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class ListDictionary : IDictionary
{
private DictionaryNode head; // Do not rename (binary serialization)
private int version; // Do not rename (binary serialization)
private int count; // Do not rename (binary serialization)
private readonly IComparer comparer; // Do not rename (binary serialization)
public ListDictionary()
{
}
public ListDictionary(IComparer comparer)
{
this.comparer = comparer;
}
public object this[object key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
DictionaryNode node = head;
if (comparer == null)
{
while (node != null)
{
object oldKey = node.key;
if (oldKey.Equals(key))
{
return node.value;
}
node = node.next;
}
}
else
{
while (node != null)
{
object oldKey = node.key;
if (comparer.Compare(oldKey, key) == 0)
{
return node.value;
}
node = node.next;
}
}
return null;
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next)
{
object oldKey = node.key;
if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0)
{
break;
}
last = node;
}
if (node != null)
{
// Found it
node.value = value;
return;
}
// Not found, so add a new one
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
if (last != null)
{
last.next = newNode;
}
else
{
head = newNode;
}
count++;
}
}
public int Count
{
get
{
return count;
}
}
public ICollection Keys
{
get
{
return new NodeKeyValueCollection(this, true);
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot => this;
public ICollection Values
{
get
{
return new NodeKeyValueCollection(this, false);
}
}
public void Add(object key, object value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next)
{
object oldKey = node.key;
if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0)
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key));
}
last = node;
}
// Not found, so add a new one
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
if (last != null)
{
last.next = newNode;
}
else
{
head = newNode;
}
count++;
}
public void Clear()
{
count = 0;
head = null;
version++;
}
public bool Contains(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
for (DictionaryNode node = head; node != null; node = node.next)
{
object oldKey = node.key;
if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0)
{
return true;
}
}
return false;
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index);
if (array.Length - index < count)
throw new ArgumentException(SR.Arg_InsufficientSpace);
for (DictionaryNode node = head; node != null; node = node.next)
{
array.SetValue(new DictionaryEntry(node.key, node.value), index);
index++;
}
}
public IDictionaryEnumerator GetEnumerator()
{
return new NodeEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new NodeEnumerator(this);
}
public void Remove(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next)
{
object oldKey = node.key;
if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0)
{
break;
}
last = node;
}
if (node == null)
{
return;
}
if (node == head)
{
head = node.next;
}
else
{
last.next = node.next;
}
count--;
}
private class NodeEnumerator : IDictionaryEnumerator
{
private ListDictionary _list;
private DictionaryNode _current;
private int _version;
private bool _start;
public NodeEnumerator(ListDictionary list)
{
_list = list;
_version = list.version;
_start = true;
_current = null;
}
public object Current
{
get
{
return Entry;
}
}
public DictionaryEntry Entry
{
get
{
if (_current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(_current.key, _current.value);
}
}
public object Key
{
get
{
if (_current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _current.key;
}
}
public object Value
{
get
{
if (_current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _current.value;
}
}
public bool MoveNext()
{
if (_version != _list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (_start)
{
_current = _list.head;
_start = false;
}
else if (_current != null)
{
_current = _current.next;
}
return (_current != null);
}
public void Reset()
{
if (_version != _list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_start = true;
_current = null;
}
}
private class NodeKeyValueCollection : ICollection
{
private ListDictionary _list;
private bool _isKeys;
public NodeKeyValueCollection(ListDictionary list, bool isKeys)
{
_list = list;
_isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index);
for (DictionaryNode node = _list.head; node != null; node = node.next)
{
array.SetValue(_isKeys ? node.key : node.value, index);
index++;
}
}
int ICollection.Count
{
get
{
int count = 0;
for (DictionaryNode node = _list.head; node != null; node = node.next)
{
count++;
}
return count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return _list.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new NodeKeyValueEnumerator(_list, _isKeys);
}
private class NodeKeyValueEnumerator : IEnumerator
{
private ListDictionary _list;
private DictionaryNode _current;
private int _version;
private bool _isKeys;
private bool _start;
public NodeKeyValueEnumerator(ListDictionary list, bool isKeys)
{
_list = list;
_isKeys = isKeys;
_version = list.version;
_start = true;
_current = null;
}
public object Current
{
get
{
if (_current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _isKeys ? _current.key : _current.value;
}
}
public bool MoveNext()
{
if (_version != _list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (_start)
{
_current = _list.head;
_start = false;
}
else if (_current != null)
{
_current = _current.next;
}
return (_current != null);
}
public void Reset()
{
if (_version != _list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_start = true;
_current = null;
}
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class DictionaryNode
{
public object key; // Do not rename (binary serialization)
public object value; // Do not rename (binary serialization)
public DictionaryNode next; // Do not rename (binary serialization)
}
}
}
| |
#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.Text;
using NUnit.Framework;
using System.IO;
#if !NET35
using System.Threading.Tasks;
#endif
namespace Google.Protobuf
{
public class ByteStringTest
{
[Test]
public void Equality()
{
ByteString b1 = ByteString.CopyFrom(1, 2, 3);
ByteString b2 = ByteString.CopyFrom(1, 2, 3);
ByteString b3 = ByteString.CopyFrom(1, 2, 4);
ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4);
EqualityTester.AssertEquality(b1, b1);
EqualityTester.AssertEquality(b1, b2);
EqualityTester.AssertInequality(b1, b3);
EqualityTester.AssertInequality(b1, b4);
EqualityTester.AssertInequality(b1, null);
#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1)
Assert.IsTrue(b1 == b1);
Assert.IsTrue(b1 == b2);
Assert.IsFalse(b1 == b3);
Assert.IsFalse(b1 == b4);
Assert.IsFalse(b1 == null);
Assert.IsTrue((ByteString) null == null);
Assert.IsFalse(b1 != b1);
Assert.IsFalse(b1 != b2);
#pragma warning disable 1718
Assert.IsTrue(b1 != b3);
Assert.IsTrue(b1 != b4);
Assert.IsTrue(b1 != null);
Assert.IsFalse((ByteString) null != null);
}
[Test]
public void EmptyByteStringHasZeroSize()
{
Assert.AreEqual(0, ByteString.Empty.Length);
}
[Test]
public void CopyFromStringWithExplicitEncoding()
{
ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode);
Assert.AreEqual(4, bs.Length);
Assert.AreEqual(65, bs[0]);
Assert.AreEqual(0, bs[1]);
Assert.AreEqual(66, bs[2]);
Assert.AreEqual(0, bs[3]);
}
[Test]
public void IsEmptyWhenEmpty()
{
Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty);
}
[Test]
public void IsEmptyWhenNotEmpty()
{
Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty);
}
[Test]
public void CopyFromByteArrayCopiesContents()
{
byte[] data = new byte[1];
data[0] = 10;
ByteString bs = ByteString.CopyFrom(data);
Assert.AreEqual(10, bs[0]);
data[0] = 5;
Assert.AreEqual(10, bs[0]);
}
[Test]
public void ToByteArrayCopiesContents()
{
ByteString bs = ByteString.CopyFromUtf8("Hello");
byte[] data = bs.ToByteArray();
Assert.AreEqual((byte)'H', data[0]);
Assert.AreEqual((byte)'H', bs[0]);
data[0] = 0;
Assert.AreEqual(0, data[0]);
Assert.AreEqual((byte)'H', bs[0]);
}
[Test]
public void CopyFromUtf8UsesUtf8()
{
ByteString bs = ByteString.CopyFromUtf8("\u20ac");
Assert.AreEqual(3, bs.Length);
Assert.AreEqual(0xe2, bs[0]);
Assert.AreEqual(0x82, bs[1]);
Assert.AreEqual(0xac, bs[2]);
}
[Test]
public void CopyFromPortion()
{
byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6};
ByteString bs = ByteString.CopyFrom(data, 2, 3);
Assert.AreEqual(3, bs.Length);
Assert.AreEqual(2, bs[0]);
Assert.AreEqual(3, bs[1]);
}
[Test]
public void ToStringUtf8()
{
ByteString bs = ByteString.CopyFromUtf8("\u20ac");
Assert.AreEqual("\u20ac", bs.ToStringUtf8());
}
[Test]
public void ToStringWithExplicitEncoding()
{
ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode);
Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode));
}
[Test]
public void FromBase64_WithText()
{
byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6};
string base64 = Convert.ToBase64String(data);
ByteString bs = ByteString.FromBase64(base64);
Assert.AreEqual(data, bs.ToByteArray());
}
[Test]
public void FromBase64_Empty()
{
// Optimization which also fixes issue 61.
Assert.AreSame(ByteString.Empty, ByteString.FromBase64(""));
}
[Test]
public void FromStream_Seekable()
{
var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
// Consume the first byte, just to test that it's "from current position"
stream.ReadByte();
var actual = ByteString.FromStream(stream);
ByteString expected = ByteString.CopyFrom(2, 3, 4, 5);
Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}");
}
[Test]
public void FromStream_NotSeekable()
{
var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
// Consume the first byte, just to test that it's "from current position"
stream.ReadByte();
// Wrap the original stream in LimitedInputStream, which has CanSeek=false
var limitedStream = new LimitedInputStream(stream, 3);
var actual = ByteString.FromStream(limitedStream);
ByteString expected = ByteString.CopyFrom(2, 3, 4);
Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}");
}
#if !NET35
[Test]
public async Task FromStreamAsync_Seekable()
{
var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
// Consume the first byte, just to test that it's "from current position"
stream.ReadByte();
var actual = await ByteString.FromStreamAsync(stream);
ByteString expected = ByteString.CopyFrom(2, 3, 4, 5);
Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}");
}
[Test]
public async Task FromStreamAsync_NotSeekable()
{
var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
// Consume the first byte, just to test that it's "from current position"
stream.ReadByte();
// Wrap the original stream in LimitedInputStream, which has CanSeek=false
var limitedStream = new LimitedInputStream(stream, 3);
var actual = await ByteString.FromStreamAsync(limitedStream);
ByteString expected = ByteString.CopyFrom(2, 3, 4);
Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}");
}
#endif
[Test]
public void GetHashCode_Regression()
{
// We used to have an awful hash algorithm where only the last four
// bytes were relevant. This is a regression test for
// https://github.com/google/protobuf/issues/2511
ByteString b1 = ByteString.CopyFrom(100, 1, 2, 3, 4);
ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4);
Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode());
}
}
}
| |
// 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.Reflection.Emit;
using System.Linq;
using Xunit;
namespace System.Reflection.Emit.ILGeneration.Tests
{
public class CustomAttributeBuilderCtor3
{
private const int MinStringLength = 1;
private const int MaxStringLength = 1024;
private const string PropertyTestInt32Name = "TestInt32";
private const string PropertyTestStringName = "TestString";
private const string PropertyGetOnlyStringName = "GetOnlyString";
private const string PropertyGetOnlyIntName = "GetOnlyInt32";
private const string DefaultNotExistPropertyName = "DOESNOTEXIST";
[Fact]
public void PosTest1()
{
string testString1 = null;
string testString2 = null;
int testInt1 = 0;
int testInt2 = 0;
testString1 = "PosTest1_TestString1";
testString2 = "PosTest1_TestString2";
testInt1 = TestLibrary.Generator.GetInt32();
testInt2 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
testString1,
testInt1
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
};
object[] propertyValues = new object[]
{
testInt2,
testString2
};
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
Assert.NotNull(cab);
PropertyInfo[] verifyFields = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
};
object[] verifyFieldValues = new object[]
{
testInt2,
testString2,
testString1,
testInt1
};
Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues));
}
[Fact]
public void PosTest2()
{
string testString1 = null;
int testInt1 = 0;
int testInt2 = 0;
testString1 = "PosTest2_TestString1";
testInt1 = TestLibrary.Generator.GetInt32();
testInt2 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
testString1,
testInt1
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name)
};
object[] propertyValues = new object[]
{
testInt2
};
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
Assert.NotNull(cab);
PropertyInfo[] verifyFields = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
};
object[] verifyFieldValues = new object[]
{
testInt2,
null,
testString1,
testInt1
};
Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues));
}
[Fact]
public void PosTest3()
{
string testString1 = null;
int testInt1 = 0;
testString1 = "PosTest3_TestString1";
testInt1 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
testString1,
testInt1
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
};
object[] propertyValues = new object[]
{
};
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
Assert.NotNull(cab);
PropertyInfo[] verifyFields = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
};
object[] verifyFieldValues = new object[]
{
0,
null,
testString1,
testInt1
};
Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues));
}
[Fact]
public void PosTest4()
{
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
};
object[] propertyValues = new object[]
{
};
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
Assert.NotNull(cab);
PropertyInfo[] verifyFields = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
};
object[] verifyFieldValues = new object[]
{
0,
null,
null,
0
};
Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues));
}
[Fact]
public void PosTest5()
{
int testInt1 = 0;
testInt1 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name)
};
object[] propertyValues = new object[]
{
testInt1
};
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
Assert.NotNull(cab);
PropertyInfo[] verifyFields = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
};
object[] verifyFieldValues = new object[]
{
testInt1,
null,
null,
0
};
Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues));
}
[Fact]
public void PosTest6()
{
string testString1 = null;
int testInt1 = 0;
testString1 = "PosTest6_TestString1";
testInt1 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
};
object[] propertyValues = new object[]
{
testInt1,
testString1
};
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
Assert.NotNull(cab);
PropertyInfo[] verifyFields = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
};
object[] verifyFieldValues = new object[]
{
testInt1,
testString1,
null,
0
};
Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues));
}
[Fact]
public void PosTest7()
{
string testString1 = null;
string testString2 = null;
int testInt1 = 0;
int testInt2 = 0;
testString1 = "PosTest7_TestString1";
testString2 = "PosTest7_TestString2";
testInt1 = TestLibrary.Generator.GetInt32();
testInt2 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int),
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
testString1,
testInt1,
testString1,
testInt1
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
};
object[] propertyValues = new object[]
{
testInt2,
testString2
};
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
Assert.NotNull(cab);
PropertyInfo[] verifyFields = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName),
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
};
object[] verifyFieldValues = new object[]
{
testInt2,
testString2,
testString1,
testInt1
};
Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues));
}
[Fact]
public void NegTest1()
{
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
};
object[] propertyValues = new object[]
{
};
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest2()
{
int testInt1 = 0;
testInt1 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
};
object[] propertyValues = new object[]
{
testInt1
};
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest3()
{
Type[] ctorParams = new Type[] { };
object[] constructorArgs = new object[] { };
PropertyInfo[] namedProperty = new PropertyInfo[] { };
object[] propertyValues = new object[] { };
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
typeof(TestConstructor).GetConstructors(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)
.Where(c => c.IsStatic).First(),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest4()
{
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
false
};
PropertyInfo[] namedProperty = new PropertyInfo[] { };
object[] propertyValues = new object[] { };
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
typeof(TestConstructor).GetConstructors(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)
.Where(c => c.IsPrivate).First(),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest5()
{
string testString1 = null;
int testInt1 = 0;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
testInt1 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int),
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
testString1,
testInt1
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
};
object[] propertyValues = new object[]
{
};
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest6()
{
string testString1 = null;
int testInt1 = 0;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
testInt1 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
testInt1,
testString1
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
};
object[] propertyValues = new object[]
{
};
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest7()
{
string testString1 = null;
int testInt1 = 0;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
testInt1 = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
};
object[] propertyValues = new object[]
{
testString1,
testInt1
};
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest8()
{
string testString1 = null;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
};
object[] propertyValues = new object[]
{
testString1
};
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest9()
{
string testString1 = null;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName)
};
object[] propertyValues = new object[]
{
testString1
};
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest10()
{
string testString1 = null;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name)
};
object[] propertyValues = new object[]
{
testString1
};
Assert.Throws<ArgumentNullException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
null,
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest11()
{
string testString1 = null;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name)
};
object[] propertyValues = new object[]
{
testString1
};
Assert.Throws<ArgumentNullException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
null,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest12()
{
string testString1 = null;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name)
};
Assert.Throws<ArgumentNullException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
null);
});
}
[Fact]
public void NegTest13()
{
string testString = null;
int testInt = 0;
testString =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
testInt = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
null,
typeof(int)
};
object[] constructorArgs = new object[]
{
testString,
testInt
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
};
object[] propertyValues = new object[]
{
testString,
testInt
};
Assert.Throws<ArgumentNullException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest14()
{
string testString = null;
int testInt = 0;
testString =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
testInt = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
null,
testInt
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
};
object[] propertyValues = new object[]
{
testString,
testInt
};
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest15()
{
string testString = null;
int testInt = 0;
testString =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
testInt = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
testString,
testInt
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
null,
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
};
object[] propertyValues = new object[]
{
testString,
testInt
};
Assert.Throws<ArgumentNullException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest16()
{
int testInt = 0;
string testString = null;
testString =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
testInt = TestLibrary.Generator.GetInt32();
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
typeof(string),
typeof(int)
};
object[] constructorArgs = new object[]
{
testString,
testInt
};
PropertyInfo[] namedProperty = new PropertyInfo[]
{
CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
};
object[] propertyValues = new object[]
{
null,
testInt
};
Assert.Throws<ArgumentNullException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
namedProperty,
propertyValues);
});
}
[Fact]
public void NegTest17()
{
string testString1 = null;
testString1 =
TestLibrary.Generator.GetString(false, MinStringLength, MaxStringLength);
Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);
Type[] ctorParams = new Type[]
{
};
object[] constructorArgs = new object[]
{
};
object[] propertyValues = new object[]
{
testString1
};
Assert.Throws<ArgumentNullException>(() =>
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
CustomAttributeBuilderTestType.GetConstructor(ctorParams),
constructorArgs,
null as PropertyInfo[],
propertyValues);
});
}
private bool VerifyCustomAttribute(CustomAttributeBuilder builder, Type attributeType, PropertyInfo[] namedProperties, object[] propertyValues)
{
AssemblyName asmName = new AssemblyName("VerificationAssembly");
bool retVal = true;
AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(
asmName, AssemblyBuilderAccess.Run);
asmBuilder.SetCustomAttribute(builder);
// Verify
object[] customAttributes = asmBuilder.GetCustomAttributes(attributeType).Select(a => (object)a).ToArray();
// We just support one custom attribute case
if (customAttributes.Length != 1)
return false;
object customAttribute = customAttributes[0];
for (int i = 0; i < namedProperties.Length; ++i)
{
PropertyInfo property = attributeType.GetProperty(namedProperties[i].Name);
object expected = property.GetValue(customAttribute, null);
object actual = propertyValues[i];
if (expected == null)
{
if (actual != null)
{
retVal = false;
break;
}
}
else
{
if (!expected.Equals(actual))
{
retVal = false;
break;
}
}
}
return retVal;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Collections
{
public partial class ArrayList : System.Collections.IEnumerable, System.Collections.IList
{
public ArrayList() { }
public ArrayList(System.Collections.ICollection c) { }
public ArrayList(int capacity) { }
public virtual int Capacity { get { return default(int); } set { } }
public virtual int Count { get { return default(int); } }
public virtual bool IsFixedSize { get { return default(bool); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual bool IsSynchronized { get { return default(bool); } }
public virtual object this[int index] { get { return default(object); } set { } }
public virtual object SyncRoot { get { return default(object); } }
public static System.Collections.ArrayList Adapter(System.Collections.IList list) { return default(System.Collections.ArrayList); }
public virtual int Add(object value) { return default(int); }
public virtual void AddRange(System.Collections.ICollection c) { }
public virtual int BinarySearch(int index, int count, object value, System.Collections.IComparer comparer) { return default(int); }
public virtual int BinarySearch(object value) { return default(int); }
public virtual int BinarySearch(object value, System.Collections.IComparer comparer) { return default(int); }
public virtual void Clear() { }
public virtual object Clone() { return default(object); }
public virtual bool Contains(object item) { return default(bool); }
public virtual void CopyTo(System.Array array) { }
public virtual void CopyTo(System.Array array, int arrayIndex) { }
public virtual void CopyTo(int index, System.Array array, int arrayIndex, int count) { }
public static System.Collections.ArrayList FixedSize(System.Collections.ArrayList list) { return default(System.Collections.ArrayList); }
public static System.Collections.IList FixedSize(System.Collections.IList list) { return default(System.Collections.IList); }
public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public virtual System.Collections.IEnumerator GetEnumerator(int index, int count) { return default(System.Collections.IEnumerator); }
public virtual System.Collections.ArrayList GetRange(int index, int count) { return default(System.Collections.ArrayList); }
public virtual int IndexOf(object value) { return default(int); }
public virtual int IndexOf(object value, int startIndex) { return default(int); }
public virtual int IndexOf(object value, int startIndex, int count) { return default(int); }
public virtual void Insert(int index, object value) { }
public virtual void InsertRange(int index, System.Collections.ICollection c) { }
public virtual int LastIndexOf(object value) { return default(int); }
public virtual int LastIndexOf(object value, int startIndex) { return default(int); }
public virtual int LastIndexOf(object value, int startIndex, int count) { return default(int); }
public static System.Collections.ArrayList ReadOnly(System.Collections.ArrayList list) { return default(System.Collections.ArrayList); }
public static System.Collections.IList ReadOnly(System.Collections.IList list) { return default(System.Collections.IList); }
public virtual void Remove(object obj) { }
public virtual void RemoveAt(int index) { }
public virtual void RemoveRange(int index, int count) { }
public static System.Collections.ArrayList Repeat(object value, int count) { return default(System.Collections.ArrayList); }
public virtual void Reverse() { }
public virtual void Reverse(int index, int count) { }
public virtual void SetRange(int index, System.Collections.ICollection c) { }
public virtual void Sort() { }
public virtual void Sort(System.Collections.IComparer comparer) { }
public virtual void Sort(int index, int count, System.Collections.IComparer comparer) { }
public static System.Collections.ArrayList Synchronized(System.Collections.ArrayList list) { return default(System.Collections.ArrayList); }
public static System.Collections.IList Synchronized(System.Collections.IList list) { return default(System.Collections.IList); }
public virtual object[] ToArray() { return default(object[]); }
public virtual System.Array ToArray(System.Type type) { return default(System.Array); }
public virtual void TrimToSize() { }
}
public partial class CaseInsensitiveComparer : System.Collections.IComparer
{
public CaseInsensitiveComparer() { }
public CaseInsensitiveComparer(System.Globalization.CultureInfo culture) { }
public static System.Collections.CaseInsensitiveComparer Default { get { return default(System.Collections.CaseInsensitiveComparer); } }
public static System.Collections.CaseInsensitiveComparer DefaultInvariant { get { return default(System.Collections.CaseInsensitiveComparer); } }
public int Compare(object a, object b) { return default(int); }
}
public abstract partial class CollectionBase : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
protected CollectionBase() { }
protected CollectionBase(int capacity) { }
public int Capacity { get { return default(int); } set { } }
public int Count { get { return default(int); } }
protected System.Collections.ArrayList InnerList { get { return default(System.Collections.ArrayList); } }
protected System.Collections.IList List { get { return default(System.Collections.IList); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IList.IsFixedSize { get { return default(bool); } }
bool System.Collections.IList.IsReadOnly { get { return default(bool); } }
object System.Collections.IList.this[int index] { get { return default(object); } set { } }
public void Clear() { }
public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
protected virtual void OnClear() { }
protected virtual void OnClearComplete() { }
protected virtual void OnInsert(int index, object value) { }
protected virtual void OnInsertComplete(int index, object value) { }
protected virtual void OnRemove(int index, object value) { }
protected virtual void OnRemoveComplete(int index, object value) { }
protected virtual void OnSet(int index, object oldValue, object newValue) { }
protected virtual void OnSetComplete(int index, object oldValue, object newValue) { }
protected virtual void OnValidate(object value) { }
public void RemoveAt(int index) { }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
int System.Collections.IList.Add(object value) { return default(int); }
bool System.Collections.IList.Contains(object value) { return default(bool); }
int System.Collections.IList.IndexOf(object value) { return default(int); }
void System.Collections.IList.Insert(int index, object value) { }
void System.Collections.IList.Remove(object value) { }
}
public sealed partial class Comparer : System.Collections.IComparer
{
public static readonly System.Collections.Comparer Default;
public static readonly System.Collections.Comparer DefaultInvariant;
public Comparer(System.Globalization.CultureInfo culture) { }
public int Compare(object a, object b) { return default(int); }
}
public abstract partial class DictionaryBase : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
protected DictionaryBase() { }
public int Count { get { return default(int); } }
protected System.Collections.IDictionary Dictionary { get { return default(System.Collections.IDictionary); } }
protected System.Collections.Hashtable InnerHashtable { get { return default(System.Collections.Hashtable); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } }
bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } }
object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } }
public void Clear() { }
public void CopyTo(System.Array array, int index) { }
public System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); }
protected virtual void OnClear() { }
protected virtual void OnClearComplete() { }
protected virtual object OnGet(object key, object currentValue) { return default(object); }
protected virtual void OnInsert(object key, object value) { }
protected virtual void OnInsertComplete(object key, object value) { }
protected virtual void OnRemove(object key, object value) { }
protected virtual void OnRemoveComplete(object key, object value) { }
protected virtual void OnSet(object key, object oldValue, object newValue) { }
protected virtual void OnSetComplete(object key, object oldValue, object newValue) { }
protected virtual void OnValidate(object key, object value) { }
void System.Collections.IDictionary.Add(object key, object value) { }
bool System.Collections.IDictionary.Contains(object key) { return default(bool); }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
public partial class Hashtable : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public Hashtable() { }
public Hashtable(System.Collections.IDictionary d) { }
public Hashtable(System.Collections.IDictionary d, System.Collections.IEqualityComparer equalityComparer) { }
public Hashtable(System.Collections.IDictionary d, float loadFactor) { }
public Hashtable(System.Collections.IDictionary d, float loadFactor, System.Collections.IEqualityComparer equalityComparer) { }
public Hashtable(System.Collections.IEqualityComparer equalityComparer) { }
public Hashtable(int capacity) { }
public Hashtable(int capacity, System.Collections.IEqualityComparer equalityComparer) { }
public Hashtable(int capacity, float loadFactor) { }
public Hashtable(int capacity, float loadFactor, System.Collections.IEqualityComparer equalityComparer) { }
public virtual int Count { get { return default(int); } }
protected System.Collections.IEqualityComparer EqualityComparer { get { return default(System.Collections.IEqualityComparer); } }
public virtual bool IsFixedSize { get { return default(bool); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual bool IsSynchronized { get { return default(bool); } }
public virtual object this[object key] { get { return default(object); } set { } }
public virtual System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } }
public virtual object SyncRoot { get { return default(object); } }
public virtual System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } }
public virtual void Add(object key, object value) { }
public virtual void Clear() { }
public virtual object Clone() { return default(object); }
public virtual bool Contains(object key) { return default(bool); }
public virtual bool ContainsKey(object key) { return default(bool); }
public virtual bool ContainsValue(object value) { return default(bool); }
public virtual void CopyTo(System.Array array, int arrayIndex) { }
public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); }
protected virtual int GetHash(object key) { return default(int); }
protected virtual bool KeyEquals(object item, object key) { return default(bool); }
public virtual void Remove(object key) { }
public static System.Collections.Hashtable Synchronized(System.Collections.Hashtable table) { return default(System.Collections.Hashtable); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
public partial class Queue : System.Collections.ICollection, System.Collections.IEnumerable
{
public Queue() { }
public Queue(System.Collections.ICollection col) { }
public Queue(int capacity) { }
public Queue(int capacity, float growFactor) { }
public virtual int Count { get { return default(int); } }
public virtual bool IsSynchronized { get { return default(bool); } }
public virtual object SyncRoot { get { return default(object); } }
public virtual void Clear() { }
public virtual object Clone() { return default(object); }
public virtual bool Contains(object obj) { return default(bool); }
public virtual void CopyTo(System.Array array, int index) { }
public virtual object Dequeue() { return default(object); }
public virtual void Enqueue(object obj) { }
public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public virtual object Peek() { return default(object); }
public static System.Collections.Queue Synchronized(System.Collections.Queue queue) { return default(System.Collections.Queue); }
public virtual object[] ToArray() { return default(object[]); }
public virtual void TrimToSize() { }
}
public abstract partial class ReadOnlyCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable
{
protected ReadOnlyCollectionBase() { }
public virtual int Count { get { return default(int); } }
protected System.Collections.ArrayList InnerList { get { return default(System.Collections.ArrayList); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
}
public partial class SortedList : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public SortedList() { }
public SortedList(System.Collections.IComparer comparer) { }
public SortedList(System.Collections.IComparer comparer, int capacity) { }
public SortedList(System.Collections.IDictionary d) { }
public SortedList(System.Collections.IDictionary d, System.Collections.IComparer comparer) { }
public SortedList(int initialCapacity) { }
public virtual int Capacity { get { return default(int); } set { } }
public virtual int Count { get { return default(int); } }
public virtual bool IsFixedSize { get { return default(bool); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual bool IsSynchronized { get { return default(bool); } }
public virtual object this[object key] { get { return default(object); } set { } }
public virtual System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } }
public virtual object SyncRoot { get { return default(object); } }
public virtual System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } }
public virtual void Add(object key, object value) { }
public virtual void Clear() { }
public virtual object Clone() { return default(object); }
public virtual bool Contains(object key) { return default(bool); }
public virtual bool ContainsKey(object key) { return default(bool); }
public virtual bool ContainsValue(object value) { return default(bool); }
public virtual void CopyTo(System.Array array, int arrayIndex) { }
public virtual object GetByIndex(int index) { return default(object); }
public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); }
public virtual object GetKey(int index) { return default(object); }
public virtual System.Collections.IList GetKeyList() { return default(System.Collections.IList); }
public virtual System.Collections.IList GetValueList() { return default(System.Collections.IList); }
public virtual int IndexOfKey(object key) { return default(int); }
public virtual int IndexOfValue(object value) { return default(int); }
public virtual void Remove(object key) { }
public virtual void RemoveAt(int index) { }
public virtual void SetByIndex(int index, object value) { }
public static System.Collections.SortedList Synchronized(System.Collections.SortedList list) { return default(System.Collections.SortedList); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public virtual void TrimToSize() { }
}
public partial class Stack : System.Collections.ICollection, System.Collections.IEnumerable
{
public Stack() { }
public Stack(System.Collections.ICollection col) { }
public Stack(int initialCapacity) { }
public virtual int Count { get { return default(int); } }
public virtual bool IsSynchronized { get { return default(bool); } }
public virtual object SyncRoot { get { return default(object); } }
public virtual void Clear() { }
public virtual object Clone() { return default(object); }
public virtual bool Contains(object obj) { return default(bool); }
public virtual void CopyTo(System.Array array, int index) { }
public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public virtual object Peek() { return default(object); }
public virtual object Pop() { return default(object); }
public virtual void Push(object obj) { }
public static System.Collections.Stack Synchronized(System.Collections.Stack stack) { return default(System.Collections.Stack); }
public virtual object[] ToArray() { return default(object[]); }
}
}
namespace System.Collections.Specialized
{
public partial class CollectionsUtil
{
public CollectionsUtil() { }
public static System.Collections.Hashtable CreateCaseInsensitiveHashtable() { return default(System.Collections.Hashtable); }
public static System.Collections.Hashtable CreateCaseInsensitiveHashtable(System.Collections.IDictionary d) { return default(System.Collections.Hashtable); }
public static System.Collections.Hashtable CreateCaseInsensitiveHashtable(int capacity) { return default(System.Collections.Hashtable); }
public static System.Collections.SortedList CreateCaseInsensitiveSortedList() { return default(System.Collections.SortedList); }
}
}
| |
using NUnit.Framework;
using SevenDigital.Api.Schema.Playlists;
using SevenDigital.Api.Schema.Playlists.Requests;
using SevenDigital.Api.Schema.Playlists.Response.Endpoints;
using SevenDigital.Api.Wrapper.Requests.Serializing;
using SevenDigital.Api.Wrapper.Responses.Parsing;
using System.Collections.Generic;
using System.Diagnostics;
namespace SevenDigital.Api.Schema.Unit.Tests.EntitySerialization.Playlists
{
public class XmlSerializationTests
{
[Test]
public void Should_deserialize_playlist_from_xml()
{
const string xml = @"
<response status=""ok"" version=""1.2"">
<playlist id=""51ed5cfec9021614f462bb7b"">
<name>party time</name>
<description>Hits to get the party started</description>
<status>Published</status>
<visibility>Public</visibility>
<image>http://artwork-cdn.7static.com/static/img/sleeveart/00/004/963/0000496338_$size$.jpg</image>
<tracks><track id=""524ae1a1c90216252c1837ab""><trackId>5495893</trackId><trackTitle>No You Girls</trackTitle></track></tracks>
<annotations>
<annotation key=""key"">value</annotation>
<annotation key=""anotherkey"">another value</annotation>
</annotations>
<lastUpdated>2013-10-02T12:16:04.615Z</lastUpdated>
</playlist>
</response>";
var response = new Wrapper.Responses.Response(System.Net.HttpStatusCode.OK, xml);
var playlist = new ResponseDeserializer().DeserializeResponse<Playlist>(response, true);
Assert.That(playlist.Id, Is.EqualTo("51ed5cfec9021614f462bb7b"));
Assert.That(playlist.Name, Is.EqualTo("party time"));
Assert.That(playlist.Description, Is.EqualTo("Hits to get the party started"));
Assert.That(playlist.Status, Is.EqualTo("Published"));
Assert.That(playlist.Visibility, Is.EqualTo(PlaylistVisibilityType.Public));
Assert.That(playlist.ImageUrl, Is.EqualTo("http://artwork-cdn.7static.com/static/img/sleeveart/00/004/963/0000496338_$size$.jpg"));
Assert.That(playlist.Tracks.Count, Is.EqualTo(1));
Assert.That(playlist.Tracks[0].PlaylistItemId, Is.EqualTo("524ae1a1c90216252c1837ab"));
Assert.That(playlist.Tracks[0].TrackId, Is.EqualTo("5495893"));
Assert.That(playlist.Tracks[0].TrackTitle, Is.EqualTo("No You Girls"));
Assert.That(playlist.LastUpdated.ToString("O"), Is.EqualTo("2013-10-02T12:16:04.6150000Z"));
Assert.That(playlist.Annotations.Count, Is.EqualTo(2));
Assert.That(playlist.Annotations[0].Key, Is.EqualTo("key"));
Assert.That(playlist.Annotations[0].Value, Is.EqualTo("value"));
}
[Test]
public void Should_deserialize_playlist_from_json()
{
const string json = @"{
""id"": ""51ed5cfec9021614f462bb7b"",
""name"": ""party time"",
""status"": ""published"",
""visibility"": ""Public"",
""imageUrl"": ""http://artwork-cdn.7static.com/static/img/sleeveart/00/004/963/0000496338_$size$.jpg"",
""description"": ""Hits to get the party started"",
""lastUpdated"": ""2013-10-02T12:16:04.615Z"",
""tracks"": [{
""playlistItemId"": ""52cd88c2c902161660aeab80"",
""trackId"": ""5495893"",
""trackTitle"": ""No You Girls""
}],
""annotations"": {
""key"": ""value"",
""another key"": ""another value""
},
""tags"": [{ ""name"": ""tag1"", ""playlistPosition"": 1 }, { ""name"": ""tag2"" }]
}";
var response = new Wrapper.Responses.Response(System.Net.HttpStatusCode.OK, new Dictionary<string, string>{ { "Content-Type", "application/json" } }, json);
var playlist = new ResponseDeserializer().DeserializeResponse<Playlist>(response, true);
Assert.That(playlist.Id, Is.EqualTo("51ed5cfec9021614f462bb7b"));
Assert.That(playlist.Name, Is.EqualTo("party time"));
Assert.That(playlist.Description, Is.EqualTo("Hits to get the party started"));
Assert.That(playlist.Status, Is.EqualTo("published"));
Assert.That(playlist.Visibility, Is.EqualTo(PlaylistVisibilityType.Public));
Assert.That(playlist.ImageUrl, Is.EqualTo("http://artwork-cdn.7static.com/static/img/sleeveart/00/004/963/0000496338_$size$.jpg"));
Assert.That(playlist.Tracks.Count, Is.EqualTo(1));
Assert.That(playlist.Tracks[0].PlaylistItemId, Is.EqualTo("52cd88c2c902161660aeab80"));
Assert.That(playlist.Tracks[0].TrackId, Is.EqualTo("5495893"));
Assert.That(playlist.Tracks[0].TrackTitle, Is.EqualTo("No You Girls"));
Assert.That(playlist.LastUpdated.ToString("O"), Is.EqualTo("2013-10-02T12:16:04.6150000Z"));
Assert.That(playlist.Annotations.Count, Is.EqualTo(2));
Assert.That(playlist.Annotations[0].Key, Is.EqualTo("key"));
Assert.That(playlist.Annotations[0].Value, Is.EqualTo("value"));
Assert.That(playlist.Annotations[1].Key, Is.EqualTo("another key"));
Assert.That(playlist.Annotations[1].Value, Is.EqualTo("another value"));
Assert.That(playlist.Tags.Count, Is.EqualTo(2));
Assert.That(playlist.Tags[0].Name, Is.EqualTo("tag1"));
Assert.That(playlist.Tags[0].PlaylistPosition, Is.EqualTo(1));
Assert.That(playlist.Tags[1].Name, Is.EqualTo("tag2"));
Assert.That(playlist.Tags[1].PlaylistPosition, Is.Null);
}
[Test]
public void Should_serialize_playlist_request_to_xml()
{
var playlistRequest = new PlaylistRequest
{
Description = "A New Playlist Description",
ImageUrl = "an-image-url",
Name = "New Playlist",
Tracks = new List<Product> {
new Product { TrackId = "12345" },
new Product { TrackId = "98765"}
},
Status = "Published",
Tags = new List<Tag>
{
new Tag { Name = "tag1", PlaylistPosition = 1 },
new Tag { Name = "tag2" }
},
Visibility = PlaylistVisibilityType.Private,
Annotations = new List<Annotation>
{
new Annotation("key", "value"),
new Annotation("another key", "another value")
}
};
var xml = new XmlPayloadSerializer().Serialize(playlistRequest);
Debug.WriteLine(xml);
const string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<playlist>" +
"<name>New Playlist</name>" +
"<visibility>Private</visibility>" +
"<status>Published</status>" +
"<description>A New Playlist Description</description>" +
"<image>an-image-url</image>" +
"<tags><tag><name>tag1</name><playlistPosition>1</playlistPosition></tag><tag><name>tag2</name><playlistPosition p4:nil=\"true\" xmlns:p4=\"http://www.w3.org/2001/XMLSchema-instance\" /></tag></tags>" +
"<annotations><annotation key=\"key\">value</annotation><annotation key=\"another key\">another value</annotation></annotations>" +
"<tracks><track><trackId>12345</trackId></track><track><trackId>98765</trackId></track></tracks>" +
"</playlist>";
Assert.That(xml, Is.EqualTo(expectedXml));
}
[Test]
public void Should_serialize_playlist_request_to_json()
{
var playlistRequest = new PlaylistRequest
{
Description = "A New Playlist Description",
ImageUrl = "an-image-url",
Name = "New Playlist",
Tracks = new List<Product> {
new Product { TrackId = "12345" },
new Product { TrackId = "98765"}
},
Status = "Published",
Tags = new List<Tag>
{
new Tag { Name="tag1", PlaylistPosition=1 },
new Tag { Name="tag2" }
},
Visibility = PlaylistVisibilityType.Private,
Annotations = new List<Annotation>
{
new Annotation("key", "value"),
new Annotation("another key", "another value")
}
};
var json = new JsonPayloadSerializer().Serialize(playlistRequest);
Debug.WriteLine(json);
var expectedJson = string.Join("",
"{",
"\"tracks\":[{\"trackId\":\"12345\"},{\"trackId\":\"98765\"}],",
"\"name\":\"New Playlist\",",
"\"visibility\":\"Private\",",
"\"status\":\"Published\",",
"\"description\":\"A New Playlist Description\",",
"\"imageUrl\":\"an-image-url\",",
"\"tags\":[{\"name\":\"tag1\",\"playlistPosition\":1},{\"name\":\"tag2\",\"playlistPosition\":null}],",
"\"annotations\":{",
"\"key\":\"value\",",
"\"another key\":\"another value\"",
"}",
"}"
);
Assert.That(json, Is.EqualTo(expectedJson));
}
[Test]
public void Should_initialize_playlist_collections()
{
var details = new PlaylistDetails();
Assert.That(details.Tags, Is.EqualTo(new List<Tag>()));
Assert.That(details.Annotations, Is.EqualTo(new List<Annotation>()));
var detailsRequest = new PlaylistDetailsRequest();
Assert.That(detailsRequest.Tags, Is.EqualTo(new List<Tag>()));
Assert.That(detailsRequest.Annotations, Is.EqualTo(new List<Annotation>()));
}
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework.Servers.HttpServer;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Xml;
namespace OpenSim.Framework.Console
{
public class ConsoleConnection
{
public int last;
public long lastLineSeen;
public bool newConnection = true;
}
// A console that uses REST interfaces
//
public class RemoteConsole : CommandConsole
{
private IHttpServer m_Server = null;
private IConfigSource m_Config = null;
private List<string> m_Scrollback = new List<string>();
private ThreadedClasses.BlockingQueue<string> m_InputData = new ThreadedClasses.BlockingQueue<string>();
private long m_LineNumber = 0;
private ThreadedClasses.RwLockedDictionary<UUID, ConsoleConnection> m_Connections =
new ThreadedClasses.RwLockedDictionary<UUID, ConsoleConnection>();
private string m_UserName = String.Empty;
private string m_Password = String.Empty;
private string m_AllowedOrigin = String.Empty;
public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
{
}
public void ReadConfig(IConfigSource config)
{
m_Config = config;
IConfig netConfig = m_Config.Configs["Network"];
if (netConfig == null)
return;
m_UserName = netConfig.GetString("ConsoleUser", String.Empty);
m_Password = netConfig.GetString("ConsolePass", String.Empty);
m_AllowedOrigin = netConfig.GetString("ConsoleAllowedOrigin", String.Empty);
}
public void SetServer(IHttpServer server)
{
m_Server = server;
m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
}
public override void Output(string text, string level)
{
lock (m_Scrollback)
{
while (m_Scrollback.Count >= 1000)
m_Scrollback.RemoveAt(0);
m_LineNumber++;
m_Scrollback.Add(String.Format("{0}", m_LineNumber)+":"+level+":"+text);
}
FireOnOutput(text.Trim());
System.Console.WriteLine(text.Trim());
}
public override void Output(string text)
{
Output(text, "normal");
}
public override string ReadLine(string p, bool isCommand, bool e)
{
if (isCommand)
Output("+++"+p);
else
Output("-++"+p);
string cmdinput = m_InputData.Dequeue();
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
if (cmd.Length != 0)
{
int i;
for (i=0 ; i < cmd.Length ; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
}
}
return cmdinput;
}
private Hashtable CheckOrigin(Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
result["access_control_allow_origin"] = m_AllowedOrigin;
return result;
}
/* TODO: Figure out how PollServiceHTTPHandler can access the request headers
* in order to use m_AllowedOrigin as a regular expression
private Hashtable CheckOrigin(Hashtable headers, Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
{
if (headers.ContainsKey("origin"))
{
string origin = headers["origin"].ToString();
if (Regex.IsMatch(origin, m_AllowedOrigin))
result["access_control_allow_origin"] = origin;
}
}
return result;
}
*/
private void DoExpire()
{
List<UUID> expired = new List<UUID>();
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
if (System.Environment.TickCount - kvp.Value.last > 500000)
expired.Add(kvp.Key);
}
foreach (UUID id in expired)
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
private Hashtable HandleHttpStartSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 401;
reply["content_type"] = "text/plain";
if (m_UserName == String.Empty)
return reply;
if (post["USER"] == null || post["PASS"] == null)
return reply;
if (m_UserName != post["USER"].ToString() ||
m_Password != post["PASS"].ToString())
{
return reply;
}
ConsoleConnection c = new ConsoleConnection();
c.last = System.Environment.TickCount;
c.lastLineSeen = 0;
UUID sessionID = UUID.Random();
m_Connections[sessionID] = c;
string uri = "/ReadResponses/" + sessionID.ToString() + "/";
m_Server.AddPollServiceHTTPHandler(
uri, new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, sessionID,25000)); // 25 secs timeout
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement id = xmldoc.CreateElement("", "SessionID", "");
id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
rootElement.AppendChild(id);
XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
rootElement.AppendChild(prompt);
rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable HandleHttpCloseSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
if (m_Connections.Remove(id))
{
CloseConnection(id);
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable HandleHttpSessionCommand(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
if (!m_Connections.ContainsKey(id))
return reply;
if (post["COMMAND"] == null)
return reply;
m_InputData.Enqueue(post["COMMAND"].ToString());
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable DecodePostString(string data)
{
Hashtable result = new Hashtable();
string[] terms = data.Split(new char[] {'&'});
foreach (string term in terms)
{
string[] elems = term.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
result[name] = value;
}
return result;
}
public void CloseConnection(UUID id)
{
try
{
string uri = "/ReadResponses/" + id.ToString() + "/";
m_Server.RemovePollServiceHTTPHandler("", uri);
}
catch (Exception)
{
}
}
private bool HasEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
if (!m_Connections.TryGetValue(sessionID, out c))
return false;
c.last = System.Environment.TickCount;
if (c.lastLineSeen < m_LineNumber)
return true;
return false;
}
private Hashtable GetEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
if (!m_Connections.TryGetValue(sessionID, out c))
return NoEvents(RequestID, UUID.Zero);
c.last = System.Environment.TickCount;
if (c.lastLineSeen >= m_LineNumber)
return NoEvents(RequestID, UUID.Zero);
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
if (c.newConnection)
{
c.newConnection = false;
Output("+++" + DefaultPrompt);
}
lock (m_Scrollback)
{
long startLine = m_LineNumber - m_Scrollback.Count;
long sendStart = startLine;
if (sendStart < c.lastLineSeen)
sendStart = c.lastLineSeen;
for (long i = sendStart ; i < m_LineNumber ; i++)
{
XmlElement res = xmldoc.CreateElement("", "Line", "");
long line = i + 1;
res.SetAttribute("Number", line.ToString());
res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
rootElement.AppendChild(res);
}
}
c.lastLineSeen = m_LineNumber;
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "application/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
private Hashtable NoEvents(UUID RequestID, UUID id)
{
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "text/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tenancy_config/time_factor_config.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.TenancyConfig {
/// <summary>Holder for reflection information generated from tenancy_config/time_factor_config.proto</summary>
public static partial class TimeFactorConfigReflection {
#region Descriptor
/// <summary>File descriptor for tenancy_config/time_factor_config.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TimeFactorConfigReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cid0ZW5hbmN5X2NvbmZpZy90aW1lX2ZhY3Rvcl9jb25maWcucHJvdG8SGmhv",
"bG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnGjx0ZW5hbmN5X2NvbmZpZy9pbmRp",
"Y2F0b3JzL3RpbWVfZmFjdG9yX2NvbmZpZ19pbmRpY2F0b3IucHJvdG8isAEK",
"EFRpbWVGYWN0b3JDb25maWcSUwoJZW50aXR5X2lkGAEgASgLMkAuaG9sbXMu",
"dHlwZXMudGVuYW5jeV9jb25maWcuaW5kaWNhdG9ycy5UaW1lRmFjdG9yQ29u",
"ZmlnSW5kaWNhdG9yEhoKEnRpbWVfaW50ZXJ2YWxfbmFtZRgCIAEoCRISCgpm",
"YXRvcl9yYXRlGAMgASgBEhcKD2hvdXJfb2ZfdGhlX2RheRgEIAEoBUIrWg10",
"ZW5hbmN5Y29uZmlnqgIZSE9MTVMuVHlwZXMuVGVuYW5jeUNvbmZpZ2IGcHJv",
"dG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.TenancyConfig.Indicators.TimeFactorConfigIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.TimeFactorConfig), global::HOLMS.Types.TenancyConfig.TimeFactorConfig.Parser, new[]{ "EntityId", "TimeIntervalName", "FatorRate", "HourOfTheDay" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class TimeFactorConfig : pb::IMessage<TimeFactorConfig> {
private static readonly pb::MessageParser<TimeFactorConfig> _parser = new pb::MessageParser<TimeFactorConfig>(() => new TimeFactorConfig());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TimeFactorConfig> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.TimeFactorConfigReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeFactorConfig() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeFactorConfig(TimeFactorConfig other) : this() {
EntityId = other.entityId_ != null ? other.EntityId.Clone() : null;
timeIntervalName_ = other.timeIntervalName_;
fatorRate_ = other.fatorRate_;
hourOfTheDay_ = other.hourOfTheDay_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeFactorConfig Clone() {
return new TimeFactorConfig(this);
}
/// <summary>Field number for the "entity_id" field.</summary>
public const int EntityIdFieldNumber = 1;
private global::HOLMS.Types.TenancyConfig.Indicators.TimeFactorConfigIndicator entityId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.Indicators.TimeFactorConfigIndicator EntityId {
get { return entityId_; }
set {
entityId_ = value;
}
}
/// <summary>Field number for the "time_interval_name" field.</summary>
public const int TimeIntervalNameFieldNumber = 2;
private string timeIntervalName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string TimeIntervalName {
get { return timeIntervalName_; }
set {
timeIntervalName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "fator_rate" field.</summary>
public const int FatorRateFieldNumber = 3;
private double fatorRate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double FatorRate {
get { return fatorRate_; }
set {
fatorRate_ = value;
}
}
/// <summary>Field number for the "hour_of_the_day" field.</summary>
public const int HourOfTheDayFieldNumber = 4;
private int hourOfTheDay_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int HourOfTheDay {
get { return hourOfTheDay_; }
set {
hourOfTheDay_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TimeFactorConfig);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TimeFactorConfig other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EntityId, other.EntityId)) return false;
if (TimeIntervalName != other.TimeIntervalName) return false;
if (FatorRate != other.FatorRate) return false;
if (HourOfTheDay != other.HourOfTheDay) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (entityId_ != null) hash ^= EntityId.GetHashCode();
if (TimeIntervalName.Length != 0) hash ^= TimeIntervalName.GetHashCode();
if (FatorRate != 0D) hash ^= FatorRate.GetHashCode();
if (HourOfTheDay != 0) hash ^= HourOfTheDay.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (entityId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(EntityId);
}
if (TimeIntervalName.Length != 0) {
output.WriteRawTag(18);
output.WriteString(TimeIntervalName);
}
if (FatorRate != 0D) {
output.WriteRawTag(25);
output.WriteDouble(FatorRate);
}
if (HourOfTheDay != 0) {
output.WriteRawTag(32);
output.WriteInt32(HourOfTheDay);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (entityId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId);
}
if (TimeIntervalName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TimeIntervalName);
}
if (FatorRate != 0D) {
size += 1 + 8;
}
if (HourOfTheDay != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(HourOfTheDay);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TimeFactorConfig other) {
if (other == null) {
return;
}
if (other.entityId_ != null) {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.TenancyConfig.Indicators.TimeFactorConfigIndicator();
}
EntityId.MergeFrom(other.EntityId);
}
if (other.TimeIntervalName.Length != 0) {
TimeIntervalName = other.TimeIntervalName;
}
if (other.FatorRate != 0D) {
FatorRate = other.FatorRate;
}
if (other.HourOfTheDay != 0) {
HourOfTheDay = other.HourOfTheDay;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.TenancyConfig.Indicators.TimeFactorConfigIndicator();
}
input.ReadMessage(entityId_);
break;
}
case 18: {
TimeIntervalName = input.ReadString();
break;
}
case 25: {
FatorRate = input.ReadDouble();
break;
}
case 32: {
HourOfTheDay = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.ComponentModel;
using System.Diagnostics.Contracts;
using System.Net;
using System.Net.Security;
using System.Runtime;
using System.Security.Authentication.ExtendedProtection;
namespace System.ServiceModel.Channels
{
public class HttpTransportBindingElement
: TransportBindingElement
{
private bool _allowCookies;
private AuthenticationSchemes _authenticationScheme;
private bool _bypassProxyOnLocal;
private bool _decompressionEnabled;
private HostNameComparisonMode _hostNameComparisonMode;
private bool _keepAliveEnabled;
private bool _inheritBaseAddressSettings;
private int _maxBufferSize;
private bool _maxBufferSizeInitialized;
private string _method;
private Uri _proxyAddress;
private AuthenticationSchemes _proxyAuthenticationScheme;
private string _realm;
private TimeSpan _requestInitializationTimeout;
private TransferMode _transferMode;
private bool _unsafeConnectionNtlmAuthentication;
private bool _useDefaultWebProxy;
private WebSocketTransportSettings _webSocketSettings;
private ExtendedProtectionPolicy _extendedProtectionPolicy;
private HttpMessageHandlerFactory _httpMessageHandlerFactory;
private int _maxPendingAccepts;
public HttpTransportBindingElement()
: base()
{
_allowCookies = HttpTransportDefaults.AllowCookies;
_authenticationScheme = HttpTransportDefaults.AuthenticationScheme;
_bypassProxyOnLocal = HttpTransportDefaults.BypassProxyOnLocal;
_decompressionEnabled = HttpTransportDefaults.DecompressionEnabled;
_hostNameComparisonMode = HttpTransportDefaults.HostNameComparisonMode;
_keepAliveEnabled = HttpTransportDefaults.KeepAliveEnabled;
_maxBufferSize = TransportDefaults.MaxBufferSize;
_maxPendingAccepts = HttpTransportDefaults.DefaultMaxPendingAccepts;
_method = string.Empty;
_realm = HttpTransportDefaults.Realm;
_requestInitializationTimeout = HttpTransportDefaults.RequestInitializationTimeout;
_transferMode = HttpTransportDefaults.TransferMode;
_unsafeConnectionNtlmAuthentication = HttpTransportDefaults.UnsafeConnectionNtlmAuthentication;
_useDefaultWebProxy = HttpTransportDefaults.UseDefaultWebProxy;
_webSocketSettings = HttpTransportDefaults.GetDefaultWebSocketTransportSettings();
}
protected HttpTransportBindingElement(HttpTransportBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
_allowCookies = elementToBeCloned._allowCookies;
_authenticationScheme = elementToBeCloned._authenticationScheme;
_bypassProxyOnLocal = elementToBeCloned._bypassProxyOnLocal;
_decompressionEnabled = elementToBeCloned._decompressionEnabled;
_hostNameComparisonMode = elementToBeCloned._hostNameComparisonMode;
_inheritBaseAddressSettings = elementToBeCloned.InheritBaseAddressSettings;
_keepAliveEnabled = elementToBeCloned._keepAliveEnabled;
_maxBufferSize = elementToBeCloned._maxBufferSize;
_maxBufferSizeInitialized = elementToBeCloned._maxBufferSizeInitialized;
_maxPendingAccepts = elementToBeCloned._maxPendingAccepts;
_method = elementToBeCloned._method;
_realm = elementToBeCloned._realm;
_requestInitializationTimeout = elementToBeCloned._requestInitializationTimeout;
_transferMode = elementToBeCloned._transferMode;
_unsafeConnectionNtlmAuthentication = elementToBeCloned._unsafeConnectionNtlmAuthentication;
_useDefaultWebProxy = elementToBeCloned._useDefaultWebProxy;
_webSocketSettings = elementToBeCloned._webSocketSettings.Clone();
_extendedProtectionPolicy = elementToBeCloned.ExtendedProtectionPolicy;
this.MessageHandlerFactory = elementToBeCloned.MessageHandlerFactory;
}
[DefaultValue(HttpTransportDefaults.AllowCookies)]
public bool AllowCookies
{
get
{
return _allowCookies;
}
set
{
_allowCookies = value;
}
}
[DefaultValue(HttpTransportDefaults.AuthenticationScheme)]
public AuthenticationSchemes AuthenticationScheme
{
get
{
return _authenticationScheme;
}
set
{
_authenticationScheme = value;
}
}
[DefaultValue(HttpTransportDefaults.BypassProxyOnLocal)]
public bool BypassProxyOnLocal
{
get
{
return _bypassProxyOnLocal;
}
set
{
_bypassProxyOnLocal = value;
}
}
[DefaultValue(HttpTransportDefaults.DecompressionEnabled)]
public bool DecompressionEnabled
{
get
{
return _decompressionEnabled;
}
set
{
_decompressionEnabled = value;
}
}
[DefaultValue(HttpTransportDefaults.HostNameComparisonMode)]
public HostNameComparisonMode HostNameComparisonMode
{
get
{
return _hostNameComparisonMode;
}
set
{
HostNameComparisonModeHelper.Validate(value);
_hostNameComparisonMode = value;
}
}
public HttpMessageHandlerFactory MessageHandlerFactory
{
get
{
return _httpMessageHandlerFactory;
}
set
{
_httpMessageHandlerFactory = value;
}
}
public ExtendedProtectionPolicy ExtendedProtectionPolicy
{
get
{
return _extendedProtectionPolicy;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
if (value.PolicyEnforcement == PolicyEnforcement.Always &&
!System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy.OSSupportsExtendedProtection)
{
ExceptionHelper.PlatformNotSupported(SR.ExtendedProtectionNotSupported);
}
_extendedProtectionPolicy = value;
}
}
// MB#26970: used by MEX to ensure that we don't conflict on base-address scoped settings
internal bool InheritBaseAddressSettings
{
get
{
return _inheritBaseAddressSettings;
}
set
{
_inheritBaseAddressSettings = value;
}
}
[DefaultValue(HttpTransportDefaults.KeepAliveEnabled)]
public bool KeepAliveEnabled
{
get
{
return _keepAliveEnabled;
}
set
{
_keepAliveEnabled = value;
}
}
// client
// server
[DefaultValue(TransportDefaults.MaxBufferSize)]
public int MaxBufferSize
{
get
{
if (_maxBufferSizeInitialized || TransferMode != TransferMode.Buffered)
return _maxBufferSize;
long maxReceivedMessageSize = MaxReceivedMessageSize;
if (maxReceivedMessageSize > int.MaxValue)
return int.MaxValue;
else
return (int)maxReceivedMessageSize;
}
set
{
if (value <= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.ValueMustBePositive));
}
_maxBufferSizeInitialized = true;
_maxBufferSize = value;
}
}
// server
[DefaultValue(HttpTransportDefaults.DefaultMaxPendingAccepts)]
public int MaxPendingAccepts
{
get
{
return _maxPendingAccepts;
}
set
{
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.ValueMustBeNonNegative));
}
if (value > HttpTransportDefaults.MaxPendingAcceptsUpperLimit)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.Format(SR.HttpMaxPendingAcceptsTooLargeError, HttpTransportDefaults.MaxPendingAcceptsUpperLimit)));
}
_maxPendingAccepts = value;
}
}
// string.Empty == wildcard
internal string Method
{
get
{
return _method;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
_method = value;
}
}
[DefaultValue(HttpTransportDefaults.ProxyAddress)]
[TypeConverter(typeof(UriTypeConverter))]
public Uri ProxyAddress
{
get
{
return _proxyAddress;
}
set
{
_proxyAddress = value;
}
}
[DefaultValue(HttpTransportDefaults.ProxyAuthenticationScheme)]
public AuthenticationSchemes ProxyAuthenticationScheme
{
get
{
return _proxyAuthenticationScheme;
}
set
{
if (!value.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(nameof(value), SR.Format(SR.HttpProxyRequiresSingleAuthScheme,
value));
}
_proxyAuthenticationScheme = value;
}
}
[DefaultValue(HttpTransportDefaults.Realm)]
public string Realm
{
get
{
return _realm;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
_realm = value;
}
}
[DefaultValue(typeof(TimeSpan), HttpTransportDefaults.RequestInitializationTimeoutString)]
public TimeSpan RequestInitializationTimeout
{
get
{
return _requestInitializationTimeout;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRange0));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRangeTooBig));
}
_requestInitializationTimeout = value;
}
}
public override string Scheme { get { return "http"; } }
// client
// server
[DefaultValue(HttpTransportDefaults.TransferMode)]
public TransferMode TransferMode
{
get
{
return _transferMode;
}
set
{
TransferModeHelper.Validate(value);
_transferMode = value;
}
}
public WebSocketTransportSettings WebSocketSettings
{
get
{
return _webSocketSettings;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
_webSocketSettings = value;
}
}
internal virtual bool GetSupportsClientAuthenticationImpl(AuthenticationSchemes effectiveAuthenticationSchemes)
{
return effectiveAuthenticationSchemes != AuthenticationSchemes.None &&
effectiveAuthenticationSchemes.IsNotSet(AuthenticationSchemes.Anonymous);
}
internal virtual bool GetSupportsClientWindowsIdentityImpl(AuthenticationSchemes effectiveAuthenticationSchemes)
{
return effectiveAuthenticationSchemes != AuthenticationSchemes.None &&
effectiveAuthenticationSchemes.IsNotSet(AuthenticationSchemes.Anonymous);
}
[DefaultValue(HttpTransportDefaults.UnsafeConnectionNtlmAuthentication)]
public bool UnsafeConnectionNtlmAuthentication
{
get
{
return _unsafeConnectionNtlmAuthentication;
}
set
{
_unsafeConnectionNtlmAuthentication = value;
}
}
[DefaultValue(HttpTransportDefaults.UseDefaultWebProxy)]
public bool UseDefaultWebProxy
{
get
{
return _useDefaultWebProxy;
}
set
{
_useDefaultWebProxy = value;
}
}
internal string GetWsdlTransportUri(bool useWebSocketTransport)
{
if (useWebSocketTransport)
{
return TransportPolicyConstants.WebSocketTransportUri;
}
return TransportPolicyConstants.HttpTransportUri;
}
public override BindingElement Clone()
{
return new HttpTransportBindingElement(this);
}
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (typeof(T) == typeof(ISecurityCapabilities))
{
AuthenticationSchemes effectiveAuthenticationSchemes = this.AuthenticationScheme;
// Desktop: HttpTransportBindingElement.GetEffectiveAuthenticationSchemes(this.AuthenticationScheme, context.BindingParameters);
return (T)(object)new SecurityCapabilities(this.GetSupportsClientAuthenticationImpl(effectiveAuthenticationSchemes),
effectiveAuthenticationSchemes == AuthenticationSchemes.Negotiate,
this.GetSupportsClientWindowsIdentityImpl(effectiveAuthenticationSchemes),
ProtectionLevel.None,
ProtectionLevel.None);
}
else if (typeof(T) == typeof(IBindingDeliveryCapabilities))
{
return (T)(object)new BindingDeliveryCapabilitiesHelper();
}
else if (typeof(T) == typeof(TransferMode))
{
return (T)(object)this.TransferMode;
}
else if (typeof(T) == typeof(ExtendedProtectionPolicy))
{
return (T)(object)this.ExtendedProtectionPolicy;
}
else if (typeof(T) == typeof(ITransportCompressionSupport))
{
return (T)(object)new TransportCompressionSupportHelper();
}
else
{
Contract.Assert(context.BindingParameters != null);
if (context.BindingParameters.Find<MessageEncodingBindingElement>() == null)
{
context.BindingParameters.Add(new TextMessageEncodingBindingElement());
}
return base.GetProperty<T>(context);
}
}
public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
{
if (typeof(TChannel) == typeof(IRequestChannel))
{
return this.WebSocketSettings.TransportUsage != WebSocketTransportUsage.Always;
}
else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
return this.WebSocketSettings.TransportUsage != WebSocketTransportUsage.Never;
}
return false;
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (this.MessageHandlerFactory != null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(SR.HttpPipelineNotSupportedOnClientSide, "MessageHandlerFactory")));
}
if (!this.CanBuildChannelFactory<TChannel>(context))
{
Contract.Assert(context.Binding != null);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.Format(SR.CouldnTCreateChannelForChannelType2, context.Binding.Name, typeof(TChannel)));
}
if (_authenticationScheme == AuthenticationSchemes.None)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpAuthSchemeCannotBeNone,
_authenticationScheme));
}
else if (!_authenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
_authenticationScheme));
}
return (IChannelFactory<TChannel>)(object)new HttpChannelFactory<TChannel>(this, context);
}
internal override bool IsMatch(BindingElement b)
{
if (!base.IsMatch(b))
return false;
HttpTransportBindingElement http = b as HttpTransportBindingElement;
if (http == null)
return false;
if (_allowCookies != http._allowCookies)
return false;
if (_authenticationScheme != http._authenticationScheme)
return false;
if (_decompressionEnabled != http._decompressionEnabled)
return false;
if (_hostNameComparisonMode != http._hostNameComparisonMode)
return false;
if (_inheritBaseAddressSettings != http._inheritBaseAddressSettings)
return false;
if (_keepAliveEnabled != http._keepAliveEnabled)
return false;
if (_maxBufferSize != http._maxBufferSize)
return false;
if (_method != http._method)
return false;
if (_realm != http._realm)
return false;
if (_transferMode != http._transferMode)
return false;
if (_unsafeConnectionNtlmAuthentication != http._unsafeConnectionNtlmAuthentication)
return false;
if (_useDefaultWebProxy != http._useDefaultWebProxy)
return false;
if (!this.WebSocketSettings.Equals(http.WebSocketSettings))
return false;
return true;
}
private MessageEncodingBindingElement FindMessageEncodingBindingElement(BindingElementCollection bindingElements, out bool createdNew)
{
createdNew = false;
MessageEncodingBindingElement encodingBindingElement = bindingElements.Find<MessageEncodingBindingElement>();
if (encodingBindingElement == null)
{
createdNew = true;
encodingBindingElement = new TextMessageEncodingBindingElement();
}
return encodingBindingElement;
}
private class BindingDeliveryCapabilitiesHelper : IBindingDeliveryCapabilities
{
internal BindingDeliveryCapabilitiesHelper()
{
}
bool IBindingDeliveryCapabilities.AssuresOrderedDelivery
{
get { return false; }
}
bool IBindingDeliveryCapabilities.QueuedDelivery
{
get { return false; }
}
}
private class TransportCompressionSupportHelper : ITransportCompressionSupport
{
public bool IsCompressionFormatSupported(CompressionFormat compressionFormat)
{
return true;
}
}
}
}
| |
//
// namespace.cs: Tracks namespaces
//
// Author:
// Miguel de Icaza (miguel@ximian.com)
// Marek Safar (marek.safar@seznam.cz)
//
// Copyright 2001 Ximian, Inc.
// Copyright 2003-2008 Novell, Inc.
// Copyright 2011 Xamarin Inc
//
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.CompilerServices.SymbolWriter;
namespace Mono.CSharp {
public class RootNamespace : Namespace {
readonly string alias_name;
readonly Dictionary<string, Namespace> all_namespaces;
public RootNamespace (string alias_name)
: base ()
{
this.alias_name = alias_name;
RegisterNamespace (this);
all_namespaces = new Dictionary<string, Namespace> ();
all_namespaces.Add ("", this);
}
public string Alias {
get {
return alias_name;
}
}
public static void Error_GlobalNamespaceRedefined (Report report, Location loc)
{
report.Error (1681, loc, "The global extern alias cannot be redefined");
}
//
// For better error reporting where we try to guess missing using directive
//
public List<string> FindTypeNamespaces (IMemberContext ctx, string name, int arity)
{
List<string> res = null;
foreach (var ns in all_namespaces) {
var type = ns.Value.LookupType (ctx, name, arity, LookupMode.Normal, Location.Null);
if (type != null) {
if (res == null)
res = new List<string> ();
res.Add (ns.Key);
}
}
return res;
}
//
// For better error reporting where compiler tries to guess missing using directive
//
public List<string> FindExtensionMethodNamespaces (IMemberContext ctx, string name, int arity)
{
List<string> res = null;
foreach (var ns in all_namespaces) {
if (ns.Key.Length == 0)
continue;
var methods = ns.Value.LookupExtensionMethod (ctx, name, arity);
if (methods != null) {
if (res == null)
res = new List<string> ();
res.Add (ns.Key);
}
}
return res;
}
public void RegisterNamespace (Namespace child)
{
if (child != this)
all_namespaces.Add (child.Name, child);
}
public override string GetSignatureForError ()
{
return alias_name + "::";
}
}
public sealed class GlobalRootNamespace : RootNamespace
{
public GlobalRootNamespace ()
: base ("global")
{
}
}
//
// Namespace cache for imported and compiled namespaces
//
public class Namespace
{
readonly Namespace parent;
string fullname;
protected Dictionary<string, Namespace> namespaces;
protected Dictionary<string, IList<TypeSpec>> types;
List<TypeSpec> extension_method_types;
Dictionary<string, TypeSpec> cached_types;
bool cls_checked;
/// <summary>
/// Constructor Takes the current namespace and the
/// name. This is bootstrapped with parent == null
/// and name = ""
/// </summary>
public Namespace (Namespace parent, string name)
: this ()
{
if (name == null)
throw new ArgumentNullException ("name");
this.parent = parent;
string pname = parent != null ? parent.fullname : null;
if (pname == null)
fullname = name;
else
fullname = pname + "." + name;
while (parent.parent != null)
parent = parent.parent;
var root = parent as RootNamespace;
if (root == null)
throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
root.RegisterNamespace (this);
}
protected Namespace ()
{
namespaces = new Dictionary<string, Namespace> ();
cached_types = new Dictionary<string, TypeSpec> ();
}
#region Properties
/// <summary>
/// The qualified name of the current namespace
/// </summary>
public string Name {
get { return fullname; }
}
/// <summary>
/// The parent of this namespace, used by the parser to "Pop"
/// the current namespace declaration
/// </summary>
public Namespace Parent {
get { return parent; }
}
#endregion
public Namespace AddNamespace (MemberName name)
{
var ns_parent = name.Left == null ? this : AddNamespace (name.Left);
return ns_parent.TryAddNamespace (name.Basename);
}
Namespace TryAddNamespace (string name)
{
Namespace ns;
if (!namespaces.TryGetValue (name, out ns)) {
ns = new Namespace (this, name);
namespaces.Add (name, ns);
}
return ns;
}
public bool TryGetNamespace (string name, out Namespace ns)
{
return namespaces.TryGetValue (name, out ns);
}
// TODO: Replace with CreateNamespace where MemberName is created for the method call
public Namespace GetNamespace (string name, bool create)
{
int pos = name.IndexOf ('.');
Namespace ns;
string first;
if (pos >= 0)
first = name.Substring (0, pos);
else
first = name;
if (!namespaces.TryGetValue (first, out ns)) {
if (!create)
return null;
ns = new Namespace (this, first);
namespaces.Add (first, ns);
}
if (pos >= 0)
ns = ns.GetNamespace (name.Substring (pos + 1), create);
return ns;
}
public IList<TypeSpec> GetAllTypes (string name)
{
IList<TypeSpec> found;
if (types == null || !types.TryGetValue (name, out found))
return null;
return found;
}
public virtual string GetSignatureForError ()
{
return fullname;
}
public TypeSpec LookupType (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
{
if (types == null)
return null;
TypeSpec best = null;
if (arity == 0 && cached_types.TryGetValue (name, out best)) {
if (best != null || mode != LookupMode.IgnoreAccessibility)
return best;
}
IList<TypeSpec> found;
if (!types.TryGetValue (name, out found))
return null;
foreach (var ts in found) {
if (ts.Arity == arity) {
if (best == null) {
if ((ts.Modifiers & Modifiers.INTERNAL) != 0 && !ts.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly) && mode != LookupMode.IgnoreAccessibility)
continue;
best = ts;
continue;
}
if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported) {
if (ts.Kind == MemberKind.MissingType)
continue;
if (best.Kind == MemberKind.MissingType) {
best = ts;
continue;
}
if (mode == LookupMode.Normal) {
ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
ctx.Module.Compiler.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
}
break;
}
if (ts.Kind == MemberKind.MissingType)
continue;
if (best.MemberDefinition.IsImported)
best = ts;
if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly))
continue;
if (mode != LookupMode.Normal)
continue;
if (ts.MemberDefinition.IsImported) {
ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
}
ctx.Module.Compiler.Report.Warning (436, 2, loc,
"The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
best.GetSignatureForError ());
}
//
// Lookup for the best candidate with the closest arity match
//
if (arity < 0) {
if (best == null) {
best = ts;
} else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
best = ts;
}
}
}
// TODO MemberCache: Cache more
if (arity == 0 && mode == LookupMode.Normal)
cached_types.Add (name, best);
if (best != null) {
var dep = best.GetMissingDependencies ();
if (dep != null)
ImportedTypeDefinition.Error_MissingDependency (ctx, dep, loc);
}
return best;
}
public FullNamedExpression LookupTypeOrNamespace (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
{
var texpr = LookupType (ctx, name, arity, mode, loc);
Namespace ns;
if (arity == 0 && namespaces.TryGetValue (name, out ns)) {
if (texpr == null)
return new NamespaceExpression (ns, loc);
if (mode != LookupMode.Probing) {
//ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (texpr.Type);
// ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ns.loc, "");
ctx.Module.Compiler.Report.Warning (437, 2, loc,
"The type `{0}' conflicts with the imported namespace `{1}'. Using the definition found in the source file",
texpr.GetSignatureForError (), ns.GetSignatureForError ());
}
if (texpr.MemberDefinition.IsImported)
return new NamespaceExpression (ns, loc);
}
if (texpr == null)
return null;
return new TypeExpression (texpr, loc);
}
//
// Completes types with the given `prefix'
//
public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
{
if (types == null)
return Enumerable.Empty<string> ();
var res = from item in types
where item.Key.StartsWith (prefix) && item.Value.Any (l => (l.Modifiers & Modifiers.PUBLIC) != 0)
select item.Key;
if (namespaces != null)
res = res.Concat (from item in namespaces where item.Key.StartsWith (prefix) select item.Key);
return res;
}
//
// Looks for extension method in this namespace
//
public List<MethodSpec> LookupExtensionMethod (IMemberContext invocationContext, string name, int arity)
{
if (extension_method_types == null)
return null;
List<MethodSpec> found = null;
for (int i = 0; i < extension_method_types.Count; ++i) {
var ts = extension_method_types[i];
//
// When the list was built we didn't know what members the type
// contains
//
if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0) {
if (extension_method_types.Count == 1) {
extension_method_types = null;
return found;
}
extension_method_types.RemoveAt (i--);
continue;
}
var res = ts.MemberCache.FindExtensionMethods (invocationContext, name, arity);
if (res == null)
continue;
if (found == null) {
found = res;
} else {
found.AddRange (res);
}
}
return found;
}
public void AddType (ModuleContainer module, TypeSpec ts)
{
if (types == null) {
types = new Dictionary<string, IList<TypeSpec>> (64);
}
if (ts.IsClass && ts.Arity == 0) {
var extension_method_allowed = ts.MemberDefinition.IsImported ? (ts.Modifiers & Modifiers.METHOD_EXTENSION) != 0 : (ts.IsStatic || ts.MemberDefinition.IsPartial);
if (extension_method_allowed) {
if (extension_method_types == null)
extension_method_types = new List<TypeSpec> ();
extension_method_types.Add (ts);
}
}
var name = ts.Name;
IList<TypeSpec> existing;
if (types.TryGetValue (name, out existing)) {
TypeSpec better_type;
TypeSpec found;
if (existing.Count == 1) {
found = existing[0];
if (ts.Arity == found.Arity) {
better_type = IsImportedTypeOverride (module, ts, found);
if (better_type == found)
return;
if (better_type != null) {
existing [0] = better_type;
return;
}
}
existing = new List<TypeSpec> ();
existing.Add (found);
types[name] = existing;
} else {
for (int i = 0; i < existing.Count; ++i) {
found = existing[i];
if (ts.Arity != found.Arity)
continue;
better_type = IsImportedTypeOverride (module, ts, found);
if (better_type == found)
return;
if (better_type != null) {
existing.RemoveAt (i);
--i;
continue;
}
}
}
existing.Add (ts);
} else {
types.Add (name, new TypeSpec[] { ts });
}
}
//
// We import any types but in the situation there are same types
// but one has better visibility (either public or internal with friend)
// the less visible type is removed from the namespace cache
//
public static TypeSpec IsImportedTypeOverride (ModuleContainer module, TypeSpec ts, TypeSpec found)
{
var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || ts.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || found.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
if (ts_accessible && !found_accessible)
return ts;
// found is better always better for accessible or inaccessible ts
if (!ts_accessible)
return found;
return null;
}
public void RemoveContainer (TypeContainer tc)
{
IList<TypeSpec> found;
if (types.TryGetValue (tc.MemberName.Name, out found)) {
for (int i = 0; i < found.Count; ++i) {
if (tc.MemberName.Arity != found [i].Arity)
continue;
if (found.Count == 1)
types.Remove (tc.MemberName.Name);
else
found.RemoveAt (i);
break;
}
}
cached_types.Remove (tc.MemberName.Basename);
}
public void SetBuiltinType (BuiltinTypeSpec pts)
{
var found = types[pts.Name];
cached_types.Remove (pts.Name);
if (found.Count == 1) {
types[pts.Name][0] = pts;
} else {
throw new NotImplementedException ();
}
}
public void VerifyClsCompliance ()
{
if (types == null || cls_checked)
return;
cls_checked = true;
// TODO: This is quite ugly way to check for CLS compliance at namespace level
var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
foreach (var tgroup in types.Values) {
foreach (var tm in tgroup) {
if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
continue;
List<TypeSpec> found;
if (!locase_types.TryGetValue (tm.Name, out found)) {
found = new List<TypeSpec> ();
locase_types.Add (tm.Name, found);
}
found.Add (tm);
}
}
foreach (var locase in locase_types.Values) {
if (locase.Count < 2)
continue;
bool all_same = true;
foreach (var notcompliant in locase) {
all_same = notcompliant.Name == locase[0].Name;
if (!all_same)
break;
}
if (all_same)
continue;
TypeContainer compiled = null;
foreach (var notcompliant in locase) {
if (!notcompliant.MemberDefinition.IsImported) {
if (compiled != null)
compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
compiled = notcompliant.MemberDefinition as TypeContainer;
} else {
compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
}
}
compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
"Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
}
}
}
public class CompilationSourceFile : NamespaceContainer
{
readonly SourceFile file;
CompileUnitEntry comp_unit;
Dictionary<string, SourceFile> include_files;
Dictionary<string, bool> conditionals;
public CompilationSourceFile (ModuleContainer parent, SourceFile sourceFile)
: this (parent)
{
this.file = sourceFile;
}
public CompilationSourceFile (ModuleContainer parent)
: base (parent)
{
}
public CompileUnitEntry SymbolUnitEntry {
get {
return comp_unit;
}
}
public string FileName {
get {
return file.Name;
}
}
public SourceFile SourceFile {
get {
return file;
}
}
public void AddIncludeFile (SourceFile file)
{
if (file == this.file)
return;
if (include_files == null)
include_files = new Dictionary<string, SourceFile> ();
if (!include_files.ContainsKey (file.OriginalFullPathName))
include_files.Add (file.OriginalFullPathName, file);
}
public void AddDefine (string value)
{
if (conditionals == null)
conditionals = new Dictionary<string, bool> (2);
conditionals[value] = true;
}
public void AddUndefine (string value)
{
if (conditionals == null)
conditionals = new Dictionary<string, bool> (2);
conditionals[value] = false;
}
public override void PrepareEmit ()
{
var sw = Module.DeclaringAssembly.SymbolWriter;
if (sw != null) {
CreateUnitSymbolInfo (sw, Compiler.Settings.PathMap);
}
base.PrepareEmit ();
}
//
// Creates symbol file index in debug symbol file
//
void CreateUnitSymbolInfo (MonoSymbolFile symwriter, List<KeyValuePair<string, string>> pathMap)
{
var si = file.CreateSymbolInfo (symwriter, pathMap);
comp_unit = new CompileUnitEntry (symwriter, si);
if (include_files != null) {
foreach (SourceFile include in include_files.Values) {
si = include.CreateSymbolInfo (symwriter, pathMap);
comp_unit.AddFile (si);
}
}
}
public bool IsConditionalDefined (string value)
{
if (conditionals != null) {
bool res;
if (conditionals.TryGetValue (value, out res))
return res;
// When conditional was undefined
if (conditionals.ContainsKey (value))
return false;
}
return Compiler.Settings.IsConditionalSymbolDefined (value);
}
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
//
// Namespace block as created by the parser
//
public class NamespaceContainer : TypeContainer, IMemberContext
{
static readonly Namespace[] empty_namespaces = new Namespace[0];
readonly Namespace ns;
public new readonly NamespaceContainer Parent;
List<UsingClause> clauses;
// Used by parsed to check for parser errors
public bool DeclarationFound;
Namespace[] namespace_using_table;
TypeSpec[] types_using_table;
Dictionary<string, UsingAliasNamespace> aliases;
public NamespaceContainer (MemberName name, NamespaceContainer parent)
: base (parent, name, null, MemberKind.Namespace)
{
this.Parent = parent;
this.ns = parent.NS.AddNamespace (name);
containers = new List<TypeContainer> ();
}
protected NamespaceContainer (ModuleContainer parent)
: base (parent, null, null, MemberKind.Namespace)
{
ns = parent.GlobalRootNamespace;
containers = new List<TypeContainer> (2);
}
#region Properties
public override AttributeTargets AttributeTargets {
get {
throw new NotSupportedException ();
}
}
public override string DocCommentHeader {
get {
throw new NotSupportedException ();
}
}
public Namespace NS {
get {
return ns;
}
}
public List<UsingClause> Usings {
get {
return clauses;
}
}
public override string[] ValidAttributeTargets {
get {
throw new NotSupportedException ();
}
}
#endregion
public void AddUsing (UsingClause un)
{
if (DeclarationFound){
Compiler.Report.Error (1529, un.Location, "A using clause must precede all other namespace elements except extern alias declarations");
}
if (clauses == null)
clauses = new List<UsingClause> ();
clauses.Add (un);
}
public void AddUsing (UsingAliasNamespace un)
{
if (DeclarationFound){
Compiler.Report.Error (1529, un.Location, "A using clause must precede all other namespace elements except extern alias declarations");
}
AddAlias (un);
}
void AddAlias (UsingAliasNamespace un)
{
if (clauses == null) {
clauses = new List<UsingClause> ();
} else {
foreach (var entry in clauses) {
var a = entry as UsingAliasNamespace;
if (a != null && a.Alias.Value == un.Alias.Value) {
Compiler.Report.SymbolRelatedToPreviousError (a.Location, "");
Compiler.Report.Error (1537, un.Location,
"The using alias `{0}' appeared previously in this namespace", un.Alias.Value);
}
}
}
clauses.Add (un);
}
public override void AddPartial (TypeDefinition next_part)
{
var existing = ns.LookupType (this, next_part.MemberName.Name, next_part.MemberName.Arity, LookupMode.Probing, Location.Null);
var td = existing != null ? existing.MemberDefinition as TypeDefinition : null;
AddPartial (next_part, td);
}
public override void AddTypeContainer (TypeContainer tc)
{
var mn = tc.MemberName;
var name = mn.Basename;
while (mn.Left != null) {
mn = mn.Left;
name = mn.Name;
}
var names_container = Parent == null ? Module : (TypeContainer) this;
MemberCore mc;
if (names_container.DefinedNames.TryGetValue (name, out mc)) {
if (tc is NamespaceContainer && mc is NamespaceContainer) {
AddTypeContainerMember (tc);
return;
}
Report.SymbolRelatedToPreviousError (mc);
if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (tc is ClassOrStruct || tc is Interface)) {
Error_MissingPartialModifier (tc);
} else {
Report.Error (101, tc.Location, "The namespace `{0}' already contains a definition for `{1}'",
GetSignatureForError (), mn.GetSignatureForError ());
}
} else {
names_container.DefinedNames.Add (name, tc);
var tdef = tc.PartialContainer;
if (tdef != null) {
//
// Same name conflict in different namespace containers
//
var conflict = ns.GetAllTypes (mn.Name);
if (conflict != null) {
foreach (var e in conflict) {
if (e.Arity == mn.Arity) {
mc = (MemberCore) e.MemberDefinition;
break;
}
}
}
if (mc != null) {
Report.SymbolRelatedToPreviousError (mc);
Report.Error (101, tc.Location, "The namespace `{0}' already contains a definition for `{1}'",
GetSignatureForError (), mn.GetSignatureForError ());
} else {
ns.AddType (Module, tdef.Definition);
}
}
}
base.AddTypeContainer (tc);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
throw new NotSupportedException ();
}
public override void EmitContainer ()
{
VerifyClsCompliance ();
base.EmitContainer ();
}
public ExtensionMethodCandidates LookupExtensionMethod (IMemberContext invocationContext, string name, int arity, int position)
{
//
// Here we try to resume the search for extension method at the point
// where the last bunch of candidates was found. It's more tricky than
// it seems as we have to check both namespace containers and namespace
// in correct order.
//
// Consider:
//
// namespace A {
// using N1;
// namespace B.C.D {
// <our first search found candidates in A.B.C.D
// }
// }
//
// In the example above namespace A.B.C.D, A.B.C and A.B have to be
// checked before we hit A.N1 using
//
ExtensionMethodCandidates candidates;
var container = this;
do {
candidates = container.LookupExtensionMethodCandidates (invocationContext, name, arity, ref position);
if (candidates != null || container.MemberName == null)
return candidates;
var container_ns = container.ns.Parent;
var mn = container.MemberName.Left;
int already_checked = position - 2;
while (already_checked-- > 0) {
mn = mn.Left;
container_ns = container_ns.Parent;
}
while (mn != null) {
++position;
var methods = container_ns.LookupExtensionMethod (invocationContext, name, arity);
if (methods != null) {
return new ExtensionMethodCandidates (invocationContext, methods, container, position);
}
mn = mn.Left;
container_ns = container_ns.Parent;
}
position = 0;
container = container.Parent;
} while (container != null);
return null;
}
ExtensionMethodCandidates LookupExtensionMethodCandidates (IMemberContext invocationContext, string name, int arity, ref int position)
{
List<MethodSpec> candidates = null;
if (position == 0) {
++position;
candidates = ns.LookupExtensionMethod (invocationContext, name, arity);
if (candidates != null) {
return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
}
}
if (position == 1) {
++position;
foreach (Namespace n in namespace_using_table) {
var a = n.LookupExtensionMethod (invocationContext, name, arity);
if (a == null)
continue;
if (candidates == null)
candidates = a;
else
candidates.AddRange (a);
}
if (types_using_table != null) {
foreach (var t in types_using_table) {
var res = t.MemberCache.FindExtensionMethods (invocationContext, name, arity);
if (res == null)
continue;
if (candidates == null)
candidates = res;
else
candidates.AddRange (res);
}
}
if (candidates != null)
return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
}
return null;
}
public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
{
//
// Only simple names (no dots) will be looked up with this function
//
FullNamedExpression resolved;
for (NamespaceContainer container = this; container != null; container = container.Parent) {
resolved = container.Lookup (name, arity, mode, loc);
if (resolved != null || container.MemberName == null)
return resolved;
var container_ns = container.ns.Parent;
var mn = container.MemberName.Left;
while (mn != null) {
resolved = container_ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
if (resolved != null)
return resolved;
mn = mn.Left;
container_ns = container_ns.Parent;
}
}
return null;
}
public override void GetCompletionStartingWith (string prefix, List<string> results)
{
if (Usings == null)
return;
foreach (var un in Usings) {
if (un.Alias != null)
continue;
var name = un.NamespaceExpression.Name;
if (name.StartsWith (prefix))
results.Add (name);
}
IEnumerable<string> all = Enumerable.Empty<string> ();
foreach (Namespace using_ns in namespace_using_table) {
if (prefix.StartsWith (using_ns.Name)) {
int ld = prefix.LastIndexOf ('.');
if (ld != -1) {
string rest = prefix.Substring (ld + 1);
all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
}
}
all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
}
results.AddRange (all);
base.GetCompletionStartingWith (prefix, results);
}
//
// Looks-up a alias named @name in this and surrounding namespace declarations
//
public FullNamedExpression LookupExternAlias (string name)
{
if (aliases == null)
return null;
UsingAliasNamespace uan;
if (aliases.TryGetValue (name, out uan) && uan is UsingExternAlias)
return uan.ResolvedExpression;
return null;
}
//
// Looks-up a alias named @name in this and surrounding namespace declarations
//
public override FullNamedExpression LookupNamespaceAlias (string name)
{
for (NamespaceContainer n = this; n != null; n = n.Parent) {
if (n.aliases == null)
continue;
UsingAliasNamespace uan;
if (n.aliases.TryGetValue (name, out uan)) {
if (uan.ResolvedExpression == null)
uan.Define (n);
return uan.ResolvedExpression;
}
}
return null;
}
FullNamedExpression Lookup (string name, int arity, LookupMode mode, Location loc)
{
//
// Check whether it's in the namespace.
//
FullNamedExpression fne = ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
//
// Check aliases.
//
if (aliases != null && arity == 0) {
UsingAliasNamespace uan;
if (aliases.TryGetValue (name, out uan)) {
if (fne != null && mode != LookupMode.Probing) {
// TODO: Namespace has broken location
//Report.SymbolRelatedToPreviousError (fne.Location, null);
Compiler.Report.SymbolRelatedToPreviousError (uan.Location, null);
Compiler.Report.Error (576, loc,
"Namespace `{0}' contains a definition with same name as alias `{1}'",
GetSignatureForError (), name);
}
if (uan.ResolvedExpression == null)
uan.Define (this);
return uan.ResolvedExpression;
}
}
if (fne != null)
return fne;
//
// Lookup can be called before the namespace is defined from different namespace using alias clause
//
if (namespace_using_table == null) {
DoDefineNamespace ();
}
//
// Check using entries.
//
FullNamedExpression match = null;
foreach (Namespace using_ns in namespace_using_table) {
//
// A using directive imports only types contained in the namespace, it
// does not import any nested namespaces
//
var t = using_ns.LookupType (this, name, arity, mode, loc);
if (t == null)
continue;
fne = new TypeExpression (t, loc);
if (match == null) {
match = fne;
continue;
}
// Prefer types over namespaces
var texpr_fne = fne as TypeExpr;
var texpr_match = match as TypeExpr;
if (texpr_fne != null && texpr_match == null) {
match = fne;
continue;
} else if (texpr_fne == null) {
continue;
}
// It can be top level accessibility only
var better = Namespace.IsImportedTypeOverride (Module, texpr_match.Type, texpr_fne.Type);
if (better == null) {
if (mode == LookupMode.Normal) {
Error_AmbiguousReference (name, texpr_match, texpr_fne, loc);
}
return match;
}
if (better == texpr_fne.Type)
match = texpr_fne;
}
if (types_using_table != null && (mode & LookupMode.IgnoreStaticUsing) == 0) {
foreach (var using_type in types_using_table) {
var type = MemberCache.FindNestedType (using_type, name, arity, true);
if (type == null)
continue;
fne = new TypeExpression (type, loc);
if (match == null) {
match = fne;
continue;
}
if (mode == LookupMode.Normal) {
Error_AmbiguousReference (name, match, fne, loc);
}
}
}
return match;
}
void Error_AmbiguousReference (string name, FullNamedExpression a, FullNamedExpression b, Location loc)
{
var report = Compiler.Report;
report.SymbolRelatedToPreviousError (a.Type);
report.SymbolRelatedToPreviousError (b.Type);
report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
name, a.GetSignatureForError (), b.GetSignatureForError ());
}
public static Expression LookupStaticUsings (IMemberContext mc, string name, int arity, Location loc)
{
for (var m = mc.CurrentMemberDefinition; m != null; m = m.Parent) {
var nc = m as NamespaceContainer;
if (nc == null)
continue;
List<MemberSpec> candidates = null;
if (nc.types_using_table != null) {
foreach (var using_type in nc.types_using_table) {
var members = MemberCache.FindMembers (using_type, name, true);
if (members == null)
continue;
foreach (var member in members) {
if ((member.Kind & MemberKind.NestedMask) != 0) {
// non-static nested type is included with using static
} else {
if ((member.Modifiers & Modifiers.STATIC) == 0)
continue;
if ((member.Modifiers & Modifiers.METHOD_EXTENSION) != 0)
continue;
}
if (arity > 0 && member.Arity != arity)
continue;
if (candidates == null)
candidates = new List<MemberSpec> ();
candidates.Add (member);
}
}
}
if (candidates != null) {
var expr = Expression.MemberLookupToExpression (mc, candidates, false, null, name, arity, Expression.MemberLookupRestrictions.None, loc);
if (expr != null)
return expr;
}
}
return null;
}
protected override void DefineNamespace ()
{
if (namespace_using_table == null)
DoDefineNamespace ();
base.DefineNamespace ();
}
void DoDefineNamespace ()
{
namespace_using_table = empty_namespaces;
if (clauses != null) {
List<Namespace> namespaces = null;
List<TypeSpec> types = null;
bool post_process_using_aliases = false;
for (int i = 0; i < clauses.Count; ++i) {
var entry = clauses[i];
if (entry.Alias != null) {
if (aliases == null)
aliases = new Dictionary<string, UsingAliasNamespace> ();
//
// Aliases are not available when resolving using section
// except extern aliases
//
if (entry is UsingExternAlias) {
entry.Define (this);
if (entry.ResolvedExpression != null)
aliases.Add (entry.Alias.Value, (UsingExternAlias) entry);
clauses.RemoveAt (i--);
} else {
post_process_using_aliases = true;
}
continue;
}
try {
entry.Define (this);
} finally {
//
// It's needed for repl only, when using clause cannot be resolved don't hold it in
// global list which is resolved for every evaluation
//
if (entry.ResolvedExpression == null) {
clauses.RemoveAt (i--);
}
}
if (entry.ResolvedExpression == null)
continue;
var using_ns = entry.ResolvedExpression as NamespaceExpression;
if (using_ns == null) {
var type = entry.ResolvedExpression.Type;
if (types == null)
types = new List<TypeSpec> ();
if (types.Contains (type)) {
Warning_DuplicateEntry (entry);
} else {
types.Add (type);
}
} else {
if (namespaces == null)
namespaces = new List<Namespace> ();
if (namespaces.Contains (using_ns.Namespace)) {
// Ensure we don't report the warning multiple times in repl
clauses.RemoveAt (i--);
Warning_DuplicateEntry (entry);
} else {
namespaces.Add (using_ns.Namespace);
}
}
}
namespace_using_table = namespaces == null ? new Namespace [0] : namespaces.ToArray ();
if (types != null)
types_using_table = types.ToArray ();
if (post_process_using_aliases) {
for (int i = 0; i < clauses.Count; ++i) {
var entry = clauses[i];
if (entry.Alias != null) {
aliases[entry.Alias.Value] = (UsingAliasNamespace) entry;
}
}
}
}
}
protected override void DoDefineContainer ()
{
base.DoDefineContainer ();
if (clauses != null) {
for (int i = 0; i < clauses.Count; ++i) {
var entry = clauses[i];
//
// Finish definition of using aliases not visited during container
// definition
//
if (entry.Alias != null && entry.ResolvedExpression == null) {
entry.Define (this);
}
}
}
}
public void EnableRedefinition ()
{
is_defined = false;
namespace_using_table = null;
}
internal override void GenerateDocComment (DocumentationBuilder builder)
{
if (containers != null) {
foreach (var tc in containers)
tc.GenerateDocComment (builder);
}
}
public override string GetSignatureForError ()
{
return MemberName == null ? "global::" : base.GetSignatureForError ();
}
public override void RemoveContainer (TypeContainer cont)
{
base.RemoveContainer (cont);
NS.RemoveContainer (cont);
}
protected override bool VerifyClsCompliance ()
{
if (Module.IsClsComplianceRequired ()) {
if (MemberName != null && MemberName.Name[0] == '_') {
Warning_IdentifierNotCompliant ();
}
ns.VerifyClsCompliance ();
return true;
}
return false;
}
void Warning_DuplicateEntry (UsingClause entry)
{
Compiler.Report.Warning (105, 3, entry.Location,
"The using directive for `{0}' appeared previously in this namespace",
entry.ResolvedExpression.GetSignatureForError ());
}
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
public class UsingNamespace : UsingClause
{
public UsingNamespace (ATypeNameExpression expr, Location loc)
: base (expr, loc)
{
}
public override void Define (NamespaceContainer ctx)
{
base.Define (ctx);
var ns = resolved as NamespaceExpression;
if (ns != null)
return;
if (resolved != null) {
var compiler = ctx.Module.Compiler;
var type = resolved.Type;
resolved = null;
compiler.Report.SymbolRelatedToPreviousError (type);
compiler.Report.Error (138, Location,
"A `using' directive can only be applied to namespaces but `{0}' denotes a type. Consider using a `using static' instead",
type.GetSignatureForError ());
}
}
}
public class UsingType : UsingClause
{
public UsingType (ATypeNameExpression expr, Location loc)
: base (expr, loc)
{
}
public override void Define (NamespaceContainer ctx)
{
base.Define (ctx);
if (resolved == null)
return;
var ns = resolved as NamespaceExpression;
if (ns != null) {
var compiler = ctx.Module.Compiler;
compiler.Report.Error (7007, Location,
"A 'using static' directive can only be applied to types but `{0}' denotes a namespace. Consider using a `using' directive instead",
ns.GetSignatureForError ());
return;
}
// TODO: Need to move it to post_process_using_aliases
//ObsoleteAttribute obsolete_attr = resolved.Type.GetAttributeObsolete ();
//if (obsolete_attr != null) {
// AttributeTester.Report_ObsoleteMessage (obsolete_attr, resolved.GetSignatureForError (), Location, ctx.Compiler.Report);
//}
}
}
public class UsingClause
{
readonly ATypeNameExpression expr;
readonly Location loc;
protected FullNamedExpression resolved;
public UsingClause (ATypeNameExpression expr, Location loc)
{
this.expr = expr;
this.loc = loc;
}
#region Properties
public virtual SimpleMemberName Alias {
get {
return null;
}
}
public Location Location {
get {
return loc;
}
}
public ATypeNameExpression NamespaceExpression {
get {
return expr;
}
}
public FullNamedExpression ResolvedExpression {
get {
return resolved;
}
}
#endregion
public string GetSignatureForError ()
{
return expr.GetSignatureForError ();
}
public virtual void Define (NamespaceContainer ctx)
{
resolved = expr.ResolveAsTypeOrNamespace (ctx, false);
}
public override string ToString()
{
return resolved.ToString();
}
}
public class UsingExternAlias : UsingAliasNamespace
{
public UsingExternAlias (SimpleMemberName alias, Location loc)
: base (alias, null, loc)
{
}
public override void Define (NamespaceContainer ctx)
{
var ns = ctx.Module.GetRootNamespace (Alias.Value);
if (ns == null) {
ctx.Module.Compiler.Report.Error (430, Location,
"The extern alias `{0}' was not specified in -reference option",
Alias.Value);
return;
}
resolved = new NamespaceExpression (ns, Location);
}
}
public class UsingAliasNamespace : UsingNamespace
{
readonly SimpleMemberName alias;
public struct AliasContext : IMemberContext
{
readonly NamespaceContainer ns;
public AliasContext (NamespaceContainer ns)
{
this.ns = ns;
}
public TypeSpec CurrentType {
get {
return null;
}
}
public TypeParameters CurrentTypeParameters {
get {
return null;
}
}
public MemberCore CurrentMemberDefinition {
get {
return null;
}
}
public bool IsObsolete {
get {
return false;
}
}
public bool IsUnsafe {
get {
throw new NotImplementedException ();
}
}
public bool IsStatic {
get {
throw new NotImplementedException ();
}
}
public ModuleContainer Module {
get {
return ns.Module;
}
}
public string GetSignatureForError ()
{
throw new NotImplementedException ();
}
public ExtensionMethodCandidates LookupExtensionMethod (string name, int arity)
{
return null;
}
public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
{
var fne = ns.NS.LookupTypeOrNamespace (ns, name, arity, mode, loc);
if (fne != null)
return fne;
//
// Only extern aliases are allowed in this context
//
fne = ns.LookupExternAlias (name);
if (fne != null || ns.MemberName == null)
return fne;
var container_ns = ns.NS.Parent;
var mn = ns.MemberName.Left;
while (mn != null) {
fne = container_ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
if (fne != null)
return fne;
mn = mn.Left;
container_ns = container_ns.Parent;
}
if (ns.Parent != null)
return ns.Parent.LookupNamespaceOrType (name, arity, mode, loc);
return null;
}
public FullNamedExpression LookupNamespaceAlias (string name)
{
return ns.LookupNamespaceAlias (name);
}
}
public UsingAliasNamespace (SimpleMemberName alias, ATypeNameExpression expr, Location loc)
: base (expr, loc)
{
this.alias = alias;
}
public override SimpleMemberName Alias {
get {
return alias;
}
}
public override void Define (NamespaceContainer ctx)
{
//
// The namespace-or-type-name of a using-alias-directive is resolved as if
// the immediately containing compilation unit or namespace body had no
// using-directives. A using-alias-directive may however be affected
// by extern-alias-directives in the immediately containing compilation
// unit or namespace body
//
// We achieve that by introducing alias-context which redirect any local
// namespace or type resolve calls to parent namespace
//
resolved = NamespaceExpression.ResolveAsTypeOrNamespace (new AliasContext (ctx), false) ??
new TypeExpression (InternalType.ErrorType, NamespaceExpression.Location);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Student Notes and Attachments Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class STNATDataSet : EduHubDataSet<STNAT>
{
/// <inheritdoc />
public override string Name { get { return "STNAT"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal STNATDataSet(EduHubContext Context)
: base(Context)
{
Index_NOTE_TYPE = new Lazy<NullDictionary<string, IReadOnlyList<STNAT>>>(() => this.ToGroupedNullDictionary(i => i.NOTE_TYPE));
Index_SKEY = new Lazy<Dictionary<string, IReadOnlyList<STNAT>>>(() => this.ToGroupedDictionary(i => i.SKEY));
Index_TID = new Lazy<Dictionary<int, STNAT>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="STNAT" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="STNAT" /> fields for each CSV column header</returns>
internal override Action<STNAT, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<STNAT, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "SKEY":
mapper[i] = (e, v) => e.SKEY = v;
break;
case "NOTE_TYPE":
mapper[i] = (e, v) => e.NOTE_TYPE = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v;
break;
case "REMARK":
mapper[i] = (e, v) => e.REMARK = v;
break;
case "ATTACHMENT":
mapper[i] = (e, v) => e.ATTACHMENT = null; // eduHub is not encoding byte arrays
break;
case "ATTACH_DATE":
mapper[i] = (e, v) => e.ATTACH_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "ADDED_BY":
mapper[i] = (e, v) => e.ADDED_BY = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="STNAT" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="STNAT" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="STNAT" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{STNAT}"/> of entities</returns>
internal override IEnumerable<STNAT> ApplyDeltaEntities(IEnumerable<STNAT> Entities, List<STNAT> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.SKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<STNAT>>> Index_NOTE_TYPE;
private Lazy<Dictionary<string, IReadOnlyList<STNAT>>> Index_SKEY;
private Lazy<Dictionary<int, STNAT>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find STNAT by NOTE_TYPE field
/// </summary>
/// <param name="NOTE_TYPE">NOTE_TYPE value used to find STNAT</param>
/// <returns>List of related STNAT entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STNAT> FindByNOTE_TYPE(string NOTE_TYPE)
{
return Index_NOTE_TYPE.Value[NOTE_TYPE];
}
/// <summary>
/// Attempt to find STNAT by NOTE_TYPE field
/// </summary>
/// <param name="NOTE_TYPE">NOTE_TYPE value used to find STNAT</param>
/// <param name="Value">List of related STNAT entities</param>
/// <returns>True if the list of related STNAT entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByNOTE_TYPE(string NOTE_TYPE, out IReadOnlyList<STNAT> Value)
{
return Index_NOTE_TYPE.Value.TryGetValue(NOTE_TYPE, out Value);
}
/// <summary>
/// Attempt to find STNAT by NOTE_TYPE field
/// </summary>
/// <param name="NOTE_TYPE">NOTE_TYPE value used to find STNAT</param>
/// <returns>List of related STNAT entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STNAT> TryFindByNOTE_TYPE(string NOTE_TYPE)
{
IReadOnlyList<STNAT> value;
if (Index_NOTE_TYPE.Value.TryGetValue(NOTE_TYPE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STNAT by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STNAT</param>
/// <returns>List of related STNAT entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STNAT> FindBySKEY(string SKEY)
{
return Index_SKEY.Value[SKEY];
}
/// <summary>
/// Attempt to find STNAT by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STNAT</param>
/// <param name="Value">List of related STNAT entities</param>
/// <returns>True if the list of related STNAT entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySKEY(string SKEY, out IReadOnlyList<STNAT> Value)
{
return Index_SKEY.Value.TryGetValue(SKEY, out Value);
}
/// <summary>
/// Attempt to find STNAT by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STNAT</param>
/// <returns>List of related STNAT entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STNAT> TryFindBySKEY(string SKEY)
{
IReadOnlyList<STNAT> value;
if (Index_SKEY.Value.TryGetValue(SKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STNAT by TID field
/// </summary>
/// <param name="TID">TID value used to find STNAT</param>
/// <returns>Related STNAT entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public STNAT FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find STNAT by TID field
/// </summary>
/// <param name="TID">TID value used to find STNAT</param>
/// <param name="Value">Related STNAT entity</param>
/// <returns>True if the related STNAT entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out STNAT Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find STNAT by TID field
/// </summary>
/// <param name="TID">TID value used to find STNAT</param>
/// <returns>Related STNAT entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public STNAT TryFindByTID(int TID)
{
STNAT value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a STNAT table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STNAT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[STNAT](
[TID] int IDENTITY NOT NULL,
[SKEY] varchar(10) NOT NULL,
[NOTE_TYPE] varchar(10) NULL,
[DESCRIPTION] varchar(30) NULL,
[REMARK] varchar(MAX) NULL,
[ATTACHMENT] varbinary(MAX) NULL,
[ATTACH_DATE] datetime NULL,
[ADDED_BY] varchar(128) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [STNAT_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [STNAT_Index_NOTE_TYPE] ON [dbo].[STNAT]
(
[NOTE_TYPE] ASC
);
CREATE CLUSTERED INDEX [STNAT_Index_SKEY] ON [dbo].[STNAT]
(
[SKEY] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STNAT]') AND name = N'STNAT_Index_NOTE_TYPE')
ALTER INDEX [STNAT_Index_NOTE_TYPE] ON [dbo].[STNAT] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STNAT]') AND name = N'STNAT_Index_TID')
ALTER INDEX [STNAT_Index_TID] ON [dbo].[STNAT] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STNAT]') AND name = N'STNAT_Index_NOTE_TYPE')
ALTER INDEX [STNAT_Index_NOTE_TYPE] ON [dbo].[STNAT] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STNAT]') AND name = N'STNAT_Index_TID')
ALTER INDEX [STNAT_Index_TID] ON [dbo].[STNAT] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STNAT"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="STNAT"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STNAT> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[STNAT] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the STNAT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the STNAT data set</returns>
public override EduHubDataSetDataReader<STNAT> GetDataSetDataReader()
{
return new STNATDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the STNAT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the STNAT data set</returns>
public override EduHubDataSetDataReader<STNAT> GetDataSetDataReader(List<STNAT> Entities)
{
return new STNATDataReader(new EduHubDataSetLoadedReader<STNAT>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class STNATDataReader : EduHubDataSetDataReader<STNAT>
{
public STNATDataReader(IEduHubDataSetReader<STNAT> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 11; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // SKEY
return Current.SKEY;
case 2: // NOTE_TYPE
return Current.NOTE_TYPE;
case 3: // DESCRIPTION
return Current.DESCRIPTION;
case 4: // REMARK
return Current.REMARK;
case 5: // ATTACHMENT
return Current.ATTACHMENT;
case 6: // ATTACH_DATE
return Current.ATTACH_DATE;
case 7: // ADDED_BY
return Current.ADDED_BY;
case 8: // LW_DATE
return Current.LW_DATE;
case 9: // LW_TIME
return Current.LW_TIME;
case 10: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // NOTE_TYPE
return Current.NOTE_TYPE == null;
case 3: // DESCRIPTION
return Current.DESCRIPTION == null;
case 4: // REMARK
return Current.REMARK == null;
case 5: // ATTACHMENT
return Current.ATTACHMENT == null;
case 6: // ATTACH_DATE
return Current.ATTACH_DATE == null;
case 7: // ADDED_BY
return Current.ADDED_BY == null;
case 8: // LW_DATE
return Current.LW_DATE == null;
case 9: // LW_TIME
return Current.LW_TIME == null;
case 10: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // SKEY
return "SKEY";
case 2: // NOTE_TYPE
return "NOTE_TYPE";
case 3: // DESCRIPTION
return "DESCRIPTION";
case 4: // REMARK
return "REMARK";
case 5: // ATTACHMENT
return "ATTACHMENT";
case 6: // ATTACH_DATE
return "ATTACH_DATE";
case 7: // ADDED_BY
return "ADDED_BY";
case 8: // LW_DATE
return "LW_DATE";
case 9: // LW_TIME
return "LW_TIME";
case 10: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "SKEY":
return 1;
case "NOTE_TYPE":
return 2;
case "DESCRIPTION":
return 3;
case "REMARK":
return 4;
case "ATTACHMENT":
return 5;
case "ATTACH_DATE":
return 6;
case "ADDED_BY":
return 7;
case "LW_DATE":
return 8;
case "LW_TIME":
return 9;
case "LW_USER":
return 10;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Runtime.Versioning
{
public sealed class FrameworkName : IEquatable<FrameworkName>
{
private readonly string _identifier;
private readonly Version _version;
private readonly string _profile;
private string _fullName;
private const char ComponentSeparator = ',';
private const char KeyValueSeparator = '=';
private const char VersionValuePrefix = 'v';
private const string VersionKey = "Version";
private const string ProfileKey = "Profile";
private static readonly char[] s_componentSplitSeparator = { ComponentSeparator };
public string Identifier
{
get
{
Debug.Assert(_identifier != null);
return _identifier;
}
}
public Version Version
{
get
{
Debug.Assert(_version != null);
return _version;
}
}
public string Profile
{
get
{
Debug.Assert(_profile != null);
return _profile;
}
}
public string FullName
{
get
{
if (_fullName == null)
{
if (string.IsNullOrEmpty(Profile))
{
_fullName =
Identifier +
ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix +
Version.ToString();
}
else
{
_fullName =
Identifier +
ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix +
Version.ToString() +
ComponentSeparator + ProfileKey + KeyValueSeparator +
Profile;
}
}
Debug.Assert(_fullName != null);
return _fullName;
}
}
public override bool Equals(object obj)
{
return Equals(obj as FrameworkName);
}
public bool Equals(FrameworkName other)
{
if (object.ReferenceEquals(other, null))
{
return false;
}
return Identifier == other.Identifier &&
Version == other.Version &&
Profile == other.Profile;
}
public override int GetHashCode()
{
return Identifier.GetHashCode() ^ Version.GetHashCode() ^ Profile.GetHashCode();
}
public override string ToString()
{
return FullName;
}
public FrameworkName(string identifier, Version version)
: this(identifier, version, null)
{
}
public FrameworkName(string identifier, Version version, string profile)
{
if (identifier == null)
{
throw new ArgumentNullException(nameof(identifier));
}
identifier = identifier.Trim();
if (identifier.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(identifier)), nameof(identifier));
}
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
_identifier = identifier;
_version = version;
_profile = (profile == null) ? string.Empty : profile.Trim();
}
// Parses strings in the following format: "<identifier>, Version=[v|V]<version>, Profile=<profile>"
// - The identifier and version is required, profile is optional
// - Only three components are allowed.
// - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed
public FrameworkName(string frameworkName)
{
if (frameworkName == null)
{
throw new ArgumentNullException(nameof(frameworkName));
}
if (frameworkName.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(frameworkName)), nameof(frameworkName));
}
string[] components = frameworkName.Split(s_componentSplitSeparator);
// Identifier and Version are required, Profile is optional.
if (components.Length < 2 || components.Length > 3)
{
throw new ArgumentException(SR.Argument_FrameworkNameTooShort, nameof(frameworkName));
}
//
// 1) Parse the "Identifier", which must come first. Trim any whitespace
//
_identifier = components[0].Trim();
if (_identifier.Length == 0)
{
throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName));
}
bool versionFound = false;
_profile = string.Empty;
//
// The required "Version" and optional "Profile" component can be in any order
//
for (int i = 1; i < components.Length; i++)
{
// Get the key/value pair separated by '='
string component = components[i];
int separatorIndex = component.IndexOf(KeyValueSeparator);
if (separatorIndex == -1 || separatorIndex != component.LastIndexOf(KeyValueSeparator))
{
throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName));
}
// Get the key and value, trimming any whitespace
ReadOnlySpan<char> key = component.AsSpan(0, separatorIndex).Trim();
ReadOnlySpan<char> value = component.AsSpan(separatorIndex + 1).Trim();
//
// 2) Parse the required "Version" key value
//
if (key.Equals(VersionKey, StringComparison.OrdinalIgnoreCase))
{
versionFound = true;
// Allow the version to include a 'v' or 'V' prefix...
if (value.Length > 0 && (value[0] == VersionValuePrefix || value[0] == 'V'))
{
value = value.Slice(1);
}
try
{
_version = Version.Parse(value);
}
catch (Exception e)
{
throw new ArgumentException(SR.Argument_FrameworkNameInvalidVersion, nameof(frameworkName), e);
}
}
//
// 3) Parse the optional "Profile" key value
//
else if (key.Equals(ProfileKey, StringComparison.OrdinalIgnoreCase))
{
if (value.Length > 0)
{
_profile = value.ToString();
}
}
else
{
throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName));
}
}
if (!versionFound)
{
throw new ArgumentException(SR.Argument_FrameworkNameMissingVersion, nameof(frameworkName));
}
}
public static bool operator ==(FrameworkName left, FrameworkName right)
{
if (object.ReferenceEquals(left, null))
{
return object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static bool operator !=(FrameworkName left, FrameworkName right)
{
return !(left == right);
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SchoolBusAPI.Models;
namespace SchoolBusAPI.Models
{
/// <summary>
/// A table managed in the application by authorized users to create named Roles that can be assigned to Users as needed. Roles can be created as needed to support the users of the system and the roles they perform within the organization.
/// </summary>
[MetaDataExtension (Description = "A table managed in the application by authorized users to create named Roles that can be assigned to Users as needed. Roles can be created as needed to support the users of the system and the roles they perform within the organization.")]
public partial class Role : AuditableEntity, IEquatable<Role>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public Role()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Role" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a Role (required).</param>
/// <param name="Name">The name of the Role, as established by the user creating the role. (required).</param>
/// <param name="Description">A description of the role as set by the user creating&#x2F;updating the role. (required).</param>
/// <param name="RolePermissions">RolePermissions.</param>
/// <param name="UserRoles">UserRoles.</param>
public Role(int Id, string Name, string Description, List<RolePermission> RolePermissions = null, List<UserRole> UserRoles = null)
{
this.Id = Id;
this.Name = Name;
this.Description = Description;
this.RolePermissions = RolePermissions;
this.UserRoles = UserRoles;
}
/// <summary>
/// A system-generated unique identifier for a Role
/// </summary>
/// <value>A system-generated unique identifier for a Role</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a Role")]
public int Id { get; set; }
/// <summary>
/// The name of the Role, as established by the user creating the role.
/// </summary>
/// <value>The name of the Role, as established by the user creating the role.</value>
[MetaDataExtension (Description = "The name of the Role, as established by the user creating the role.")]
[MaxLength(255)]
public string Name { get; set; }
/// <summary>
/// A description of the role as set by the user creating/updating the role.
/// </summary>
/// <value>A description of the role as set by the user creating/updating the role.</value>
[MetaDataExtension (Description = "A description of the role as set by the user creating/updating the role.")]
[MaxLength(255)]
public string Description { get; set; }
/// <summary>
/// The date on which a role was removed.
/// </summary>
/// <value>The date on which a role was removed.</value>
[MetaDataExtension(Description = "The date on which a role was removed")]
public DateTime? ExpiryDate { get; set; }
/// <summary>
/// Gets or Sets RolePermissions
/// </summary>
public List<RolePermission> RolePermissions { get; set; }
/// <summary>
/// Gets or Sets UserRoles
/// </summary>
public List<UserRole> UserRoles { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
return ToJson();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((Role)obj);
}
/// <summary>
/// Returns true if Role instances are equal
/// </summary>
/// <param name="other">Instance of Role to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Role other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.RolePermissions == other.RolePermissions ||
this.RolePermissions != null &&
this.RolePermissions.SequenceEqual(other.RolePermissions)
) &&
(
this.UserRoles == other.UserRoles ||
this.UserRoles != null &&
this.UserRoles.SequenceEqual(other.UserRoles)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null)
{
hash = hash * 59 + this.Name.GetHashCode();
}
if (this.Description != null)
{
hash = hash * 59 + this.Description.GetHashCode();
}
if (this.RolePermissions != null)
{
hash = hash * 59 + this.RolePermissions.GetHashCode();
}
if (this.UserRoles != null)
{
hash = hash * 59 + this.UserRoles.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Role left, Role right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Role left, Role right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
/*
* 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.Binary
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Compute;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.Messaging;
using Apache.Ignite.Core.Log;
/// <summary>
/// Marshaller implementation.
/// </summary>
internal class Marshaller
{
/** Binary configuration. */
private readonly BinaryConfiguration _cfg;
/** Type to descriptor map. */
private readonly CopyOnWriteConcurrentDictionary<Type, BinaryFullTypeDescriptor> _typeToDesc =
new CopyOnWriteConcurrentDictionary<Type, BinaryFullTypeDescriptor>();
/** Type name to descriptor map. */
private readonly CopyOnWriteConcurrentDictionary<string, BinaryFullTypeDescriptor> _typeNameToDesc =
new CopyOnWriteConcurrentDictionary<string, BinaryFullTypeDescriptor>();
/** ID to descriptor map. */
private readonly CopyOnWriteConcurrentDictionary<long, BinaryFullTypeDescriptor> _idToDesc =
new CopyOnWriteConcurrentDictionary<long, BinaryFullTypeDescriptor>();
/** Cached binary types. */
private volatile IDictionary<int, BinaryTypeHolder> _metas = new Dictionary<int, BinaryTypeHolder>();
/** */
private volatile Ignite _ignite;
/** */
private readonly ILogger _log;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="log"></param>
public Marshaller(BinaryConfiguration cfg, ILogger log = null)
{
_cfg = cfg ?? new BinaryConfiguration();
_log = log;
CompactFooter = _cfg.CompactFooter;
if (_cfg.TypeConfigurations == null)
_cfg.TypeConfigurations = new List<BinaryTypeConfiguration>();
foreach (BinaryTypeConfiguration typeCfg in _cfg.TypeConfigurations)
{
if (string.IsNullOrEmpty(typeCfg.TypeName))
throw new BinaryObjectException("Type name cannot be null or empty: " + typeCfg);
}
// Define system types. They use internal reflective stuff, so configuration doesn't affect them.
AddSystemTypes();
// 2. Define user types.
var typeResolver = new TypeResolver();
ICollection<BinaryTypeConfiguration> typeCfgs = _cfg.TypeConfigurations;
if (typeCfgs != null)
foreach (BinaryTypeConfiguration typeCfg in typeCfgs)
AddUserType(cfg, typeCfg, typeResolver);
var typeNames = _cfg.Types;
if (typeNames != null)
foreach (string typeName in typeNames)
AddUserType(cfg, new BinaryTypeConfiguration(typeName), typeResolver);
}
/// <summary>
/// Gets or sets the backing grid.
/// </summary>
public Ignite Ignite
{
get { return _ignite; }
set
{
Debug.Assert(value != null);
_ignite = value;
}
}
/// <summary>
/// Gets the compact footer flag.
/// </summary>
public bool CompactFooter { get; set; }
/// <summary>
/// Gets or sets a value indicating whether type registration is disabled.
/// This may be desirable for static system marshallers where everything is written in unregistered mode.
/// </summary>
public bool RegistrationDisabled { get; set; }
/// <summary>
/// Marshal object.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Serialized data as byte array.</returns>
public byte[] Marshal<T>(T val)
{
using (var stream = new BinaryHeapStream(128))
{
Marshal(val, stream);
return stream.GetArrayCopy();
}
}
/// <summary>
/// Marshals an object.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="stream">Output stream.</param>
private void Marshal<T>(T val, IBinaryStream stream)
{
BinaryWriter writer = StartMarshal(stream);
writer.Write(val);
FinishMarshal(writer);
}
/// <summary>
/// Start marshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>Writer.</returns>
public BinaryWriter StartMarshal(IBinaryStream stream)
{
return new BinaryWriter(this, stream);
}
/// <summary>
/// Finish marshal session.
/// </summary>
/// <param name="writer">Writer.</param>
/// <returns>Dictionary with metadata.</returns>
public void FinishMarshal(BinaryWriter writer)
{
var metas = writer.GetBinaryTypes();
var ignite = Ignite;
if (ignite != null && metas != null && metas.Count > 0)
{
ignite.BinaryProcessor.PutBinaryTypes(metas);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">Data array.</param>
/// <param name="keepBinary">Whether to keep binarizable as binary.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(byte[] data, bool keepBinary)
{
using (var stream = new BinaryHeapStream(data))
{
return Unmarshal<T>(stream, keepBinary);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="data">Data array.</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(byte[] data, BinaryMode mode = BinaryMode.Deserialize)
{
using (var stream = new BinaryHeapStream(data))
{
return Unmarshal<T>(stream, mode);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="keepBinary">Whether to keep binary objects in binary form.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, bool keepBinary)
{
return Unmarshal<T>(stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize)
{
return Unmarshal<T>(stream, mode, null);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="mode">The mode.</param>
/// <param name="builder">Builder.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode, BinaryObjectBuilder builder)
{
return new BinaryReader(this, stream, mode, builder).Deserialize<T>();
}
/// <summary>
/// Start unmarshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="keepBinary">Whether to keep binarizable as binary.</param>
/// <returns>
/// Reader.
/// </returns>
public BinaryReader StartUnmarshal(IBinaryStream stream, bool keepBinary)
{
return new BinaryReader(this, stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null);
}
/// <summary>
/// Start unmarshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="mode">The mode.</param>
/// <returns>Reader.</returns>
public BinaryReader StartUnmarshal(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize)
{
return new BinaryReader(this, stream, mode, null);
}
/// <summary>
/// Gets metadata for the given type ID.
/// </summary>
/// <param name="typeId">Type ID.</param>
/// <returns>Metadata or null.</returns>
public IBinaryType GetBinaryType(int typeId)
{
if (Ignite != null)
{
IBinaryType meta = Ignite.BinaryProcessor.GetBinaryType(typeId);
if (meta != null)
return meta;
}
return BinaryType.Empty;
}
/// <summary>
/// Puts the binary type metadata to Ignite.
/// </summary>
/// <param name="desc">Descriptor.</param>
public void PutBinaryType(IBinaryTypeDescriptor desc)
{
Debug.Assert(desc != null);
GetBinaryTypeHandler(desc); // ensure that handler exists
if (Ignite != null)
{
ICollection<BinaryType> metas = new[] {new BinaryType(desc)};
Ignite.BinaryProcessor.PutBinaryTypes(metas);
}
}
/// <summary>
/// Gets binary type handler for the given type ID.
/// </summary>
/// <param name="desc">Type descriptor.</param>
/// <returns>Binary type handler.</returns>
public IBinaryTypeHandler GetBinaryTypeHandler(IBinaryTypeDescriptor desc)
{
BinaryTypeHolder holder;
if (!_metas.TryGetValue(desc.TypeId, out holder))
{
lock (this)
{
if (!_metas.TryGetValue(desc.TypeId, out holder))
{
IDictionary<int, BinaryTypeHolder> metas0 =
new Dictionary<int, BinaryTypeHolder>(_metas);
holder = new BinaryTypeHolder(desc.TypeId, desc.TypeName, desc.AffinityKeyFieldName, desc.IsEnum);
metas0[desc.TypeId] = holder;
_metas = metas0;
}
}
}
if (holder != null)
{
ICollection<int> ids = holder.GetFieldIds();
bool newType = ids.Count == 0 && !holder.Saved();
return new BinaryTypeHashsetHandler(ids, newType);
}
return null;
}
/// <summary>
/// Callback invoked when metadata has been sent to the server and acknowledged by it.
/// </summary>
/// <param name="newMetas">Binary types.</param>
public void OnBinaryTypesSent(IEnumerable<BinaryType> newMetas)
{
foreach (var meta in newMetas)
{
var mergeInfo = new Dictionary<int, Tuple<string, BinaryField>>(meta.GetFieldsMap().Count);
foreach (var fieldMeta in meta.GetFieldsMap())
{
int fieldId = BinaryUtils.FieldId(meta.TypeId, fieldMeta.Key, null, null);
mergeInfo[fieldId] = new Tuple<string, BinaryField>(fieldMeta.Key, fieldMeta.Value);
}
_metas[meta.TypeId].Merge(mergeInfo);
}
}
/// <summary>
/// Gets descriptor for type.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>
/// Descriptor.
/// </returns>
public IBinaryTypeDescriptor GetDescriptor(Type type)
{
BinaryFullTypeDescriptor desc;
if (!_typeToDesc.TryGetValue(type, out desc) || !desc.IsRegistered)
desc = RegisterType(type, desc);
return desc;
}
/// <summary>
/// Gets descriptor for type name.
/// </summary>
/// <param name="typeName">Type name.</param>
/// <returns>Descriptor.</returns>
public IBinaryTypeDescriptor GetDescriptor(string typeName)
{
BinaryFullTypeDescriptor desc;
return _typeNameToDesc.TryGetValue(typeName, out desc)
? (IBinaryTypeDescriptor) desc
: new BinarySurrogateTypeDescriptor(_cfg, typeName);
}
/// <summary>
/// Gets descriptor for a type id.
/// </summary>
/// <param name="userType">User type flag.</param>
/// <param name="typeId">Type id.</param>
/// <param name="requiresType">
/// If set to true, resulting descriptor must have Type property populated.
/// <para />
/// When working in binary mode, we don't need Type. And there is no Type at all in some cases.
/// So we should not attempt to call BinaryProcessor right away.
/// Only when we really deserialize the value, requiresType is set to true
/// and we attempt to resolve the type by all means.
/// </param>
/// <returns>
/// Descriptor.
/// </returns>
public IBinaryTypeDescriptor GetDescriptor(bool userType, int typeId, bool requiresType = false)
{
BinaryFullTypeDescriptor desc;
var typeKey = BinaryUtils.TypeKey(userType, typeId);
if (_idToDesc.TryGetValue(typeKey, out desc) && (!requiresType || desc.Type != null))
return desc;
if (!userType)
return null;
if (requiresType)
{
// Check marshaller context for dynamically registered type.
var type = _ignite == null ? null : _ignite.BinaryProcessor.GetType(typeId);
if (type != null)
return AddUserType(type, typeId, BinaryUtils.GetTypeName(type), true, desc);
}
var meta = GetBinaryType(typeId);
if (meta != BinaryType.Empty)
{
desc = new BinaryFullTypeDescriptor(null, meta.TypeId, meta.TypeName, true, null, null, null, false,
meta.AffinityKeyFieldName, meta.IsEnum, null);
_idToDesc.GetOrAdd(typeKey, _ => desc);
return desc;
}
return new BinarySurrogateTypeDescriptor(_cfg, typeId, null);
}
/// <summary>
/// Registers the type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="desc">Existing descriptor.</param>
private BinaryFullTypeDescriptor RegisterType(Type type, BinaryFullTypeDescriptor desc)
{
Debug.Assert(type != null);
var typeName = BinaryUtils.GetTypeName(type);
var typeId = BinaryUtils.TypeId(typeName, _cfg.DefaultNameMapper, _cfg.DefaultIdMapper);
var registered = _ignite != null && _ignite.BinaryProcessor.RegisterType(typeId, type);
return AddUserType(type, typeId, typeName, registered, desc);
}
/// <summary>
/// Gets the user type descriptors.
/// </summary>
public ICollection<BinaryFullTypeDescriptor> GetUserTypeDescriptors()
{
return _typeNameToDesc.Values;
}
/// <summary>
/// Add user type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="typeId">The type id.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="registered">Registered flag.</param>
/// <param name="desc">Existing descriptor.</param>
/// <returns>Descriptor.</returns>
private BinaryFullTypeDescriptor AddUserType(Type type, int typeId, string typeName, bool registered,
BinaryFullTypeDescriptor desc)
{
Debug.Assert(type != null);
Debug.Assert(typeName != null);
var ser = GetSerializer(_cfg, null, type, typeId, null, null, _log);
desc = desc == null
? new BinaryFullTypeDescriptor(type, typeId, typeName, true, _cfg.DefaultNameMapper,
_cfg.DefaultIdMapper, ser, false, null, type.IsEnum, null, registered)
: new BinaryFullTypeDescriptor(desc, type, ser, registered);
if (RegistrationDisabled)
return desc;
var typeKey = BinaryUtils.TypeKey(true, typeId);
var desc0 = _idToDesc.GetOrAdd(typeKey, x => desc);
if (desc0.Type != null && desc0.Type.FullName != type.FullName)
ThrowConflictingTypeError(type, desc0.Type, typeId);
desc0 = _typeNameToDesc.GetOrAdd(typeName, x => desc);
if (desc0.Type != null && desc0.Type.FullName != type.FullName)
ThrowConflictingTypeError(type, desc0.Type, typeId);
_typeToDesc.Set(type, desc);
return desc;
}
/// <summary>
/// Throws the conflicting type error.
/// </summary>
private static void ThrowConflictingTypeError(object type1, object type2, int typeId)
{
throw new BinaryObjectException(string.Format("Conflicting type IDs [type1='{0}', " +
"type2='{1}', typeId={2}]", type1, type2, typeId));
}
/// <summary>
/// Add user type.
/// </summary>
/// <param name="cfg">The binary configuration.</param>
/// <param name="typeCfg">Type configuration.</param>
/// <param name="typeResolver">The type resolver.</param>
/// <exception cref="BinaryObjectException"></exception>
private void AddUserType(BinaryConfiguration cfg, BinaryTypeConfiguration typeCfg, TypeResolver typeResolver)
{
// Get converter/mapper/serializer.
IBinaryNameMapper nameMapper = typeCfg.NameMapper ?? _cfg.DefaultNameMapper;
IBinaryIdMapper idMapper = typeCfg.IdMapper ?? _cfg.DefaultIdMapper;
bool keepDeserialized = typeCfg.KeepDeserialized ?? _cfg.DefaultKeepDeserialized;
// Try resolving type.
Type type = typeResolver.ResolveType(typeCfg.TypeName);
if (type != null)
{
ValidateUserType(type);
if (typeCfg.IsEnum != type.IsEnum)
{
throw new BinaryObjectException(
string.Format(
"Invalid IsEnum flag in binary type configuration. " +
"Configuration value: IsEnum={0}, actual type: IsEnum={1}",
typeCfg.IsEnum, type.IsEnum));
}
// Type is found.
var typeName = BinaryUtils.GetTypeName(type);
int typeId = BinaryUtils.TypeId(typeName, nameMapper, idMapper);
var affKeyFld = typeCfg.AffinityKeyFieldName ?? GetAffinityKeyFieldNameFromAttribute(type);
var serializer = GetSerializer(cfg, typeCfg, type, typeId, nameMapper, idMapper, _log);
AddType(type, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, serializer,
affKeyFld, type.IsEnum, typeCfg.EqualityComparer);
}
else
{
// Type is not found.
string typeName = BinaryUtils.SimpleTypeName(typeCfg.TypeName);
int typeId = BinaryUtils.TypeId(typeName, nameMapper, idMapper);
AddType(null, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, null,
typeCfg.AffinityKeyFieldName, typeCfg.IsEnum, typeCfg.EqualityComparer);
}
}
/// <summary>
/// Gets the serializer.
/// </summary>
private static IBinarySerializerInternal GetSerializer(BinaryConfiguration cfg,
BinaryTypeConfiguration typeCfg, Type type, int typeId, IBinaryNameMapper nameMapper,
IBinaryIdMapper idMapper, ILogger log)
{
var serializer = (typeCfg != null ? typeCfg.Serializer : null) ??
(cfg != null ? cfg.DefaultSerializer : null);
if (serializer == null)
{
if (type.GetInterfaces().Contains(typeof(IBinarizable)))
return BinarizableSerializer.Instance;
if (type.GetInterfaces().Contains(typeof(ISerializable)))
{
LogSerializableWarning(type, log);
return new SerializableSerializer(type);
}
serializer = new BinaryReflectiveSerializer();
}
var refSerializer = serializer as BinaryReflectiveSerializer;
return refSerializer != null
? refSerializer.Register(type, typeId, nameMapper, idMapper)
: new UserSerializerProxy(serializer);
}
/// <summary>
/// Gets the affinity key field name from attribute.
/// </summary>
private static string GetAffinityKeyFieldNameFromAttribute(Type type)
{
var res = type.GetMembers()
.Where(x => x.GetCustomAttributes(false).OfType<AffinityKeyMappedAttribute>().Any())
.Select(x => x.Name).ToArray();
if (res.Length > 1)
{
throw new BinaryObjectException(string.Format("Multiple '{0}' attributes found on type '{1}'. " +
"There can be only one affinity field.", typeof (AffinityKeyMappedAttribute).Name, type));
}
return res.SingleOrDefault();
}
/// <summary>
/// Add type.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="typeId">Type ID.</param>
/// <param name="typeName">Type name.</param>
/// <param name="userType">User type flag.</param>
/// <param name="keepDeserialized">Whether to cache deserialized value in IBinaryObject</param>
/// <param name="nameMapper">Name mapper.</param>
/// <param name="idMapper">ID mapper.</param>
/// <param name="serializer">Serializer.</param>
/// <param name="affKeyFieldName">Affinity key field name.</param>
/// <param name="isEnum">Enum flag.</param>
/// <param name="comparer">Comparer.</param>
private void AddType(Type type, int typeId, string typeName, bool userType,
bool keepDeserialized, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper,
IBinarySerializerInternal serializer, string affKeyFieldName, bool isEnum,
IEqualityComparer<IBinaryObject> comparer)
{
long typeKey = BinaryUtils.TypeKey(userType, typeId);
BinaryFullTypeDescriptor conflictingType;
if (_idToDesc.TryGetValue(typeKey, out conflictingType))
{
var type1 = conflictingType.Type != null
? conflictingType.Type.AssemblyQualifiedName
: conflictingType.TypeName;
var type2 = type != null ? type.AssemblyQualifiedName : typeName;
ThrowConflictingTypeError(type1, type2, typeId);
}
if (userType && _typeNameToDesc.ContainsKey(typeName))
throw new BinaryObjectException("Conflicting type name: " + typeName);
var descriptor = new BinaryFullTypeDescriptor(type, typeId, typeName, userType, nameMapper, idMapper,
serializer, keepDeserialized, affKeyFieldName, isEnum, comparer);
if (type != null)
_typeToDesc.GetOrAdd(type, x => descriptor);
if (userType)
_typeNameToDesc.GetOrAdd(typeName, x => descriptor);
_idToDesc.GetOrAdd(typeKey, _ => descriptor);
}
/// <summary>
/// Adds a predefined system type.
/// </summary>
private void AddSystemType<T>(int typeId, Func<BinaryReader, T> ctor, string affKeyFldName = null,
IBinarySerializerInternal serializer = null)
where T : IBinaryWriteAware
{
var type = typeof(T);
serializer = serializer ?? new BinarySystemTypeSerializer<T>(ctor);
if (typeId == 0)
typeId = BinaryUtils.TypeId(type.Name, null, null);
AddType(type, typeId, BinaryUtils.GetTypeName(type), false, false, null, null, serializer, affKeyFldName,
false, null);
}
/// <summary>
/// Adds predefined system types.
/// </summary>
private void AddSystemTypes()
{
AddSystemType(BinaryUtils.TypeNativeJobHolder, r => new ComputeJobHolder(r));
AddSystemType(BinaryUtils.TypeComputeJobWrapper, r => new ComputeJobWrapper(r));
AddSystemType(BinaryUtils.TypeIgniteProxy, r => new IgniteProxy());
AddSystemType(BinaryUtils.TypeComputeOutFuncJob, r => new ComputeOutFuncJob(r));
AddSystemType(BinaryUtils.TypeComputeOutFuncWrapper, r => new ComputeOutFuncWrapper(r));
AddSystemType(BinaryUtils.TypeComputeFuncWrapper, r => new ComputeFuncWrapper(r));
AddSystemType(BinaryUtils.TypeComputeFuncJob, r => new ComputeFuncJob(r));
AddSystemType(BinaryUtils.TypeComputeActionJob, r => new ComputeActionJob(r));
AddSystemType(BinaryUtils.TypeContinuousQueryRemoteFilterHolder, r => new ContinuousQueryFilterHolder(r));
AddSystemType(BinaryUtils.TypeCacheEntryProcessorHolder, r => new CacheEntryProcessorHolder(r));
AddSystemType(BinaryUtils.TypeCacheEntryPredicateHolder, r => new CacheEntryFilterHolder(r));
AddSystemType(BinaryUtils.TypeMessageListenerHolder, r => new MessageListenerHolder(r));
AddSystemType(BinaryUtils.TypeStreamReceiverHolder, r => new StreamReceiverHolder(r));
AddSystemType(0, r => new AffinityKey(r), "affKey");
AddSystemType(BinaryUtils.TypePlatformJavaObjectFactoryProxy, r => new PlatformJavaObjectFactoryProxy());
AddSystemType(0, r => new ObjectInfoHolder(r));
AddSystemType(BinaryUtils.TypeIgniteUuid, r => new IgniteGuid(r));
}
/// <summary>
/// Logs the warning about ISerializable pitfalls.
/// </summary>
private static void LogSerializableWarning(Type type, ILogger log)
{
if (log == null)
return;
log.GetLogger(typeof(Marshaller).Name)
.Warn("Type '{0}' implements '{1}'. It will be written in Ignite binary format, however, " +
"the following limitations apply: " +
"DateTime fields would not work in SQL; " +
"sbyte, ushort, uint, ulong fields would not work in DML.", type, typeof(ISerializable));
}
/// <summary>
/// Validates binary type.
/// </summary>
// ReSharper disable once UnusedParameter.Local
private static void ValidateUserType(Type type)
{
Debug.Assert(type != null);
if (type.IsGenericTypeDefinition)
{
throw new BinaryObjectException(
"Open generic types (Type.IsGenericTypeDefinition == true) are not allowed " +
"in BinaryConfiguration: " + type.AssemblyQualifiedName);
}
if (type.IsAbstract)
{
throw new BinaryObjectException(
"Abstract types and interfaces are not allowed in BinaryConfiguration: " +
type.AssemblyQualifiedName);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Http
{
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyCreate")]
public static extern SafeCurlHandle EasyCreate();
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyDestroy")]
private static extern void EasyDestroy(IntPtr handle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionString", CharSet = CharSet.Ansi)]
public static extern CURLcode EasySetOptionString(SafeCurlHandle curl, CURLoption option, string value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionLong")]
public static extern CURLcode EasySetOptionLong(SafeCurlHandle curl, CURLoption option, long value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")]
public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, IntPtr value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")]
public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, SafeHandle value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetErrorString")]
public static extern IntPtr EasyGetErrorString(int code);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoPointer")]
public static extern CURLcode EasyGetInfoPointer(IntPtr handle, CURLINFO info, out IntPtr value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoLong")]
public static extern CURLcode EasyGetInfoLong(SafeCurlHandle handle, CURLINFO info, out long value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyPerform")]
public static extern CURLcode EasyPerform(SafeCurlHandle curl);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyUnpause")]
public static extern CURLcode EasyUnpause(SafeCurlHandle easy);
public delegate CurlSeekResult SeekCallback(IntPtr userPointer, long offset, int origin);
public delegate ulong ReadWriteCallback(IntPtr buffer, ulong bufferSize, ulong nitems, IntPtr userPointer);
public delegate CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSeekCallback")]
public static extern void RegisterSeekCallback(
SafeCurlHandle curl,
SeekCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterReadWriteCallback")]
public static extern void RegisterReadWriteCallback(
SafeCurlHandle curl,
ReadWriteFunction functionType,
ReadWriteCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSslCtxCallback")]
public static extern CURLcode RegisterSslCtxCallback(
SafeCurlHandle curl,
SslCtxCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_FreeCallbackHandle")]
private static extern void FreeCallbackHandle(IntPtr handle);
// Curl options are of the format <type base> + <n>
private const int CurlOptionLongBase = 0;
private const int CurlOptionObjectPointBase = 10000;
// Enum for constants defined for the enum CURLoption in curl.h
internal enum CURLoption
{
CURLOPT_INFILESIZE = CurlOptionLongBase + 14,
CURLOPT_VERBOSE = CurlOptionLongBase + 41,
CURLOPT_NOBODY = CurlOptionLongBase + 44,
CURLOPT_UPLOAD = CurlOptionLongBase + 46,
CURLOPT_POST = CurlOptionLongBase + 47,
CURLOPT_FOLLOWLOCATION = CurlOptionLongBase + 52,
CURLOPT_PROXYPORT = CurlOptionLongBase + 59,
CURLOPT_POSTFIELDSIZE = CurlOptionLongBase + 60,
CURLOPT_MAXREDIRS = CurlOptionLongBase + 68,
CURLOPT_HTTP_VERSION = CurlOptionLongBase + 84,
CURLOPT_NOSIGNAL = CurlOptionLongBase + 99,
CURLOPT_PROXYTYPE = CurlOptionLongBase + 101,
CURLOPT_HTTPAUTH = CurlOptionLongBase + 107,
CURLOPT_PROTOCOLS = CurlOptionLongBase + 181,
CURLOPT_REDIR_PROTOCOLS = CurlOptionLongBase + 182,
CURLOPT_URL = CurlOptionObjectPointBase + 2,
CURLOPT_PROXY = CurlOptionObjectPointBase + 4,
CURLOPT_PROXYUSERPWD = CurlOptionObjectPointBase + 6,
CURLOPT_COOKIE = CurlOptionObjectPointBase + 22,
CURLOPT_HTTPHEADER = CurlOptionObjectPointBase + 23,
CURLOPT_CUSTOMREQUEST = CurlOptionObjectPointBase + 36,
CURLOPT_ACCEPT_ENCODING = CurlOptionObjectPointBase + 102,
CURLOPT_PRIVATE = CurlOptionObjectPointBase + 103,
CURLOPT_COPYPOSTFIELDS = CurlOptionObjectPointBase + 165,
CURLOPT_USERNAME = CurlOptionObjectPointBase + 173,
CURLOPT_PASSWORD = CurlOptionObjectPointBase + 174,
}
internal enum ReadWriteFunction
{
Write = 0,
Read = 1,
Header = 2,
}
// Curl info are of the format <type base> + <n>
private const int CurlInfoStringBase = 0x100000;
private const int CurlInfoLongBase = 0x200000;
// Enum for constants defined for CURL_HTTP_VERSION
internal enum CurlHttpVersion
{
CURL_HTTP_VERSION_NONE = 0,
CURL_HTTP_VERSION_1_0 = 1,
CURL_HTTP_VERSION_1_1 = 2,
CURL_HTTP_VERSION_2_0 = 3,
};
// Enum for constants defined for the enum CURLINFO in curl.h
internal enum CURLINFO
{
CURLINFO_PRIVATE = CurlInfoStringBase + 21,
CURLINFO_HTTPAUTH_AVAIL = CurlInfoLongBase + 23,
}
// AUTH related constants
[Flags]
internal enum CURLAUTH
{
None = 0,
Basic = 1 << 0,
Digest = 1 << 1,
Negotiate = 1 << 2,
}
// Enum for constants defined for the enum curl_proxytype in curl.h
internal enum curl_proxytype
{
CURLPROXY_HTTP = 0,
}
[Flags]
internal enum CurlProtocols
{
CURLPROTO_HTTP = (1 << 0),
CURLPROTO_HTTPS = (1 << 1),
}
// Enum for constants defined for the results of CURL_SEEKFUNCTION
internal enum CurlSeekResult : int
{
CURL_SEEKFUNC_OK = 0,
CURL_SEEKFUNC_FAIL = 1,
CURL_SEEKFUNC_CANTSEEK = 2,
}
// constants defined for the results of a CURL_READ or CURL_WRITE function
internal const ulong CURL_READFUNC_ABORT = 0x10000000;
internal const ulong CURL_READFUNC_PAUSE = 0x10000001;
internal const ulong CURL_WRITEFUNC_PAUSE = 0x10000001;
internal sealed class SafeCurlHandle : SafeHandle
{
public SafeCurlHandle() : base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
EasyDestroy(handle);
SetHandle(IntPtr.Zero);
return true;
}
}
internal sealed class SafeCallbackHandle : SafeHandle
{
public SafeCallbackHandle()
: base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
FreeCallbackHandle(handle);
SetHandle(IntPtr.Zero);
return true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Internal;
using Orleans.Metadata;
using Orleans.Runtime.Utilities;
namespace Orleans.Runtime.Metadata
{
internal class ClusterManifestProvider : IClusterManifestProvider, IAsyncDisposable, IDisposable, ILifecycleParticipant<ISiloLifecycle>
{
private readonly SiloAddress _localSiloAddress;
private readonly ILogger<ClusterManifestProvider> _logger;
private readonly IServiceProvider _services;
private readonly IClusterMembershipService _clusterMembershipService;
private readonly IFatalErrorHandler _fatalErrorHandler;
private readonly CancellationTokenSource _cancellation = new CancellationTokenSource();
private readonly AsyncEnumerable<ClusterManifest> _updates;
private ClusterManifest _current;
private Task _runTask;
public ClusterManifestProvider(
ILocalSiloDetails localSiloDetails,
SiloManifestProvider siloManifestProvider,
ClusterMembershipService clusterMembershipService,
IFatalErrorHandler fatalErrorHandler,
ILogger<ClusterManifestProvider> logger,
IServiceProvider services)
{
_localSiloAddress = localSiloDetails.SiloAddress;
_logger = logger;
_services = services;
_clusterMembershipService = clusterMembershipService;
_fatalErrorHandler = fatalErrorHandler;
this.LocalGrainManifest = siloManifestProvider.SiloManifest;
_current = new ClusterManifest(
MajorMinorVersion.Zero,
ImmutableDictionary.CreateRange(new[] { new KeyValuePair<SiloAddress, GrainManifest>(localSiloDetails.SiloAddress, this.LocalGrainManifest) }),
ImmutableArray.Create(this.LocalGrainManifest));
_updates = new AsyncEnumerable<ClusterManifest>(
(previous, proposed) => previous.Version <= MajorMinorVersion.Zero || proposed.Version > previous.Version,
_current)
{
OnPublished = update => Interlocked.Exchange(ref _current, update)
};
}
public ClusterManifest Current => _current;
public IAsyncEnumerable<ClusterManifest> Updates => _updates;
public GrainManifest LocalGrainManifest { get; }
private async Task ProcessMembershipUpdates()
{
try
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Starting to process membership updates");
}
var cancellation = _cancellation.Token;
await foreach (var _ in _clusterMembershipService.MembershipUpdates.WithCancellation(cancellation))
{
while (true)
{
var membershipSnapshot = _clusterMembershipService.CurrentSnapshot;
var success = await this.UpdateManifest(membershipSnapshot);
if (success || cancellation.IsCancellationRequested)
{
break;
}
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
}
catch (Exception exception) when (_fatalErrorHandler.IsUnexpected(exception))
{
_fatalErrorHandler.OnFatalException(this, nameof(ProcessMembershipUpdates), exception);
}
finally
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Stopped processing membership updates");
}
}
}
private async Task<bool> UpdateManifest(ClusterMembershipSnapshot clusterMembership)
{
var existingManifest = _current;
var builder = existingManifest.Silos.ToBuilder();
var modified = false;
// First, remove defunct entries.
foreach (var entry in existingManifest.Silos)
{
var address = entry.Key;
var status = clusterMembership.GetSiloStatus(address);
if (address.Equals(_localSiloAddress))
{
// The local silo is always present in the manifest.
continue;
}
if (status == SiloStatus.None || status == SiloStatus.Dead)
{
builder.Remove(address);
modified = true;
}
}
// Next, fill missing entries.
var tasks = new List<Task<(SiloAddress Key, GrainManifest Value, Exception Exception)>>();
foreach (var entry in clusterMembership.Members)
{
var member = entry.Value;
if (member.SiloAddress.Equals(_localSiloAddress))
{
// The local silo is always present in the manifest.
continue;
}
if (existingManifest.Silos.ContainsKey(member.SiloAddress))
{
// Manifest has already been retrieved for the cluster member.
continue;
}
if (member.Status != SiloStatus.Active)
{
// If the member is not yet active, it may not be ready to process requests.
continue;
}
tasks.Add(GetManifest(member.SiloAddress));
async Task<(SiloAddress, GrainManifest, Exception)> GetManifest(SiloAddress siloAddress)
{
try
{
// Get the manifest from the remote silo.
var grainFactory = _services.GetRequiredService<IInternalGrainFactory>();
var remoteManifestProvider = grainFactory.GetSystemTarget<ISiloManifestSystemTarget>(Constants.ManifestProviderType, member.SiloAddress);
var manifest = await remoteManifestProvider.GetSiloManifest();
return (siloAddress, manifest, null);
}
catch (Exception exception)
{
return (siloAddress, null, exception);
}
}
}
var fetchSuccess = true;
await Task.WhenAll(tasks);
foreach (var task in tasks)
{
var result = await task;
if (result.Exception is Exception exception)
{
fetchSuccess = false;
_logger.LogWarning(exception, "Error retrieving silo manifest for silo {SiloAddress}", result.Key);
}
else
{
modified = true;
builder[result.Key] = result.Value;
}
}
// Regardless of success or failure, update the manifest if it has been modified.
var version = new MajorMinorVersion(clusterMembership.Version.Value, existingManifest.Version.Minor + 1);
if (modified)
{
return _updates.TryPublish(new ClusterManifest(version, builder.ToImmutable(), builder.Values.ToImmutableArray())) && fetchSuccess;
}
return fetchSuccess;
}
private Task StartAsync(CancellationToken _)
{
_runTask = Task.Run(ProcessMembershipUpdates);
return Task.CompletedTask;
}
private Task Initialize(CancellationToken _)
{
var catalog = _services.GetRequiredService<Catalog>();
catalog.RegisterSystemTarget(ActivatorUtilities.CreateInstance<ClusterManifestSystemTarget>(_services));
return Task.CompletedTask;
}
private async Task StopAsync(CancellationToken cancellationToken)
{
_cancellation.Cancel();
if (_runTask is Task task)
{
await task;
}
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(
nameof(ClusterManifestProvider),
ServiceLifecycleStage.RuntimeServices,
Initialize,
_ => Task.CompletedTask);
lifecycle.Subscribe(
nameof(ClusterManifestProvider),
ServiceLifecycleStage.RuntimeGrainServices,
StartAsync,
StopAsync);
}
public async ValueTask DisposeAsync()
{
await this.StopAsync(CancellationToken.None);
}
public void Dispose()
{
_cancellation.Cancel();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// EnvironmentMapEffect.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace Microsoft.Xna.Framework.Graphics
{
/// <summary>
/// Built-in effect that supports environment mapping.
/// </summary>
public class EnvironmentMapEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog
{
#region Effect Parameters
EffectParameter textureParam;
EffectParameter environmentMapParam;
EffectParameter environmentMapAmountParam;
EffectParameter environmentMapSpecularParam;
EffectParameter fresnelFactorParam;
EffectParameter diffuseColorParam;
EffectParameter emissiveColorParam;
EffectParameter eyePositionParam;
EffectParameter fogColorParam;
EffectParameter fogVectorParam;
EffectParameter worldParam;
EffectParameter worldInverseTransposeParam;
EffectParameter worldViewProjParam;
int _shaderIndex = -1;
#endregion
#region Fields
bool oneLight;
bool fogEnabled;
bool fresnelEnabled;
bool specularEnabled;
Matrix world = Matrix.Identity;
Matrix view = Matrix.Identity;
Matrix projection = Matrix.Identity;
Matrix worldView;
Vector3 diffuseColor = Vector3.One;
Vector3 emissiveColor = Vector3.Zero;
Vector3 ambientLightColor = Vector3.Zero;
float alpha = 1;
DirectionalLight light0;
DirectionalLight light1;
DirectionalLight light2;
float fogStart = 0;
float fogEnd = 1;
EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All;
static readonly byte[] Bytecode = LoadEffectResource(
#if DIRECTX
"Microsoft.Xna.Framework.Graphics.Effect.Resources.EnvironmentMapEffect.dx11.mgfxo"
#else
"Microsoft.Xna.Framework.Graphics.Effect.Resources.EnvironmentMapEffect.ogl.mgfxo"
#endif
);
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the world matrix.
/// </summary>
public Matrix World
{
get { return world; }
set
{
world = value;
dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the view matrix.
/// </summary>
public Matrix View
{
get { return view; }
set
{
view = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the projection matrix.
/// </summary>
public Matrix Projection
{
get { return projection; }
set
{
projection = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj;
}
}
/// <summary>
/// Gets or sets the material diffuse color (range 0 to 1).
/// </summary>
public Vector3 DiffuseColor
{
get { return diffuseColor; }
set
{
diffuseColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material emissive color (range 0 to 1).
/// </summary>
public Vector3 EmissiveColor
{
get { return emissiveColor; }
set
{
emissiveColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material alpha.
/// </summary>
public float Alpha
{
get { return alpha; }
set
{
alpha = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the ambient light color (range 0 to 1).
/// </summary>
public Vector3 AmbientLightColor
{
get { return ambientLightColor; }
set
{
ambientLightColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets the first directional light.
/// </summary>
public DirectionalLight DirectionalLight0 { get { return light0; } }
/// <summary>
/// Gets the second directional light.
/// </summary>
public DirectionalLight DirectionalLight1 { get { return light1; } }
/// <summary>
/// Gets the third directional light.
/// </summary>
public DirectionalLight DirectionalLight2 { get { return light2; } }
/// <summary>
/// Gets or sets the fog enable flag.
/// </summary>
public bool FogEnabled
{
get { return fogEnabled; }
set
{
if (fogEnabled != value)
{
fogEnabled = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable;
}
}
}
/// <summary>
/// Gets or sets the fog start distance.
/// </summary>
public float FogStart
{
get { return fogStart; }
set
{
fogStart = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog end distance.
/// </summary>
public float FogEnd
{
get { return fogEnd; }
set
{
fogEnd = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog color.
/// </summary>
public Vector3 FogColor
{
get { return fogColorParam.GetValueVector3(); }
set { fogColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current texture.
/// </summary>
public Texture2D Texture
{
get { return textureParam.GetValueTexture2D(); }
set { textureParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current environment map texture.
/// </summary>
public TextureCube EnvironmentMap
{
get { return environmentMapParam.GetValueTextureCube(); }
set { environmentMapParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the amount of the environment map RGB that will be blended over
/// the base texture. Range 0 to 1, default 1. If set to zero, the RGB channels
/// of the environment map will completely ignored (but the environment map alpha
/// may still be visible if EnvironmentMapSpecular is greater than zero).
/// </summary>
public float EnvironmentMapAmount
{
get { return environmentMapAmountParam.GetValueSingle(); }
set { environmentMapAmountParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the amount of the environment map alpha channel that will
/// be added to the base texture. Range 0 to 1, default 0. This can be used
/// to implement cheap specular lighting, by encoding one or more specular
/// highlight patterns into the environment map alpha channel, then setting
/// EnvironmentMapSpecular to the desired specular light color.
/// </summary>
public Vector3 EnvironmentMapSpecular
{
get { return environmentMapSpecularParam.GetValueVector3(); }
set
{
environmentMapSpecularParam.SetValue(value);
bool enabled = (value != Vector3.Zero);
if (specularEnabled != enabled)
{
specularEnabled = enabled;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// Gets or sets the Fresnel factor used for the environment map blending.
/// Higher values make the environment map only visible around the silhouette
/// edges of the object, while lower values make it visible everywhere.
/// Setting this property to 0 disables Fresnel entirely, making the
/// environment map equally visible regardless of view angle. The default is
/// 1. Fresnel only affects the environment map RGB (the intensity of which is
/// controlled by EnvironmentMapAmount). The alpha contribution (controlled by
/// EnvironmentMapSpecular) is not affected by the Fresnel setting.
/// </summary>
public float FresnelFactor
{
get { return fresnelFactorParam.GetValueSingle(); }
set
{
fresnelFactorParam.SetValue(value);
bool enabled = (value != 0);
if (fresnelEnabled != enabled)
{
fresnelEnabled = enabled;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// This effect requires lighting, so we explicitly implement
/// IEffectLights.LightingEnabled, and do not allow turning it off.
/// </summary>
bool IEffectLights.LightingEnabled
{
get { return true; }
set { if (!value) throw new NotSupportedException("EnvironmentMapEffect does not support setting LightingEnabled to false."); }
}
#endregion
#region Methods
/// <summary>
/// Creates a new EnvironmentMapEffect with default parameter settings.
/// </summary>
public EnvironmentMapEffect(GraphicsDevice device)
: base(device, Bytecode)
{
CacheEffectParameters(null);
DirectionalLight0.Enabled = true;
EnvironmentMapAmount = 1;
EnvironmentMapSpecular = Vector3.Zero;
FresnelFactor = 1;
}
/// <summary>
/// Creates a new EnvironmentMapEffect by cloning parameter settings from an existing instance.
/// </summary>
protected EnvironmentMapEffect(EnvironmentMapEffect cloneSource)
: base(cloneSource)
{
CacheEffectParameters(cloneSource);
fogEnabled = cloneSource.fogEnabled;
fresnelEnabled = cloneSource.fresnelEnabled;
specularEnabled = cloneSource.specularEnabled;
world = cloneSource.world;
view = cloneSource.view;
projection = cloneSource.projection;
diffuseColor = cloneSource.diffuseColor;
emissiveColor = cloneSource.emissiveColor;
ambientLightColor = cloneSource.ambientLightColor;
alpha = cloneSource.alpha;
fogStart = cloneSource.fogStart;
fogEnd = cloneSource.fogEnd;
}
/// <summary>
/// Creates a clone of the current EnvironmentMapEffect instance.
/// </summary>
public override Effect Clone()
{
return new EnvironmentMapEffect(this);
}
/// <summary>
/// Sets up the standard key/fill/back lighting rig.
/// </summary>
public void EnableDefaultLighting()
{
AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2);
}
/// <summary>
/// Looks up shortcut references to our effect parameters.
/// </summary>
void CacheEffectParameters(EnvironmentMapEffect cloneSource)
{
textureParam = Parameters["Texture"];
environmentMapParam = Parameters["EnvironmentMap"];
environmentMapAmountParam = Parameters["EnvironmentMapAmount"];
environmentMapSpecularParam = Parameters["EnvironmentMapSpecular"];
fresnelFactorParam = Parameters["FresnelFactor"];
diffuseColorParam = Parameters["DiffuseColor"];
emissiveColorParam = Parameters["EmissiveColor"];
eyePositionParam = Parameters["EyePosition"];
fogColorParam = Parameters["FogColor"];
fogVectorParam = Parameters["FogVector"];
worldParam = Parameters["World"];
worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
worldViewProjParam = Parameters["WorldViewProj"];
light0 = new DirectionalLight(Parameters["DirLight0Direction"],
Parameters["DirLight0DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light0 : null);
light1 = new DirectionalLight(Parameters["DirLight1Direction"],
Parameters["DirLight1DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light1 : null);
light2 = new DirectionalLight(Parameters["DirLight2Direction"],
Parameters["DirLight2DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light2 : null);
}
/// <summary>
/// Lazily computes derived parameter values immediately before applying the effect.
/// </summary>
protected internal override bool OnApply()
{
// Recompute the world+view+projection matrix or fog vector?
dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam);
// Recompute the world inverse transpose and eye position?
dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam);
// Recompute the diffuse/emissive/alpha material color parameters?
if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0)
{
EffectHelpers.SetMaterialColor(true, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam);
dirtyFlags &= ~EffectDirtyFlags.MaterialColor;
}
// Check if we can use the only-bother-with-the-first-light shader optimization.
bool newOneLight = !light1.Enabled && !light2.Enabled;
if (oneLight != newOneLight)
{
oneLight = newOneLight;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
// Recompute the shader index?
if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0)
{
int shaderIndex = 0;
if (!fogEnabled)
shaderIndex += 1;
if (fresnelEnabled)
shaderIndex += 2;
if (specularEnabled)
shaderIndex += 4;
if (oneLight)
shaderIndex += 8;
dirtyFlags &= ~EffectDirtyFlags.ShaderIndex;
if (_shaderIndex != shaderIndex)
{
_shaderIndex = shaderIndex;
CurrentTechnique = Techniques[_shaderIndex];
return true;
}
}
return false;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class TernaryNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableBoolTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
bool?[] array2 = new bool?[] { null, true, false };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableBool(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableByteTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
byte?[] array2 = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableByte(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableCharTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
char?[] array2 = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableChar(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableDecimalTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
decimal?[] array2 = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableDecimal(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableDoubleTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
double?[] array2 = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableDouble(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableEnumTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
E?[] array2 = new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableEnum(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableEnumLongTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
El?[] array2 = new El?[] { null, (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableEnumLong(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableFloatTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
float?[] array2 = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableFloat(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableIntTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
int?[] array2 = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableInt(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableLongTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
long?[] array2 = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableLong(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableStructTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
S?[] array2 = new S?[] { null, default(S), new S() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStruct(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableSByteTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
sbyte?[] array2 = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableSByte(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableStructWithStringTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Sc?[] array2 = new Sc?[] { null, default(Sc), new Sc(), new Sc(null) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStructWithString(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableStructWithStringAndFieldTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Scs?[] array2 = new Scs?[] { null, default(Scs), new Scs(), new Scs(null, new S()) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStructWithStringAndField(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableShortTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
short?[] array2 = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableShort(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableStructWithTwoValuesTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Sp?[] array2 = new Sp?[] { null, default(Sp), new Sp(), new Sp(5, 5.0) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStructWithTwoValues(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableStructWithValueTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Ss?[] array2 = new Ss?[] { null, default(Ss), new Ss(), new Ss(new S()) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStructWithValue(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableUIntTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
uint?[] array2 = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableUInt(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableULongTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
ulong?[] array2 = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableULong(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableUShortTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
ushort?[] array2 = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableUShort(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableGenericWithStructRestrictionWithEnumTest(bool useInterpreter)
{
CheckTernaryNullableGenericWithStructRestrictionHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableGenericWithStructRestrictionWithStructTest(bool useInterpreter)
{
CheckTernaryNullableGenericWithStructRestrictionHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryNullableGenericWithStructRestrictionWithStructWithStringAndFieldTest(bool useInterpreter)
{
CheckTernaryNullableGenericWithStructRestrictionHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
private static void CheckTernaryNullableGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct
{
bool[] array1 = new bool[] { false, true };
Ts?[] array2 = new Ts?[] { default(Ts), new Ts() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableGenericWithStructRestriction<Ts>(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableBool(bool condition, bool? a, bool? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?))),
Enumerable.Empty<ParameterExpression>());
Func<bool?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableByte(bool condition, byte? a, byte? b, bool useInterpreter)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?))),
Enumerable.Empty<ParameterExpression>());
Func<byte?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableChar(bool condition, char? a, char? b, bool useInterpreter)
{
Expression<Func<char?>> e =
Expression.Lambda<Func<char?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?))),
Enumerable.Empty<ParameterExpression>());
Func<char?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableDecimal(bool condition, decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableDouble(bool condition, double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableEnum(bool condition, E? a, E? b, bool useInterpreter)
{
Expression<Func<E?>> e =
Expression.Lambda<Func<E?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(E?)),
Expression.Constant(b, typeof(E?))),
Enumerable.Empty<ParameterExpression>());
Func<E?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableEnumLong(bool condition, El? a, El? b, bool useInterpreter)
{
Expression<Func<El?>> e =
Expression.Lambda<Func<El?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(El?)),
Expression.Constant(b, typeof(El?))),
Enumerable.Empty<ParameterExpression>());
Func<El?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableFloat(bool condition, float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableInt(bool condition, int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableLong(bool condition, long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableStruct(bool condition, S? a, S? b, bool useInterpreter)
{
Expression<Func<S?>> e =
Expression.Lambda<Func<S?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(S?)),
Expression.Constant(b, typeof(S?))),
Enumerable.Empty<ParameterExpression>());
Func<S?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableSByte(bool condition, sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?))),
Enumerable.Empty<ParameterExpression>());
Func<sbyte?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableStructWithString(bool condition, Sc? a, Sc? b, bool useInterpreter)
{
Expression<Func<Sc?>> e =
Expression.Lambda<Func<Sc?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Sc?)),
Expression.Constant(b, typeof(Sc?))),
Enumerable.Empty<ParameterExpression>());
Func<Sc?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableStructWithStringAndField(bool condition, Scs? a, Scs? b, bool useInterpreter)
{
Expression<Func<Scs?>> e =
Expression.Lambda<Func<Scs?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Scs?)),
Expression.Constant(b, typeof(Scs?))),
Enumerable.Empty<ParameterExpression>());
Func<Scs?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableShort(bool condition, short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableStructWithTwoValues(bool condition, Sp? a, Sp? b, bool useInterpreter)
{
Expression<Func<Sp?>> e =
Expression.Lambda<Func<Sp?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Sp?)),
Expression.Constant(b, typeof(Sp?))),
Enumerable.Empty<ParameterExpression>());
Func<Sp?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableStructWithValue(bool condition, Ss? a, Ss? b, bool useInterpreter)
{
Expression<Func<Ss?>> e =
Expression.Lambda<Func<Ss?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Ss?)),
Expression.Constant(b, typeof(Ss?))),
Enumerable.Empty<ParameterExpression>());
Func<Ss?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableUInt(bool condition, uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableULong(bool condition, ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableUShort(bool condition, ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyNullableGenericWithStructRestriction<Ts>(bool condition, Ts? a, Ts? b, bool useInterpreter) where Ts : struct
{
Expression<Func<Ts?>> e =
Expression.Lambda<Func<Ts?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Ts?)),
Expression.Constant(b, typeof(Ts?))),
Enumerable.Empty<ParameterExpression>());
Func<Ts?> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
#endregion
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Menu {public class Menu : MonoBehaviour{
public static int frame;
void Update () { Update(Time.deltaTime, this);
frame++; }
public bool JustEntered = true;
public void Start()
{
UnityMenu = new UnityMenu();
StartButton = new ButtonGUI("Canvas/Play");
PreviousMButton = (new Nothing<ButtonGUI>());
PlusButton = (new Nothing<ButtonGUI>());
NextMButton = (new Nothing<ButtonGUI>());
LessButton = (new Nothing<ButtonGUI>());
BackButton = new ButtonGUI("Canvas/Back");
}
public System.Int32 AmountOfPlayers{ get { return UnityMenu.AmountOfPlayers; }
set{UnityMenu.AmountOfPlayers = value; }
}
public ButtonGUI __BackButton;
public ButtonGUI BackButton{ get { return __BackButton; }
set{ __BackButton = value;
if(!value.JustEntered) __BackButton = value;
else{ value.JustEntered = false;
}
}
}
public System.Int32 CurrentScreenNumber{ get { return UnityMenu.CurrentScreenNumber; }
set{UnityMenu.CurrentScreenNumber = value; }
}
public Option<ButtonGUI> __LessButton;
public Option<ButtonGUI> LessButton{ get { return __LessButton; }
set{ __LessButton = value;
if(value.IsSome){if(!value.Value.JustEntered) __LessButton = value;
else{ value.Value.JustEntered = false;
}
} }
}
public System.String MapName{ get { return UnityMenu.MapName; }
set{UnityMenu.MapName = value; }
}
public System.Int32 MapSelectNumber{ get { return UnityMenu.MapSelectNumber; }
set{UnityMenu.MapSelectNumber = value; }
}
public UnityEngine.Texture MapSelecter{ get { return UnityMenu.MapSelecter; }
set{UnityMenu.MapSelecter = value; }
}
public Option<ButtonGUI> __NextMButton;
public Option<ButtonGUI> NextMButton{ get { return __NextMButton; }
set{ __NextMButton = value;
if(value.IsSome){if(!value.Value.JustEntered) __NextMButton = value;
else{ value.Value.JustEntered = false;
}
} }
}
public System.String PlayerAmount{ get { return UnityMenu.PlayerAmount; }
set{UnityMenu.PlayerAmount = value; }
}
public Option<ButtonGUI> __PlusButton;
public Option<ButtonGUI> PlusButton{ get { return __PlusButton; }
set{ __PlusButton = value;
if(value.IsSome){if(!value.Value.JustEntered) __PlusButton = value;
else{ value.Value.JustEntered = false;
}
} }
}
public Option<ButtonGUI> __PreviousMButton;
public Option<ButtonGUI> PreviousMButton{ get { return __PreviousMButton; }
set{ __PreviousMButton = value;
if(value.IsSome){if(!value.Value.JustEntered) __PreviousMButton = value;
else{ value.Value.JustEntered = false;
}
} }
}
public ButtonGUI __StartButton;
public ButtonGUI StartButton{ get { return __StartButton; }
set{ __StartButton = value;
if(!value.JustEntered) __StartButton = value;
else{ value.JustEntered = false;
}
}
}
public UnityMenu UnityMenu;
public UnityEngine.Animation animation{ get { return UnityMenu.animation; }
}
public UnityEngine.AudioSource audio{ get { return UnityMenu.audio; }
}
public UnityEngine.Camera camera{ get { return UnityMenu.camera; }
}
public UnityEngine.Collider collider{ get { return UnityMenu.collider; }
}
public UnityEngine.Collider2D collider2D{ get { return UnityMenu.collider2D; }
}
public UnityEngine.ConstantForce constantForce{ get { return UnityMenu.constantForce; }
}
public System.Boolean enabled{ get { return UnityMenu.enabled; }
set{UnityMenu.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityMenu.gameObject; }
}
public UnityEngine.GUIElement guiElement{ get { return UnityMenu.guiElement; }
}
public UnityEngine.GUIText guiText{ get { return UnityMenu.guiText; }
}
public UnityEngine.GUITexture guiTexture{ get { return UnityMenu.guiTexture; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityMenu.hideFlags; }
set{UnityMenu.hideFlags = value; }
}
public UnityEngine.HingeJoint hingeJoint{ get { return UnityMenu.hingeJoint; }
}
public UnityEngine.Light light{ get { return UnityMenu.light; }
}
public System.String name{ get { return UnityMenu.name; }
set{UnityMenu.name = value; }
}
public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityMenu.particleEmitter; }
}
public UnityEngine.ParticleSystem particleSystem{ get { return UnityMenu.particleSystem; }
}
public UnityEngine.Renderer renderer{ get { return UnityMenu.renderer; }
}
public UnityEngine.Rigidbody rigidbody{ get { return UnityMenu.rigidbody; }
}
public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityMenu.rigidbody2D; }
}
public System.String tag{ get { return UnityMenu.tag; }
set{UnityMenu.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityMenu.transform; }
}
public System.Boolean useGUILayout{ get { return UnityMenu.useGUILayout; }
set{UnityMenu.useGUILayout = value; }
}
public ButtonGUI ___LessB00;
public ButtonGUI ___PlusB10;
public ButtonGUI ___NextM20;
public ButtonGUI ___PreviousM30;
public System.Int32 ___Minus40;
public System.Int32 ___Plus40;
public System.Int32 ___previous90;
public System.Int32 ___next100;
System.DateTime init_time = System.DateTime.Now;
public void Update(float dt, Menu world) {
var t = System.DateTime.Now;
this.Rule0(dt, world);
this.Rule1(dt, world);
this.Rule2(dt, world);
this.Rule3(dt, world);
this.Rule4(dt, world);
this.Rule5(dt, world);
this.Rule6(dt, world);
this.Rule7(dt, world);
this.Rule8(dt, world);
this.Rule9(dt, world);
this.Rule10(dt, world);
}
int s0=-1;
public void Rule0(float dt, Menu world){
switch (s0)
{
case -1:
if(((CurrentScreenNumber) == (1)))
{
goto case 0; }else
{
goto case 1; }
case 0:
___LessB00 = new ButtonGUI("Canvas/LessP");
UnityEngine.Debug.Log("LessButton Created");
LessButton = (new Just<ButtonGUI>(___LessB00));
s0 = 3;
return;
case 3:
if(!(false))
{
s0 = 3;
return; }else
{
s0 = -1;
return; }
case 1:
UnityEngine.Debug.Log("LessButton Destroyed");
LessButton = (new Nothing<ButtonGUI>());
s0 = -1;
return;
default: return;}}
int s1=-1;
public void Rule1(float dt, Menu world){
switch (s1)
{
case -1:
if(((CurrentScreenNumber) == (1)))
{
goto case 9; }else
{
goto case 10; }
case 9:
___PlusB10 = new ButtonGUI("Canvas/MoreP");
UnityEngine.Debug.Log("PlusButton Created");
PlusButton = (new Just<ButtonGUI>(___PlusB10));
s1 = 12;
return;
case 12:
if(!(false))
{
s1 = 12;
return; }else
{
s1 = -1;
return; }
case 10:
UnityEngine.Debug.Log("PlusButton Destroyed");
PlusButton = (new Nothing<ButtonGUI>());
s1 = -1;
return;
default: return;}}
int s2=-1;
public void Rule2(float dt, Menu world){
switch (s2)
{
case -1:
if(((CurrentScreenNumber) == (1)))
{
goto case 18; }else
{
goto case 19; }
case 18:
___NextM20 = new ButtonGUI("Canvas/NextM");
UnityEngine.Debug.Log("NextMButton Created");
NextMButton = (new Just<ButtonGUI>(___NextM20));
s2 = 21;
return;
case 21:
if(!(false))
{
s2 = 21;
return; }else
{
s2 = -1;
return; }
case 19:
UnityEngine.Debug.Log("NextMButton Destroyed");
NextMButton = (new Nothing<ButtonGUI>());
s2 = -1;
return;
default: return;}}
int s3=-1;
public void Rule3(float dt, Menu world){
switch (s3)
{
case -1:
if(((CurrentScreenNumber) == (1)))
{
goto case 27; }else
{
goto case 28; }
case 27:
___PreviousM30 = new ButtonGUI("Canvas/PreviousM");
UnityEngine.Debug.Log("PreviousM Created");
PreviousMButton = (new Just<ButtonGUI>(___PreviousM30));
s3 = 30;
return;
case 30:
if(!(false))
{
s3 = 30;
return; }else
{
s3 = -1;
return; }
case 28:
UnityEngine.Debug.Log("PreviousM Destroyed");
PreviousMButton = (new Nothing<ButtonGUI>());
s3 = -1;
return;
default: return;}}
int s4=-1;
public void Rule4(float dt, Menu world){
switch (s4)
{
case -1:
if(!(((LessButton.IsSome) && (PlusButton.IsSome))))
{
s4 = -1;
return; }else
{
goto case 14; }
case 14:
if(!(((LessButton.Value.IsPressed) || (PlusButton.Value.IsPressed))))
{
s4 = 14;
return; }else
{
goto case 13; }
case 13:
___Minus40 = ((AmountOfPlayers) - (1));
___Plus40 = ((AmountOfPlayers) + (1));
if(PlusButton.Value.IsPressed)
{
goto case 7; }else
{
goto case 0; }
case 7:
if(((4) > (AmountOfPlayers)))
{
goto case 9; }else
{
s4 = 0;
return; }
case 9:
UnityEngine.Debug.Log(("Players become ") + (___Plus40));
AmountOfPlayers = ___Plus40;
LessButton.Value.IsPressed = false;
PlusButton.Value.IsPressed = false;
s4 = 0;
return;
case 0:
if(LessButton.Value.IsPressed)
{
goto case 1; }else
{
s4 = -1;
return; }
case 1:
if(((AmountOfPlayers) > (1)))
{
goto case 3; }else
{
s4 = -1;
return; }
case 3:
UnityEngine.Debug.Log(("Players become ") + (___Minus40));
AmountOfPlayers = ___Minus40;
LessButton.Value.IsPressed = false;
PlusButton.Value.IsPressed = false;
s4 = -1;
return;
default: return;}}
int s5=-1;
public void Rule5(float dt, Menu world){
switch (s5)
{
case -1:
PlayerAmount = PlayerAmount;
s5 = -1;
return;
default: return;}}
int s6=-1;
public void Rule6(float dt, Menu world){
switch (s6)
{
case -1:
if(!(((PreviousMButton.IsSome) && (NextMButton.IsSome))))
{
s6 = -1;
return; }else
{
goto case 11; }
case 11:
if(!(((PreviousMButton.Value.IsPressed) || (NextMButton.Value.IsPressed))))
{
s6 = 11;
return; }else
{
goto case 10; }
case 10:
UnityEngine.Debug.Log(MapSelectNumber);
if(PreviousMButton.Value.IsPressed)
{
goto case 4; }else
{
goto case 0; }
case 4:
if(((MapSelectNumber) == (1)))
{
goto case 5; }else
{
goto case 6; }
case 5:
MapSelectNumber = MapSelectNumber;
PreviousMButton.Value.IsPressed = false;
NextMButton.Value.IsPressed = false;
s6 = 0;
return;
case 6:
MapSelectNumber = ((MapSelectNumber) - (1));
PreviousMButton.Value.IsPressed = false;
NextMButton.Value.IsPressed = false;
s6 = 0;
return;
case 0:
if(NextMButton.Value.IsPressed)
{
goto case 1; }else
{
s6 = -1;
return; }
case 1:
MapSelectNumber = ((MapSelectNumber) + (1));
PreviousMButton.Value.IsPressed = false;
NextMButton.Value.IsPressed = false;
s6 = -1;
return;
default: return;}}
int s7=-1;
public void Rule7(float dt, Menu world){
switch (s7)
{
case -1:
UnityEngine.Debug.Log(MapName);
MapName = MapName;
s7 = -1;
return;
default: return;}}
int s8=-1;
public void Rule8(float dt, Menu world){
switch (s8)
{
case -1:
MapSelecter = MapSelecter;
s8 = -1;
return;
default: return;}}
int s9=-1;
public void Rule9(float dt, Menu world){
switch (s9)
{
case -1:
if(!(BackButton.IsPressed))
{
s9 = -1;
return; }else
{
goto case 2; }
case 2:
if(((CurrentScreenNumber) == (0)))
{
goto case 0; }else
{
goto case 1; }
case 0:
UnityEngine.Debug.Log("Quit");
CurrentScreenNumber = -1;
BackButton.IsPressed = false;
s9 = -1;
return;
case 1:
___previous90 = ((CurrentScreenNumber) - (1));
UnityEngine.Debug.Log(("Going to previous scene") + (___previous90));
CurrentScreenNumber = ___previous90;
BackButton.IsPressed = false;
s9 = -1;
return;
default: return;}}
int s10=-1;
public void Rule10(float dt, Menu world){
switch (s10)
{
case -1:
if(!(StartButton.IsPressed))
{
s10 = -1;
return; }else
{
goto case 2; }
case 2:
___next100 = ((CurrentScreenNumber) + (1));
UnityEngine.Debug.Log(("Going to next scene: ") + (___next100));
CurrentScreenNumber = ___next100;
StartButton.IsPressed = false;
s10 = -1;
return;
default: return;}}
}
public class ButtonGUI{
public int frame;
public bool JustEntered = true;
private System.String n;
public int ID;
public ButtonGUI(System.String n)
{JustEntered = false;
frame = Menu.frame;
UnityButton = UnityButton.Find(n);
}
public System.Boolean IsPressed{ get { return UnityButton.IsPressed; }
set{UnityButton.IsPressed = value; }
}
public UnityButton UnityButton;
public UnityEngine.Animation animation{ get { return UnityButton.animation; }
}
public UnityEngine.AudioSource audio{ get { return UnityButton.audio; }
}
public UnityEngine.Camera camera{ get { return UnityButton.camera; }
}
public UnityEngine.Collider collider{ get { return UnityButton.collider; }
}
public UnityEngine.Collider2D collider2D{ get { return UnityButton.collider2D; }
}
public UnityEngine.ConstantForce constantForce{ get { return UnityButton.constantForce; }
}
public System.Boolean enabled{ get { return UnityButton.enabled; }
set{UnityButton.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityButton.gameObject; }
}
public UnityEngine.GUIElement guiElement{ get { return UnityButton.guiElement; }
}
public UnityEngine.GUIText guiText{ get { return UnityButton.guiText; }
}
public UnityEngine.GUITexture guiTexture{ get { return UnityButton.guiTexture; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityButton.hideFlags; }
set{UnityButton.hideFlags = value; }
}
public UnityEngine.HingeJoint hingeJoint{ get { return UnityButton.hingeJoint; }
}
public UnityEngine.Light light{ get { return UnityButton.light; }
}
public System.String name{ get { return UnityButton.name; }
set{UnityButton.name = value; }
}
public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityButton.particleEmitter; }
}
public UnityEngine.ParticleSystem particleSystem{ get { return UnityButton.particleSystem; }
}
public UnityEngine.Renderer renderer{ get { return UnityButton.renderer; }
}
public UnityEngine.Rigidbody rigidbody{ get { return UnityButton.rigidbody; }
}
public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityButton.rigidbody2D; }
}
public System.String tag{ get { return UnityButton.tag; }
set{UnityButton.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityButton.transform; }
}
public System.Boolean useGUILayout{ get { return UnityButton.useGUILayout; }
set{UnityButton.useGUILayout = value; }
}
public void Update(float dt, Menu world) {
frame = Menu.frame;
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax
// .NET Compact Framework 1.0 has no support for Win32 NetMessageBufferSend API
#if !NETCF
// MONO 1.0 has no support for Win32 NetMessageBufferSend API
#if !MONO
// SSCLI 1.0 has no support for Win32 NetMessageBufferSend API
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of log4net
#if !CLI_1_0
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using log4net.Util;
using log4net.Layout;
using log4net.Core;
namespace log4net.Appender
{
/// <summary>
/// Logs entries by sending network messages using the
/// <see cref="NetMessageBufferSend" /> native function.
/// </summary>
/// <remarks>
/// <para>
/// You can send messages only to names that are active
/// on the network. If you send the message to a user name,
/// that user must be logged on and running the Messenger
/// service to receive the message.
/// </para>
/// <para>
/// The receiver will get a top most window displaying the
/// messages one at a time, therefore this appender should
/// not be used to deliver a high volume of messages.
/// </para>
/// <para>
/// The following table lists some possible uses for this appender :
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Action</term>
/// <description>Property Value(s)</description>
/// </listheader>
/// <item>
/// <term>Send a message to a user account on the local machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the local machine>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to a user account on a remote machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the remote machine>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to a domain user account</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of a domain controller | uninitialized>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to all the names in a workgroup or domain</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <workgroup name | domain name>*
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message from the local machine to a remote machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the local machine | uninitialized>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <name of the remote machine>
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// <b>Note :</b> security restrictions apply for sending
/// network messages, see <see cref="NetMessageBufferSend" />
/// for more information.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// An example configuration section to log information
/// using this appender from the local machine, named
/// LOCAL_PC, to machine OPERATOR_PC :
/// </para>
/// <code lang="XML" escaped="true">
/// <appender name="NetSendAppender_Operator" type="log4net.Appender.NetSendAppender">
/// <server value="LOCAL_PC" />
/// <recipient value="OPERATOR_PC" />
/// <layout type="log4net.Layout.PatternLayout" value="%-5p %c [%x] - %m%n" />
/// </appender>
/// </code>
/// </example>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class NetSendAppender : AppenderSkeleton
{
#region Member Variables
/// <summary>
/// The DNS or NetBIOS name of the server on which the function is to execute.
/// </summary>
private string m_server;
/// <summary>
/// The sender of the network message.
/// </summary>
private string m_sender;
/// <summary>
/// The message alias to which the message should be sent.
/// </summary>
private string m_recipient;
/// <summary>
/// The security context to use for privileged calls
/// </summary>
private SecurityContext m_securityContext;
#endregion
#region Constructors
/// <summary>
/// Initializes the appender.
/// </summary>
/// <remarks>
/// The default constructor initializes all fields to their default values.
/// </remarks>
public NetSendAppender()
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the sender of the message.
/// </summary>
/// <value>
/// The sender of the message.
/// </value>
/// <remarks>
/// If this property is not specified, the message is sent from the local computer.
/// </remarks>
public string Sender
{
get { return m_sender; }
set { m_sender = value; }
}
/// <summary>
/// Gets or sets the message alias to which the message should be sent.
/// </summary>
/// <value>
/// The recipient of the message.
/// </value>
/// <remarks>
/// This property should always be specified in order to send a message.
/// </remarks>
public string Recipient
{
get { return m_recipient; }
set { m_recipient = value; }
}
/// <summary>
/// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute.
/// </summary>
/// <value>
/// DNS or NetBIOS name of the remote server on which the function is to execute.
/// </value>
/// <remarks>
/// <para>
/// For Windows NT 4.0 and earlier, the string should begin with \\.
/// </para>
/// <para>
/// If this property is not specified, the local computer is used.
/// </para>
/// </remarks>
public string Server
{
get { return m_server; }
set { m_server = value; }
}
/// <summary>
/// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method.
/// </summary>
/// <value>
/// The <see cref="SecurityContext"/> used to call the NetSend method.
/// </value>
/// <remarks>
/// <para>
/// Unless a <see cref="SecurityContext"/> specified here for this appender
/// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
/// security context to use. The default behavior is to use the security context
/// of the current thread.
/// </para>
/// </remarks>
public SecurityContext SecurityContext
{
get { return m_securityContext; }
set { m_securityContext = value; }
}
#endregion
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// The appender will be ignored if no <see cref="Recipient" /> was specified.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">The required property <see cref="Recipient" /> was not specified.</exception>
public override void ActivateOptions()
{
base.ActivateOptions();
if (this.Recipient == null)
{
throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified.");
}
if (m_securityContext == null)
{
m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
}
#endregion
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Sends the event using a network message.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
protected override void Append(LoggingEvent loggingEvent)
{
NativeError nativeError = null;
// Render the event in the callers security context
string renderedLoggingEvent = RenderLoggingEvent(loggingEvent);
using(m_securityContext.Impersonate(this))
{
// Send the message
int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize);
// Log the error if the message could not be sent
if (returnValue != 0)
{
// Lookup the native error
nativeError = NativeError.GetError(returnValue);
}
}
if (nativeError != null)
{
// Handle the error over to the ErrorHandler
ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")");
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion
#region Stubs For Native Function Calls
/// <summary>
/// Sends a buffer of information to a registered message alias.
/// </summary>
/// <param name="serverName">The DNS or NetBIOS name of the server on which the function is to execute.</param>
/// <param name="msgName">The message alias to which the message buffer should be sent</param>
/// <param name="fromName">The originator of the message.</param>
/// <param name="buffer">The message text.</param>
/// <param name="bufferSize">The length, in bytes, of the message text.</param>
/// <remarks>
/// <para>
/// The following restrictions apply for sending network messages:
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Platform</term>
/// <description>Requirements</description>
/// </listheader>
/// <item>
/// <term>Windows NT</term>
/// <description>
/// <para>
/// No special group membership is required to send a network message.
/// </para>
/// <para>
/// Admin, Accounts, Print, or Server Operator group membership is required to
/// successfully send a network message on a remote server.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Windows 2000 or later</term>
/// <description>
/// <para>
/// If you send a message on a domain controller that is running Active Directory,
/// access is allowed or denied based on the access control list (ACL) for the securable
/// object. The default ACL permits only Domain Admins and Account Operators to send a network message.
/// </para>
/// <para>
/// On a member server or workstation, only Administrators and Server Operators can send a network message.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// For more information see <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/security_requirements_for_the_network_management_functions.asp">Security Requirements for the Network Management Functions</a>.
/// </para>
/// </remarks>
/// <returns>
/// <para>
/// If the function succeeds, the return value is zero.
/// </para>
/// </returns>
[DllImport("netapi32.dll", SetLastError=true)]
protected static extern int NetMessageBufferSend(
[MarshalAs(UnmanagedType.LPWStr)] string serverName,
[MarshalAs(UnmanagedType.LPWStr)] string msgName,
[MarshalAs(UnmanagedType.LPWStr)] string fromName,
[MarshalAs(UnmanagedType.LPWStr)] string buffer,
int bufferSize);
#endregion
}
}
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
#endif // !NETCF
| |
// 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 program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
#if PLATFORM_WINDOWS
#define FEATURE_MANAGED_ETW
#if !ES_BUILD_STANDALONE
#define FEATURE_ACTIVITYSAMPLING
#endif
#endif // PLATFORM_WINDOWS
#if ES_BUILD_STANDALONE
#define FEATURE_MANAGED_ETW_CHANNELS
// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
#endif
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor;
#endif
using System;
using System.Resources;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections.ObjectModel;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
using System.Collections.Generic;
using System.Text;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
using System.Collections.Generic;
using System.Text;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
public partial class EventSource
{
#if FEATURE_MANAGED_ETW
private byte[] providerMetadata;
#endif
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
public EventSource(
string eventSourceName)
: this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat)
{ }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
public EventSource(
string eventSourceName,
EventSourceSettings config)
: this(eventSourceName, config, null) { }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
///
/// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
/// The first string is the key and the second is the value. These are not interpreted by EventSource
/// itself but may be interpreted the listeners. Can be fetched with GetTrait(string).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
/// <param name="traits">A collection of key-value strings (must be an even number).</param>
public EventSource(
string eventSourceName,
EventSourceSettings config,
params string[] traits)
: this(
eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()),
eventSourceName,
config, traits)
{
if (eventSourceName == null)
{
throw new ArgumentNullException(nameof(eventSourceName));
}
Contract.EndContractBlock();
}
/// <summary>
/// Writes an event with no fields and default options.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
public unsafe void Write(string eventName)
{
if (eventName == null)
{
throw new ArgumentNullException(nameof(eventName));
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
}
/// <summary>
/// Writes an event with no fields.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
public unsafe void Write(string eventName, EventSourceOptions options)
{
if (eventName == null)
{
throw new ArgumentNullException(nameof(eventName));
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
public unsafe void Write<T>(
string eventName,
T data)
{
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
public unsafe void Write<T>(
string eventName,
EventSourceOptions options,
T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// This overload is for use with extension methods that wish to efficiently
/// forward the options or data parameter without performing an extra copy.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// This overload is meant for clients that need to manipuate the activityId
/// and related ActivityId for the event.
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="activityId">
/// The GUID of the activity associated with this event.
/// </param>
/// <param name="relatedActivityId">
/// The GUID of another activity that is related to this activity, or Guid.Empty
/// if there is no related activity. Most commonly, the Start operation of a
/// new activity specifies a parent activity as its related activity.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref Guid activityId,
ref Guid relatedActivityId,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId)
{
this.WriteImpl(
eventName,
ref options,
data,
pActivity,
relatedActivityId == Guid.Empty ? null : pRelated,
SimpleEventTypes<T>.Instance);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// This method does a quick check on whether this event is enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null) </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
private unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
if (!this.IsEnabled())
{
return;
}
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// Attention: This API does not check whether the event is enabled or not.
/// Please use WriteMultiMerge to avoid spending CPU cycles for events that are
/// not enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
private unsafe void WriteMultiMergeInner(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
#if FEATURE_MANAGED_ETW
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventTypes.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventTypes.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags);
if (nameInfo == null)
{
return;
}
identity = nameInfo.identity;
EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
for (int i = 0; i < pinCount; i++)
pins[i] = default(GCHandle);
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if (!ES_BUILD_PCL && !ES_BUILD_PN)
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
var info = eventTypes.typeInfos[i];
info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i]));
}
this.WriteEventRaw(
eventName,
ref descriptor,
activityID,
childActivityID,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
#endif // FEATURE_MANAGED_ETW
}
/// <summary>
/// Writes an extended event, where the values of the event have already
/// been serialized in "data".
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="data">
/// The previously serialized values to include in the event. Must not be null.
/// The number and types of the values must match the number and types of the
/// fields described by the eventTypes parameter.
/// </param>
internal unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
EventData* data)
{
#if FEATURE_MANAGED_ETW
if (!this.IsEnabled())
{
return;
}
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
// We make a descriptor for each EventData, and because we morph strings to counted strings
// we may have 2 for each arg, so we allocate enough for this.
var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
int numDescrs = 3;
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
// Until M3, we need to morph strings to a counted representation
// When TDH supports null terminated strings, we can remove this.
if (eventTypes.typeInfos[i].DataType == typeof(string))
{
// Write out the size of the string
descriptors[numDescrs].DataPointer = (IntPtr) (&descriptors[numDescrs + 1].m_Size);
descriptors[numDescrs].m_Size = 2;
numDescrs++;
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator
numDescrs++;
}
else
{
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size;
// old conventions for bool is 4 bytes, but meta-data assumes 1.
if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool))
descriptors[numDescrs].m_Size = 1;
numDescrs++;
}
}
this.WriteEventRaw(
eventName,
ref descriptor,
activityID,
childActivityID,
numDescrs,
(IntPtr)descriptors);
}
}
#endif // FEATURE_MANAGED_ETW
}
private unsafe void WriteImpl(
string eventName,
ref EventSourceOptions options,
object data,
Guid* pActivityId,
Guid* pRelatedActivityId,
TraceLoggingEventTypes eventTypes)
{
try
{
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName);
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
#if FEATURE_MANAGED_ETW
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
for (int i = 0; i < pinCount; i++)
pins[i] = default(GCHandle);
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#endif // FEATURE_MANAGED_ETW
#if (!ES_BUILD_PCL && !ES_BUILD_PN)
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
EventOpcode opcode = (EventOpcode)descriptor.Opcode;
Guid activityId = Guid.Empty;
Guid relatedActivityId = Guid.Empty;
if (pActivityId == null && pRelatedActivityId == null &&
((options.ActivityOptions & EventActivityOptions.Disable) == 0))
{
if (opcode == EventOpcode.Start)
{
m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions);
}
else if (opcode == EventOpcode.Stop)
{
m_activityTracker.OnStop(m_name, eventName, 0, ref activityId);
}
if (activityId != Guid.Empty)
pActivityId = &activityId;
if (relatedActivityId != Guid.Empty)
pRelatedActivityId = &relatedActivityId;
}
try
{
#if FEATURE_MANAGED_ETW
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
var info = eventTypes.typeInfos[0];
info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data));
this.WriteEventRaw(
eventName,
ref descriptor,
pActivityId,
pRelatedActivityId,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
#endif // FEATURE_MANAGED_ETW
// TODO enable filtering for listeners.
if (m_Dispatchers != null)
{
var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data));
WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData);
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(eventName, ex);
}
#if FEATURE_MANAGED_ETW
finally
{
this.WriteCleanup(pins, pinCount);
}
}
#endif // FEATURE_MANAGED_ETW
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(eventName, ex);
}
}
private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
{
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
eventCallbackArgs.EventName = eventName;
eventCallbackArgs.m_level = (EventLevel) eventDescriptor.Level;
eventCallbackArgs.m_keywords = (EventKeywords) eventDescriptor.Keywords;
eventCallbackArgs.m_opcode = (EventOpcode) eventDescriptor.Opcode;
eventCallbackArgs.m_tags = tags;
// Self described events do not have an id attached. We mark it internally with -1.
eventCallbackArgs.EventId = -1;
if (pActivityId != null)
eventCallbackArgs.RelatedActivityId = *pActivityId;
if (payload != null)
{
eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values);
eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys);
}
DispatchToAllListeners(-1, pActivityId, eventCallbackArgs);
}
#if (!ES_BUILD_PCL && !ES_BUILD_PN)
[System.Runtime.ConstrainedExecution.ReliabilityContract(
System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
System.Runtime.ConstrainedExecution.Cer.Success)]
#endif
[NonEvent]
private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
{
DataCollector.ThreadInstance.Disable();
for (int i = 0; i < cPins; i++)
{
if (pPins[i].IsAllocated)
{
pPins[i].Free();
}
}
}
private void InitializeProviderMetadata()
{
#if FEATURE_MANAGED_ETW
if (m_traits != null)
{
List<byte> traitMetaData = new List<byte>(100);
for (int i = 0; i < m_traits.Length - 1; i += 2)
{
if (m_traits[i].StartsWith("ETW_", StringComparison.Ordinal))
{
string etwTrait = m_traits[i].Substring(4);
byte traitNum;
if (!byte.TryParse(etwTrait, out traitNum))
{
if (etwTrait == "GROUP")
{
traitNum = 1;
}
else
{
throw new ArgumentException(SR.Format(SR.EventSource_UnknownEtwTrait, etwTrait), "traits");
}
}
string value = m_traits[i + 1];
int lenPos = traitMetaData.Count;
traitMetaData.Add(0); // Emit size (to be filled in later)
traitMetaData.Add(0);
traitMetaData.Add(traitNum); // Emit Trait number
var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above.
traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size
traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8));
}
}
providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0);
int startPos = providerMetadata.Length - traitMetaData.Count;
foreach (var b in traitMetaData)
providerMetadata[startPos++] = b;
}
else
providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0);
#endif //FEATURE_MANAGED_ETW
}
private static int AddValueToMetaData(List<byte> metaData, string value)
{
if (value.Length == 0)
return 0;
int startPos = metaData.Count;
char firstChar = value[0];
if (firstChar == '@')
metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1)));
else if (firstChar == '{')
metaData.AddRange(new Guid(value).ToByteArray());
else if (firstChar == '#')
{
for (int i = 1; i < value.Length; i++)
{
if (value[i] != ' ') // Skip spaces between bytes.
{
if (!(i + 1 < value.Length))
{
throw new ArgumentException(SR.EventSource_EvenHexDigits, "traits");
}
metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1])));
i++;
}
}
}
else if ('A' <= firstChar || ' ' == firstChar) // Is it alphabetic or space (excludes digits and most punctuation).
{
metaData.AddRange(Encoding.UTF8.GetBytes(value));
}
else
{
throw new ArgumentException(SR.Format(SR.EventSource_IllegalValue, value), "traits");
}
return metaData.Count - startPos;
}
/// <summary>
/// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception.
/// </summary>
private static int HexDigit(char c)
{
if ('0' <= c && c <= '9')
{
return (c - '0');
}
if ('a' <= c)
{
c = unchecked((char)(c - ('a' - 'A'))); // Convert to lower case
}
if ('A' <= c && c <= 'F')
{
return (c - 'A' + 10);
}
throw new ArgumentException(SR.Format(SR.EventSource_BadHexDigit, c), "traits");
}
private NameInfo UpdateDescriptor(
string name,
TraceLoggingEventTypes eventInfo,
ref EventSourceOptions options,
out EventDescriptor descriptor)
{
NameInfo nameInfo = null;
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventInfo.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventInfo.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventInfo.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventInfo.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags);
identity = nameInfo.identity;
}
descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
return nameInfo;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
using System.Numerics;
#endif
using System.Text;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JTokenWriterTest : TestFixtureBase
{
[Test]
public void ValueFormatting()
{
byte[] data = Encoding.UTF8.GetBytes("Hello world.");
JToken root;
using (JTokenWriter jsonWriter = new JTokenWriter())
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue('@');
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
jsonWriter.WriteValue(true);
jsonWriter.WriteValue(10);
jsonWriter.WriteValue(10.99);
jsonWriter.WriteValue(0.99);
jsonWriter.WriteValue(0.000000000000000001d);
jsonWriter.WriteValue(0.000000000000000001m);
jsonWriter.WriteValue((string)null);
jsonWriter.WriteValue("This is a string.");
jsonWriter.WriteNull();
jsonWriter.WriteUndefined();
jsonWriter.WriteValue(data);
jsonWriter.WriteEndArray();
root = jsonWriter.Token;
}
CustomAssert.IsInstanceOfType(typeof(JArray), root);
Assert.AreEqual(13, root.Children().Count());
Assert.AreEqual("@", (string)root[0]);
Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]);
Assert.AreEqual(true, (bool)root[2]);
Assert.AreEqual(10, (int)root[3]);
Assert.AreEqual(10.99, (double)root[4]);
Assert.AreEqual(0.99, (double)root[5]);
Assert.AreEqual(0.000000000000000001d, (double)root[6]);
Assert.AreEqual(0.000000000000000001m, (decimal)root[7]);
Assert.AreEqual(null, (string)root[8]);
Assert.AreEqual("This is a string.", (string)root[9]);
Assert.AreEqual(null, ((JValue)root[10]).Value);
Assert.AreEqual(null, ((JValue)root[11]).Value);
Assert.AreEqual(data, (byte[])root[12]);
}
[Test]
public void State()
{
using (JsonWriter jsonWriter = new JTokenWriter())
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#endif
jsonWriter.WriteValue(new byte[0]);
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
}
}
[Test]
public void CurrentToken()
{
using (JTokenWriter jsonWriter = new JTokenWriter())
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
Assert.AreEqual(null, jsonWriter.CurrentToken);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(jsonWriter.Token, jsonWriter.CurrentToken);
JObject o = (JObject)jsonWriter.Token;
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual(o.Property("CPU"), jsonWriter.CurrentToken);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(o["CPU"], jsonWriter.CurrentToken);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual(o.Property("Drives"), jsonWriter.CurrentToken);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(o["Drives"], jsonWriter.CurrentToken);
JArray a = (JArray)jsonWriter.CurrentToken;
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
#endif
jsonWriter.WriteValue(new byte[0]);
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(a, jsonWriter.CurrentToken);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
Assert.AreEqual(o, jsonWriter.CurrentToken);
}
}
[Test]
public void WriteComment()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteComment("fail");
writer.WriteEndArray();
StringAssert.AreEqual(@"[
/*fail*/]", writer.Token.ToString());
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
[Test]
public void WriteBigInteger()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteValue(new BigInteger(123));
writer.WriteEndArray();
JValue i = (JValue)writer.Token[0];
Assert.AreEqual(new BigInteger(123), i.Value);
Assert.AreEqual(JTokenType.Integer, i.Type);
StringAssert.AreEqual(@"[
123
]", writer.Token.ToString());
}
#endif
[Test]
public void WriteRaw()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteRaw("fail");
writer.WriteRaw("fail");
writer.WriteEndArray();
// this is a bug. write raw shouldn't be autocompleting like this
// hard to fix without introducing Raw and RawValue token types
// meh
StringAssert.AreEqual(@"[
fail,
fail
]", writer.Token.ToString());
}
[Test]
public void WriteTokenWithParent()
{
JObject o = new JObject
{
["prop1"] = new JArray(1),
["prop2"] = 1
};
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteToken(o.CreateReader());
Assert.AreEqual(WriteState.Array, writer.WriteState);
writer.WriteEndArray();
Console.WriteLine(writer.Token.ToString());
StringAssert.AreEqual(@"[
{
""prop1"": [
1
],
""prop2"": 1
}
]", writer.Token.ToString());
}
[Test]
public void WriteTokenWithPropertyParent()
{
JValue v = new JValue(1);
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("Prop1");
writer.WriteToken(v.CreateReader());
Assert.AreEqual(WriteState.Object, writer.WriteState);
writer.WriteEndObject();
StringAssert.AreEqual(@"{
""Prop1"": 1
}", writer.Token.ToString());
}
[Test]
public void WriteValueTokenWithParent()
{
JValue v = new JValue(1);
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteToken(v.CreateReader());
Assert.AreEqual(WriteState.Array, writer.WriteState);
writer.WriteEndArray();
StringAssert.AreEqual(@"[
1
]", writer.Token.ToString());
}
[Test]
public void WriteEmptyToken()
{
JObject o = new JObject();
JsonReader reader = o.CreateReader();
while (reader.Read())
{
}
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteToken(reader);
Assert.AreEqual(WriteState.Array, writer.WriteState);
writer.WriteEndArray();
StringAssert.AreEqual(@"[]", writer.Token.ToString());
}
[Test]
public void WriteRawValue()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteRawValue("fail");
writer.WriteRawValue("fail");
writer.WriteEndArray();
StringAssert.AreEqual(@"[
fail,
fail
]", writer.Token.ToString());
}
[Test]
public void WriteDuplicatePropertyName()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("prop1");
writer.WriteStartObject();
writer.WriteEndObject();
writer.WritePropertyName("prop1");
writer.WriteStartArray();
writer.WriteEndArray();
writer.WriteEndObject();
StringAssert.AreEqual(@"{
""prop1"": []
}", writer.Token.ToString());
}
[Test]
public void DateTimeZoneHandling()
{
JTokenWriter writer = new JTokenWriter
{
DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
};
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
JValue value = (JValue)writer.Token;
DateTime dt = (DateTime)value.Value;
Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// PartitionerQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Linq.Parallel;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// A QueryOperator that represents the output of the query partitioner.AsParallel().
/// </summary>
internal class PartitionerQueryOperator<TElement> : QueryOperator<TElement>
{
private Partitioner<TElement> _partitioner; // The partitioner to use as data source.
internal PartitionerQueryOperator(Partitioner<TElement> partitioner)
: base(false, QuerySettings.Empty)
{
_partitioner = partitioner;
}
internal bool Orderable
{
get { return _partitioner is OrderablePartitioner<TElement>; }
}
internal override QueryResults<TElement> Open(QuerySettings settings, bool preferStriping)
{
// Notice that the preferStriping argument is not used. Partitioner<T> does not support
// striped partitioning.
return new PartitionerQueryOperatorResults(_partitioner, settings);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TElement> AsSequentialQuery(CancellationToken token)
{
using (IEnumerator<TElement> enumerator = _partitioner.GetPartitions(1)[0])
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
//---------------------------------------------------------------------------------------
// The state of the order index of the results returned by this operator.
//
internal override OrdinalIndexState OrdinalIndexState
{
get { return GetOrdinalIndexState(_partitioner); }
}
/// <summary>
/// Determines the OrdinalIndexState for a partitioner
/// </summary>
internal static OrdinalIndexState GetOrdinalIndexState(Partitioner<TElement> partitioner)
{
OrderablePartitioner<TElement> orderablePartitioner = partitioner as OrderablePartitioner<TElement>;
if (orderablePartitioner == null)
{
return OrdinalIndexState.Shuffled;
}
if (orderablePartitioner.KeysOrderedInEachPartition)
{
if (orderablePartitioner.KeysNormalized)
{
return OrdinalIndexState.Correct;
}
else
{
return OrdinalIndexState.Increasing;
}
}
else
{
return OrdinalIndexState.Shuffled;
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
/// <summary>
/// QueryResults for a PartitionerQueryOperator
/// </summary>
private class PartitionerQueryOperatorResults : QueryResults<TElement>
{
private Partitioner<TElement> _partitioner; // The data source for the query
private QuerySettings _settings; // Settings collected from the query
internal PartitionerQueryOperatorResults(Partitioner<TElement> partitioner, QuerySettings settings)
{
_partitioner = partitioner;
_settings = settings;
}
internal override void GivePartitionedStream(IPartitionedStreamRecipient<TElement> recipient)
{
Contract.Assert(_settings.DegreeOfParallelism.HasValue);
int partitionCount = _settings.DegreeOfParallelism.Value;
OrderablePartitioner<TElement> orderablePartitioner = _partitioner as OrderablePartitioner<TElement>;
// If the partitioner is not orderable, it will yield zeros as order keys. The order index state
// is irrelevant.
OrdinalIndexState indexState = (orderablePartitioner != null)
? GetOrdinalIndexState(orderablePartitioner)
: OrdinalIndexState.Shuffled;
PartitionedStream<TElement, int> partitions = new PartitionedStream<TElement, int>(
partitionCount,
Util.GetDefaultComparer<int>(),
indexState);
if (orderablePartitioner != null)
{
IList<IEnumerator<KeyValuePair<long, TElement>>> partitionerPartitions =
orderablePartitioner.GetOrderablePartitions(partitionCount);
if (partitionerPartitions == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartitionList);
}
if (partitionerPartitions.Count != partitionCount)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_WrongNumberOfPartitions);
}
for (int i = 0; i < partitionCount; i++)
{
IEnumerator<KeyValuePair<long, TElement>> partition = partitionerPartitions[i];
if (partition == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartition);
}
partitions[i] = new OrderablePartitionerEnumerator(partition);
}
}
else
{
IList<IEnumerator<TElement>> partitionerPartitions =
_partitioner.GetPartitions(partitionCount);
if (partitionerPartitions == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartitionList);
}
if (partitionerPartitions.Count != partitionCount)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_WrongNumberOfPartitions);
}
for (int i = 0; i < partitionCount; i++)
{
IEnumerator<TElement> partition = partitionerPartitions[i];
if (partition == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartition);
}
partitions[i] = new PartitionerEnumerator(partition);
}
}
recipient.Receive<int>(partitions);
}
}
/// <summary>
/// Enumerator that converts an enumerator over key-value pairs exposed by a partitioner
/// to a QueryOperatorEnumerator used by PLINQ internally.
/// </summary>
private class OrderablePartitionerEnumerator : QueryOperatorEnumerator<TElement, int>
{
private IEnumerator<KeyValuePair<long, TElement>> _sourceEnumerator;
internal OrderablePartitionerEnumerator(IEnumerator<KeyValuePair<long, TElement>> sourceEnumerator)
{
_sourceEnumerator = sourceEnumerator;
}
internal override bool MoveNext(ref TElement currentElement, ref int currentKey)
{
if (!_sourceEnumerator.MoveNext()) return false;
KeyValuePair<long, TElement> current = _sourceEnumerator.Current;
currentElement = current.Value;
checked
{
currentKey = (int)current.Key;
}
return true;
}
protected override void Dispose(bool disposing)
{
Contract.Assert(_sourceEnumerator != null);
_sourceEnumerator.Dispose();
}
}
/// <summary>
/// Enumerator that converts an enumerator over key-value pairs exposed by a partitioner
/// to a QueryOperatorEnumerator used by PLINQ internally.
/// </summary>
private class PartitionerEnumerator : QueryOperatorEnumerator<TElement, int>
{
private IEnumerator<TElement> _sourceEnumerator;
internal PartitionerEnumerator(IEnumerator<TElement> sourceEnumerator)
{
_sourceEnumerator = sourceEnumerator;
}
internal override bool MoveNext(ref TElement currentElement, ref int currentKey)
{
if (!_sourceEnumerator.MoveNext()) return false;
currentElement = _sourceEnumerator.Current;
currentKey = 0;
return true;
}
protected override void Dispose(bool disposing)
{
Contract.Assert(_sourceEnumerator != null);
_sourceEnumerator.Dispose();
}
}
}
}
| |
using System.Diagnostics;
namespace System.Data.SQLite
{
public partial class Sqlite3
{
/*
** 2009 March 3
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains the implementation of the sqlite3_unlock_notify()
** API method and its associated functionality.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include "btreeInt.h"
/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
#if SQLITE_ENABLE_UNLOCK_NOTIFY
/*
** Public interfaces:
**
** sqlite3ConnectionBlocked()
** sqlite3ConnectionUnlocked()
** sqlite3ConnectionClosed()
** sqlite3_unlock_notify()
*/
//#define assertMutexHeld() \
assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
/*
** Head of a linked list of all sqlite3 objects created by this process
** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
** is not NULL. This variable may only accessed while the STATIC_MASTER
** mutex is held.
*/
static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
#if !NDEBUG
/*
** This function is a complex assert() that verifies the following
** properties of the blocked connections list:
**
** 1) Each entry in the list has a non-NULL value for either
** pUnlockConnection or pBlockingConnection, or both.
**
** 2) All entries in the list that share a common value for
** xUnlockNotify are grouped together.
**
** 3) If the argument db is not NULL, then none of the entries in the
** blocked connections list have pUnlockConnection or pBlockingConnection
** set to db. This is used when closing connection db.
*/
static void checkListProperties(sqlite3 *db){
sqlite3 *p;
for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
int seen = 0;
sqlite3 *p2;
/* Verify property (1) */
assert( p->pUnlockConnection || p->pBlockingConnection );
/* Verify property (2) */
for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
assert( db==0 || p->pUnlockConnection!=db );
assert( db==0 || p->pBlockingConnection!=db );
}
}
}
#else
//# define checkListProperties(x)
#endif
/*
** Remove connection db from the blocked connections list. If connection
** db is not currently a part of the list, this function is a no-op.
*/
static void removeFromBlockedList(sqlite3 *db){
sqlite3 **pp;
assertMutexHeld();
for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
if( *pp==db ){
*pp = (*pp)->pNextBlocked;
break;
}
}
}
/*
** Add connection db to the blocked connections list. It is assumed
** that it is not already a part of the list.
*/
static void addToBlockedList(sqlite3 *db){
sqlite3 **pp;
assertMutexHeld();
for(
pp=&sqlite3BlockedList;
*pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
pp=&(*pp)->pNextBlocked
);
db->pNextBlocked = *pp;
*pp = db;
}
/*
** Obtain the STATIC_MASTER mutex.
*/
static void enterMutex(){
sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
checkListProperties(0);
}
/*
** Release the STATIC_MASTER mutex.
*/
static void leaveMutex(){
assertMutexHeld();
checkListProperties(0);
sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
}
/*
** Register an unlock-notify callback.
**
** This is called after connection "db" has attempted some operation
** but has received an SQLITE_LOCKED error because another connection
** (call it pOther) in the same process was busy using the same shared
** cache. pOther is found by looking at db->pBlockingConnection.
**
** If there is no blocking connection, the callback is invoked immediately,
** before this routine returns.
**
** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
** a deadlock.
**
** Otherwise, make arrangements to invoke xNotify when pOther drops
** its locks.
**
** Each call to this routine overrides any prior callbacks registered
** on the same "db". If xNotify==0 then any prior callbacks are immediately
** cancelled.
*/
int sqlite3_unlock_notify(
sqlite3 *db,
void (*xNotify)(void **, int),
void *pArg
){
int rc = SQLITE_OK;
sqlite3_mutex_enter(db->mutex);
enterMutex();
if( xNotify==0 ){
removeFromBlockedList(db);
db->pUnlockConnection = 0;
db->xUnlockNotify = 0;
db->pUnlockArg = 0;
}else if( 0==db->pBlockingConnection ){
/* The blocking transaction has been concluded. Or there never was a
** blocking transaction. In either case, invoke the notify callback
** immediately.
*/
xNotify(&pArg, 1);
}else{
sqlite3 *p;
for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
if( p ){
rc = SQLITE_LOCKED; /* Deadlock detected. */
}else{
db->pUnlockConnection = db->pBlockingConnection;
db->xUnlockNotify = xNotify;
db->pUnlockArg = pArg;
removeFromBlockedList(db);
addToBlockedList(db);
}
}
leaveMutex();
assert( !db->mallocFailed );
sqlite3Error(db, rc, (rc?"database is deadlocked":0));
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** This function is called while stepping or preparing a statement
** associated with connection db. The operation will return SQLITE_LOCKED
** to the user because it requires a lock that will not be available
** until connection pBlocker concludes its current transaction.
*/
void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
enterMutex();
if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
addToBlockedList(db);
}
db->pBlockingConnection = pBlocker;
leaveMutex();
}
/*
** This function is called when
** the transaction opened by database db has just finished. Locks held
** by database connection db have been released.
**
** This function loops through each entry in the blocked connections
** list and does the following:
**
** 1) If the sqlite3.pBlockingConnection member of a list entry is
** set to db, then set pBlockingConnection=0.
**
** 2) If the sqlite3.pUnlockConnection member of a list entry is
** set to db, then invoke the configured unlock-notify callback and
** set pUnlockConnection=0.
**
** 3) If the two steps above mean that pBlockingConnection==0 and
** pUnlockConnection==0, remove the entry from the blocked connections
** list.
*/
void sqlite3ConnectionUnlocked(sqlite3 *db){
void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
int nArg = 0; /* Number of entries in aArg[] */
sqlite3 **pp; /* Iterator variable */
void **aArg; /* Arguments to the unlock callback */
void **aDyn = 0; /* Dynamically allocated space for aArg[] */
void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
aArg = aStatic;
enterMutex(); /* Enter STATIC_MASTER mutex */
/* This loop runs once for each entry in the blocked-connections list. */
for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
sqlite3 *p = *pp;
/* Step 1. */
if( p->pBlockingConnection==db ){
p->pBlockingConnection = 0;
}
/* Step 2. */
if( p->pUnlockConnection==db ){
assert( p->xUnlockNotify );
if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
xUnlockNotify(aArg, nArg);
nArg = 0;
}
sqlite3BeginBenignMalloc();
assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
if( (!aDyn && nArg==(int)ArraySize(aStatic))
|| (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
){
/* The aArg[] array needs to grow. */
void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
if( pNew ){
memcpy(pNew, aArg, nArg*sizeof(void *));
//sqlite3_free(aDyn);
aDyn = aArg = pNew;
}else{
/* This occurs when the array of context pointers that need to
** be passed to the unlock-notify callback is larger than the
** aStatic[] array allocated on the stack and the attempt to
** allocate a larger array from the heap has failed.
**
** This is a difficult situation to handle. Returning an error
** code to the caller is insufficient, as even if an error code
** is returned the transaction on connection db will still be
** closed and the unlock-notify callbacks on blocked connections
** will go unissued. This might cause the application to wait
** indefinitely for an unlock-notify callback that will never
** arrive.
**
** Instead, invoke the unlock-notify callback with the context
** array already accumulated. We can then clear the array and
** begin accumulating any further context pointers without
** requiring any dynamic allocation. This is sub-optimal because
** it means that instead of one callback with a large array of
** context pointers the application will receive two or more
** callbacks with smaller arrays of context pointers, which will
** reduce the applications ability to prioritize multiple
** connections. But it is the best that can be done under the
** circumstances.
*/
xUnlockNotify(aArg, nArg);
nArg = 0;
}
}
sqlite3EndBenignMalloc();
aArg[nArg++] = p->pUnlockArg;
xUnlockNotify = p->xUnlockNotify;
p->pUnlockConnection = 0;
p->xUnlockNotify = 0;
p->pUnlockArg = 0;
}
/* Step 3. */
if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
/* Remove connection p from the blocked connections list. */
*pp = p->pNextBlocked;
p->pNextBlocked = 0;
}else{
pp = &p->pNextBlocked;
}
}
if( nArg!=0 ){
xUnlockNotify(aArg, nArg);
}
//sqlite3_free(aDyn);
leaveMutex(); /* Leave STATIC_MASTER mutex */
}
/*
** This is called when the database connection passed as an argument is
** being closed. The connection is removed from the blocked list.
*/
void sqlite3ConnectionClosed(sqlite3 *db){
sqlite3ConnectionUnlocked(db);
enterMutex();
removeFromBlockedList(db);
checkListProperties(db);
leaveMutex();
}
#endif
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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
* http://www.gnu.org/copyleft/lesser.html
*/
using System;
using System.Collections.Generic;
using System.IO;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Tools.Import {
public enum Mode {
Import,
Export,
Copy
}
public enum Restriction {
Default,
Public,
SemiPublic,
Private
}
public class Opts {
//--- Class Fields ---
public static string[] Usage = new string[] {
"USAGE: mindtouch.import.exe [options] [target]",
"",
" [target] is either a path to a directory or a filepath ending in .mtarc or .mtapp",
" (not used for copy operations)",
"",
"Options:",
" (Options must be prefixed by a '-' or '/')",
"",
" Modes: Import (default), Export or Copy",
" e|export - export mode",
" c|copy - copy mode",
"",
" General:",
" ?|usage - display this message",
" C|config <path> - confguration xml file (see below)",
" g|genconfig <path> - instead of executing the command, generate the config file for later execution",
" h|host <host> - MindTouch host (assumes standard API location)",
" u|uri <api-uri> - specify the full uri to the API",
" a|archive - force the target to be treated as an archive file",
" f|folder - force the target to be treated as a folder",
" I|importreltopath <path> - relative uri path for import and copy destination",
" importrelto <id> - relative page id for import and copy destination (alternative to importreltopath)",
" X|exportreltopath <path> - relative uri path for export and copy source",
" exportrelto <id> - relative page id for export and copy source (alternative to exportreltopath)",
" D|exportdoc <filename> - filename of the export xml document for export or copy",
" L|exportlist <filename> - list of paths or uri's to pages to export (respects 'recursive' flag)",
" p|exportpath <path> - specifies the uri path to export (in lieu of specifying an export document/list)",
" r|recursive - export all child documents of 'exportpath' or 'exportlist'",
" o|output - output file/directory path for import or export",
" R|retries - Maximum number of retries on import/export item failures (default: 3)",
" l|preservelocal - mark package to preserve local changes to existing pages on import",
" O|overwritelocal - mark package to preserve local changes to existing pages on import",
" (overwrite is the default unless the package has a different value set, in which case",
" this flag can be used to forces overwrite behavior on import)",
" s|securityrestriction (public|semipublic|private)",
" - enforce a page restriction for all imported content",
" cap <capability-name>[=<capability-value>]",
" - add a capability requirement for the exported package. The default for capability-value",
" 'enabled'",
"",
" Authentication:",
" (if no authentication is provided, the program will prompt for user and password interactively)",
" A|authtoken <token> - authtoken to use for user authentication",
" U|user <username> - username for authentication (requires password option",
" P|password <password> - password for username authentcation",
"",
"Xml Configuration:",
" Commandline options can be provided by or augmented with an xml configuration document:",
" <config [option-longname]='value' ...>",
" [ <target>{output/input file/dir for import/export}</target> ]",
" [ <export><!--optionally inlined export document--></export> ]",
" </config>",
" Value-less options are booleans and have an xml attribute value of 'true' or 'false'.",
" The 'genconfig' option creates this configuration document from the provided settings for later use.",
""
};
//--- Fields ---
public bool WantUsage;
public Mode Mode = Mode.Import;
public bool Archive;
public Plug DekiApi;
public string FilePath;
public string ImportReltoPath = "/";
public int? ImportRelto;
public string ExportReltoPath = "/";
public int? ExportRelto;
public XDoc ExportDocument;
public string User;
public string Password;
public string AuthToken;
public bool Test;
public bool GenConfig;
public int Retries = 3;
public bool? PreserveLocalChanges;
public string ExportPath;
public Restriction Restriction = Restriction.Default;
public List<KeyValuePair<string, string>> Capabilities = new List<KeyValuePair<string, string>>();
private bool _exportRecursive;
private string _genConfigPath;
//--- Methods ---
public Opts(string[] argArray) {
List<string> args = new List<string>(argArray);
int index = 0;
bool? archive = null;
Func<XDoc> exportDocumentBuilder = null;
while(index < args.Count) {
if(WantUsage) {
break;
}
string key = args[index];
string value = (index + 1 >= args.Count) ? null : args[index + 1];
bool handled = false;
if(key.StartsWith("-") || key.StartsWith("/")) {
handled = true;
key = key.Remove(0, 1);
switch(key) {
case "a":
case "archive":
archive = true;
break;
case "A":
case "authtoken":
AuthToken = value;
index++;
break;
case "C":
case "config":
index++;
List<string> extra = ConfigureFromXml(value);
extra.Reverse();
foreach(string opt in extra) {
args.Insert(index + 1, opt);
}
break;
case "c":
case "copy":
Mode = Mode.Copy;
break;
case "cap":
index++;
var split = value.Split(new[] { '=' }, 2);
var name = split[0];
var v = (split.Length == 2) ? split[1] : null;
Capabilities.Add(new KeyValuePair<string, string>(name,v));
break;
case "e":
case "export":
Mode = Mode.Export;
break;
case "p":
case "exportPath":
string exportPath = value;
ExportPath = exportPath;
exportDocumentBuilder = delegate() { return CreateExportDocumentFromSinglePath(exportPath); };
index++;
break;
case "D":
case "exportdoc":
string exportDocumentPath = value;
exportDocumentBuilder = delegate() { return LoadExportDocumentFromFile(exportDocumentPath); };
index++;
break;
case "f":
case "folder":
archive = false;
break;
case "L":
case "exportlist":
string exportListPath = value;
exportDocumentBuilder = delegate() { return CreateExportDocumentFromList(exportListPath); };
index++;
break;
case "l":
case "preservelocal":
PreserveLocalChanges = true;
break;
case "O":
case "overwritelocal":
PreserveLocalChanges = false;
break;
case "g":
case "genconfig":
GenConfig = true;
_genConfigPath = value;
index++;
break;
case "h":
case "host":
try {
if(!value.StartsWithInvariantIgnoreCase("http://") && !value.StartsWithInvariantIgnoreCase("https://")) {
DekiApi = Plug.New(string.Format("http://{0}/@api/deki", value));
} else {
DekiApi = Plug.New(new XUri(value).At("@api", "deki"));
}
} catch {
throw new ConfigurationException("Invalid host format {0}", value);
}
index++;
break;
case "I":
case "importreltopath":
ImportReltoPath = Title.FromUIUri(null, value).AsPrefixedDbPath();
index++;
break;
case "importrelto":
ImportRelto = int.Parse(value);
index++;
break;
case "X":
case "exportreltopath":
ExportReltoPath = Title.FromUIUri(null, value).AsPrefixedDbPath();
index++;
break;
case "exportrelto":
ExportRelto = int.Parse(value);
index++;
break;
case "P":
case "password":
Password = value;
index++;
break;
case "r":
case "recursive":
_exportRecursive = true;
break;
case "R":
case "retries":
Retries = int.Parse(value);
index++;
break;
case "s":
case "securityrestriction":
try {
Restriction = SysUtil.ChangeType<Restriction>(value);
} catch {
throw new ConfigurationException("invalid securityrestriction: {0}", value);
}
index++;
break;
case "U":
case "user":
User = value;
index++;
break;
case "u":
case "uri":
DekiApi = Plug.New(value);
index++;
break;
case "?":
case "usage":
WantUsage = true;
break;
case "t":
Test = true;
break;
default:
handled = false;
break;
}
}
if(!handled) {
if(index + 1 == args.Count && Mode != Mode.Copy) {
FilePath = key;
} else {
throw new ConfigurationException("Unknown option {0}", key);
}
}
index++;
}
if(WantUsage) {
return;
}
if(!string.IsNullOrEmpty(FilePath)) {
string ext = Path.GetExtension(FilePath);
if(!archive.HasValue) {
// Note (arnec): .zip and .mtap are still being handled for backwards compatibility, but have been removed from docs
if(ext.EqualsInvariantIgnoreCase(".mtapp") || ext.EqualsInvariantIgnoreCase(".mtarc") ||
ext.EqualsInvariantIgnoreCase(".zip") || ext.EqualsInvariantIgnoreCase(".mtap")) {
archive = true;
}
}
}
Archive = archive ?? false;
if(Mode != Mode.Import && ExportDocument == null) {
if(exportDocumentBuilder == null) {
exportDocumentBuilder = delegate() { return CreateExportDocumentFromSinglePath(ExportReltoPath); };
}
ExportDocument = exportDocumentBuilder();
}
if(Mode == Mode.Copy || !string.IsNullOrEmpty(FilePath)) {
return;
}
if(Archive) {
throw new ConfigurationException("Missing {0} Archive filepath", Mode);
}
throw new ConfigurationException("Missing {0} Directory", Mode);
}
private XDoc CreateExportDocumentFromSinglePath(string exportPath) {
return new XDoc("export")
.Start("page")
.Attr("path", Title.FromUIUri(null, exportPath).AsPrefixedDbPath())
.Attr("recursive", _exportRecursive)
.End();
}
private XDoc CreateExportDocumentFromList(string listPath) {
if(!File.Exists(listPath)) {
throw new ConfigurationException("No such export list: {0}", listPath);
}
XDoc exportDoc = new XDoc("export");
foreach(string line in File.ReadAllLines(listPath)) {
if(string.IsNullOrEmpty(line)) {
continue;
}
if(line.StartsWith("#")) {
exportDoc.Comment(line.Remove(0, 1));
continue;
}
try {
string path = line.Trim();
if(!line.StartsWith("/")) {
XUri uri = new XUri(path);
path = uri.Path;
if(StringUtil.EqualsInvariantIgnoreCase("/index.php", path)) {
path = uri.GetParam("title");
}
}
exportDoc.Start("page")
.Attr("path", Title.FromUIUri(null, path).AsPrefixedDbPath())
.Attr("recursive", _exportRecursive)
.End();
} catch(Exception) {
throw new ConfigurationException("Unable to parse uri: {0}", line.Trim());
}
}
return exportDoc;
}
private XDoc LoadExportDocumentFromFile(string exportDocumentPath) {
if(!File.Exists(exportDocumentPath)) {
throw new ConfigurationException("No such export document: {0}", exportDocumentPath);
}
try {
return XDocFactory.LoadFrom(exportDocumentPath, MimeType.TEXT_XML);
} catch(Exception e) {
throw new ConfigurationException("Unable to load '{0}': {1}", exportDocumentPath, e.Message);
}
}
private List<string> ConfigureFromXml(string configFile) {
if(!File.Exists(configFile)) {
throw new ConfigurationException("No such config file: {0}", configFile);
}
XDoc config = null;
try {
config = XDocFactory.LoadFrom(configFile, MimeType.TEXT_XML);
} catch(Exception e) {
throw new ConfigurationException("Unable to load '{0}': {1}", configFile, e.Message);
}
List<string> extraOpts = new List<string>();
foreach(string flagPath in new string[] { "export", "copy", "archive", "recursive" }) {
XDoc flag = config["@" + flagPath];
if(!flag.IsEmpty && (flag.AsBool ?? false)) {
extraOpts.Add("-" + flagPath);
}
}
foreach(string argPath in new string[] { "host", "uri", "importreltopath", "importrelto", "exportreltopath", "exportrelto", "exportdoc", "exportpath", "exportlist", "authtoken", "user", "password" }) {
string opt = config["@" + argPath].AsText;
if(string.IsNullOrEmpty(opt)) {
continue;
}
extraOpts.Add("-" + argPath);
extraOpts.Add(opt);
}
XDoc export = config["export"];
if(!export.IsEmpty) {
ExportDocument = export;
}
XDoc target = config["target"];
if(!target.IsEmpty) {
FilePath = target.AsText;
}
return extraOpts;
}
public void WriteConfig() {
XDoc exportDocument = new XDoc("config")
.Attr("archive", Archive)
.Add(ExportDocument);
switch(Mode) {
case Mode.Export:
exportDocument.Attr("export", true);
break;
case Mode.Copy:
exportDocument.Attr("copy", true);
break;
}
if(DekiApi != null) {
exportDocument.Attr("uri", DekiApi.Uri);
}
if(!string.IsNullOrEmpty(User)) {
exportDocument.Attr("user", User);
}
if(!string.IsNullOrEmpty(Password)) {
exportDocument.Attr("password", Password);
}
if(!string.IsNullOrEmpty(AuthToken)) {
exportDocument.Attr("authtoken", AuthToken);
}
if(!string.IsNullOrEmpty(FilePath)) {
exportDocument.Elem("target", FilePath);
}
if(Mode != Import.Mode.Export && !string.IsNullOrEmpty(ImportReltoPath)) {
exportDocument.Attr("importreltopath", ImportReltoPath);
}
if(Mode != Import.Mode.Import && !string.IsNullOrEmpty(ExportReltoPath)) {
exportDocument.Attr("exportreltopath", ExportReltoPath);
}
if(ImportRelto.HasValue) {
exportDocument.Attr("importrelto", ImportRelto.Value);
}
if(ExportRelto.HasValue) {
exportDocument.Attr("exportrelto", ExportRelto.Value);
}
string dir = Path.GetDirectoryName(Path.GetFullPath(_genConfigPath));
if(!Directory.Exists(dir)) {
Directory.CreateDirectory(dir);
}
exportDocument.Save(_genConfigPath);
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using HETSAPI.Models;
namespace HETSAPI.ViewModels
{
/// <summary>
/// Rental Agreement Pdf View Model
/// </summary>
[DataContract]
public sealed class RentalAgreementPdfViewModel : IEquatable<RentalAgreementPdfViewModel>
{
/// <summary>
/// /// Rental Agreement Pdf View Model Constructor
/// </summary>
public RentalAgreementPdfViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RentalAgreementPdfViewModel" /> class.
/// </summary>
/// <param name="id">Id (required).</param>
/// <param name="number">A system-generated unique rental agreement number in a format defined by the business as suitable for the business and client to see and use.</param>
/// <param name="status">The current status of the Rental Agreement, such as Active or Complete.</param>
/// <param name="equipment">A foreign key reference to the system-generated unique identifier for an Equipment.</param>
/// <param name="project">A foreign key reference to the system-generated unique identifier for a Project.</param>
/// <param name="rentalAgreementRates">RentalAgreementRates.</param>
/// <param name="rentalAgreementConditions">RentalAgreementConditions.</param>
/// <param name="note">An optional note to be placed onto the Rental Agreement.</param>
/// <param name="estimateStartWork">The estimated start date of the work to be placed on the rental agreement.</param>
/// <param name="datedOn">The dated on date to put on the Rental Agreement.</param>
/// <param name="estimateHours">The estimated number of hours of work to be put onto the Rental Agreement.</param>
/// <param name="equipmentRate">The dollar rate for the piece of equipment itself for this Rental Agreement. Other rates associated with the Rental Agreement are in the Rental Agreement Rate table.</param>
/// <param name="ratePeriod">The period of the rental rate. The vast majority will be hourly, but the rate could apply across a different period, e.g. daily.</param>
/// <param name="rateComment">A comment about the rate for the piece of equipment.</param>
/// <param name="conditionsPresent">Are there any conditions in this agreement</param>
public RentalAgreementPdfViewModel(int id, string number = null, string status = null, Equipment equipment = null,
Project project = null, List<RentalAgreementRate> rentalAgreementRates = null,
List<RentalAgreementCondition> rentalAgreementConditions = null,
string note = null, string estimateStartWork = null, string datedOn = null, int? estimateHours = null,
float? equipmentRate = null, string ratePeriod = null, string rateComment = null, bool conditionsPresent = false)
{
Id = id;
Number = number;
Status = status;
Equipment = equipment;
Project = project;
RentalAgreementRates = rentalAgreementRates;
RentalAgreementConditions = rentalAgreementConditions;
Note = note;
EstimateStartWork = estimateStartWork;
DatedOn = datedOn;
EstimateHours = estimateHours;
EquipmentRate = equipmentRate;
RatePeriod = ratePeriod;
RateComment = rateComment;
ConditionsPresent = conditionsPresent;
}
/// <summary>
/// Look for "Other" and replace with Comment text
/// </summary>
public void FixOther()
{
foreach (RentalAgreementRate rentalRate in RentalAgreementRatesWithTotal)
{
if (rentalRate.ComponentName.Equals("Other", StringComparison.InvariantCultureIgnoreCase))
{
rentalRate.ComponentName = rentalRate.Comment;
rentalRate.Comment = "";
}
}
foreach (RentalAgreementRate rentalRate in RentalAgreementRatesWithoutTotal)
{
if (rentalRate.ComponentName.Equals("Other", StringComparison.InvariantCultureIgnoreCase))
{
rentalRate.ComponentName = rentalRate.Comment;
rentalRate.Comment = "";
}
}
foreach (RentalAgreementCondition condition in RentalAgreementConditions)
{
if (condition.ConditionName.Equals("Other", StringComparison.InvariantCultureIgnoreCase))
{
condition.ConditionName = condition.Comment;
condition.Comment = "";
}
}
}
/// <summary>
/// Uses the rates data to calculate the totals and setup the required data for printing
/// </summary>
public void CalculateTotals()
{
// **********************************************
// setup the rates lists ->
// 1. overtime records
// 2. records in the total and
// 3. records not included
// **********************************************
RentalAgreementRatesOvertime = RentalAgreementRates
.FindAll(x => x.ComponentName.StartsWith("Overtime", true, CultureInfo.InvariantCulture))
.OrderBy(x => x.Id).ToList();
RentalAgreementRatesWithTotal = RentalAgreementRates
.FindAll(x => x.IsIncludedInTotal &&
!x.ComponentName.StartsWith("Overtime", true, CultureInfo.InvariantCulture))
.OrderBy(x => x.Id).ToList();
RentalAgreementRatesWithoutTotal = RentalAgreementRates
.FindAll(x => !x.IsIncludedInTotal &&
!x.ComponentName.StartsWith("Overtime", true, CultureInfo.InvariantCulture))
.OrderBy(x => x.Id).ToList();
// **********************************************
// calculate the total
// **********************************************
float temp = 0.0F;
foreach (RentalAgreementRate rentalRate in RentalAgreementRatesWithTotal)
{
if (rentalRate.PercentOfEquipmentRate != null &&
EquipmentRate != null &&
rentalRate.PercentOfEquipmentRate > 0)
{
rentalRate.Rate = (float)rentalRate.PercentOfEquipmentRate * ((float)EquipmentRate / 100);
temp = temp + (float)rentalRate.Rate;
}
else if (rentalRate.Rate != null)
{
temp = temp + (float)rentalRate.Rate;
}
// format the rate / percent at the same time
rentalRate.RateString = FormatRateString(rentalRate);
}
// add the base amount to the total too
if (EquipmentRate != null)
{
temp = temp + (float)EquipmentRate;
}
AgreementTotal = temp;
// format the base rate
BaseRateString = string.Format("$ {0:0.00} / {1}", EquipmentRate, FormatRatePeriod(RatePeriod));
// format the total
AgreementTotalString = string.Format("$ {0:0.00} / {1}", AgreementTotal, FormatRatePeriod(RatePeriod));
// **********************************************
// format the rate / percent values
// **********************************************
foreach (RentalAgreementRate rentalRate in RentalAgreementRatesOvertime)
{
if (rentalRate.PercentOfEquipmentRate != null &&
EquipmentRate != null &&
rentalRate.PercentOfEquipmentRate > 0)
{
rentalRate.Rate = (float)rentalRate.PercentOfEquipmentRate * ((float)EquipmentRate / 100);
}
rentalRate.RateString = FormatRateString(rentalRate);
}
foreach (RentalAgreementRate rentalRate in RentalAgreementRatesWithoutTotal)
{
if (rentalRate.PercentOfEquipmentRate != null &&
EquipmentRate != null &&
rentalRate.PercentOfEquipmentRate > 0)
{
rentalRate.Rate = (float)rentalRate.PercentOfEquipmentRate * ((float)EquipmentRate / 100);
}
rentalRate.RateString = FormatRateString(rentalRate);
}
}
private static string FormatRatePeriod(string period)
{
if (!string.IsNullOrEmpty(period))
{
switch (period.ToLower())
{
case "daily":
case "dy":
return "Dy";
case "hourly":
case "hr":
return "Hr";
}
}
else
{
period = "";
}
return period;
}
private static string FormatRateString(RentalAgreementRate rentalRate)
{
string temp = "";
// format the rate
if (rentalRate.Rate != null)
{
temp = string.Format("$ {0:0.00} / {1}", rentalRate.Rate, FormatRatePeriod(rentalRate.RatePeriod));
}
// format the percent
if (rentalRate.PercentOfEquipmentRate != null &&
rentalRate.PercentOfEquipmentRate > 0)
{
temp = string.Format("({0:0.00}%) ", rentalRate.PercentOfEquipmentRate) + temp;
}
return temp;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id")]
public int Id { get; set; }
/// <summary>
/// A system-generated unique rental agreement number in a format defined by the business as suitable for the business and client to see and use.
/// </summary>
/// <value>A system-generated unique rental agreement number in a format defined by the business as suitable for the business and client to see and use.</value>
[DataMember(Name="number")]
[MetaData (Description = "A system-generated unique rental agreement number in a format defined by the business as suitable for the business and client to see and use.")]
public string Number { get; set; }
/// <summary>
/// The current status of the Rental Agreement, such as Active or Complete
/// </summary>
/// <value>The current status of the Rental Agreement, such as Active or Complete</value>
[DataMember(Name="status")]
[MetaData (Description = "The current status of the Rental Agreement, such as Active or Complete")]
public string Status { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for an Equipment
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for an Equipment</value>
[DataMember(Name="equipment")]
[MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Equipment")]
public Equipment Equipment { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for a Project
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for a Project</value>
[DataMember(Name="project")]
[MetaData (Description = "A foreign key reference to the system-generated unique identifier for a Project")]
public Project Project { get; set; }
/// <summary>
/// Gets or Sets RentalAgreementRates
/// </summary>
[DataMember(Name="rentalAgreementRates")]
public List<RentalAgreementRate> RentalAgreementRates { get; set; }
/// <summary>
/// Gets or Sets RentalAgreementRates -> that are included in the total
/// </summary>
[DataMember(Name = "rentalAgreementRatesWithTotal")]
public List<RentalAgreementRate> RentalAgreementRatesWithTotal { get; set; }
/// <summary>
/// Gets or Sets RentalAgreementRates -> that are included in the total
/// </summary>
[DataMember(Name = "rentalAgreementRatesOvertime")]
public List<RentalAgreementRate> RentalAgreementRatesOvertime { get; set; }
/// <summary>
/// The dollar total -> for all included rental agreement rate records
/// </summary>
[DataMember(Name = "agreementTotal")]
public float? AgreementTotal { get; set; }
/// <summary>
/// Used for the Pdf only (formatted version of the agreement total ($))
/// </summary>
[DataMember(Name = "agreementTotalString")]
public string AgreementTotalString { get; set; }
/// <summary>
/// Used for the Pdf only (formatted version of the base rate ($))
/// </summary>
[DataMember(Name = "baseRateString")]
public string BaseRateString { get; set; }
/// <summary>
/// Gets or Sets RentalAgreementRates -> that aren't included in the total
/// </summary>
[DataMember(Name = "rentalAgreementRatesWithoutTotal")]
public List<RentalAgreementRate> RentalAgreementRatesWithoutTotal { get; set; }
/// <summary>
/// Gets or Sets RentalAgreementConditions
/// </summary>
[DataMember(Name="rentalAgreementConditions")]
public List<RentalAgreementCondition> RentalAgreementConditions { get; set; }
/// <summary>
/// An optional note to be placed onto the Rental Agreement.
/// </summary>
/// <value>An optional note to be placed onto the Rental Agreement.</value>
[DataMember(Name="note")]
[MetaData (Description = "An optional note to be placed onto the Rental Agreement.")]
public string Note { get; set; }
/// <summary>
/// The estimated start date of the work to be placed on the rental agreement.
/// </summary>
/// <value>The estimated start date of the work to be placed on the rental agreement.</value>
[DataMember(Name="estimateStartWork")]
[MetaData (Description = "The estimated start date of the work to be placed on the rental agreement.")]
public string EstimateStartWork { get; set; }
/// <summary>
/// The dated on date to put on the Rental Agreement.
/// </summary>
/// <value>The dated on date to put on the Rental Agreement.</value>
[DataMember(Name="datedOn")]
[MetaData (Description = "The dated on date to put on the Rental Agreement.")]
public string DatedOn { get; set; }
/// <summary>
/// The estimated number of hours of work to be put onto the Rental Agreement.
/// </summary>
/// <value>The estimated number of hours of work to be put onto the Rental Agreement.</value>
[DataMember(Name="estimateHours")]
[MetaData (Description = "The estimated number of hours of work to be put onto the Rental Agreement.")]
public int? EstimateHours { get; set; }
/// <summary>
/// The dollar rate for the piece of equipment itself for this Rental Agreement. Other rates associated with the Rental Agreement are in the Rental Agreement Rate table.
/// </summary>
/// <value>The dollar rate for the piece of equipment itself for this Rental Agreement. Other rates associated with the Rental Agreement are in the Rental Agreement Rate table.</value>
[DataMember(Name="equipmentRate")]
[MetaData (Description = "The dollar rate for the piece of equipment itself for this Rental Agreement. Other rates associated with the Rental Agreement are in the Rental Agreement Rate table.")]
public float? EquipmentRate { get; set; }
/// <summary>
/// The period of the rental rate. The vast majority will be hourly, but the rate could apply across a different period, e.g. daily.
/// </summary>
/// <value>The period of the rental rate. The vast majority will be hourly, but the rate could apply across a different period, e.g. daily.</value>
[DataMember(Name="ratePeriod")]
[MetaData (Description = "The period of the rental rate. The vast majority will be hourly, but the rate could apply across a different period, e.g. daily.")]
public string RatePeriod { get; set; }
/// <summary>
/// A comment about the rate for the piece of equipment.
/// </summary>
/// <value>A comment about the rate for the piece of equipment.</value>
[DataMember(Name="rateComment")]
[MetaData (Description = "A comment about the rate for the piece of equipment.")]
public string RateComment { get; set; }
/// <summary>
/// Are there any conditions in this agreement
/// </summary>
/// <value>Are there any conditions in this agreement</value>
[DataMember(Name = "conditionsPresent")]
[MetaData(Description = "Are there any conditions in this agreement.")]
public bool ConditionsPresent { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RentalAgreementPdfViewModel {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Number: ").Append(Number).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Equipment: ").Append(Equipment).Append("\n");
sb.Append(" Project: ").Append(Project).Append("\n");
sb.Append(" RentalAgreementRates: ").Append(RentalAgreementRates).Append("\n");
sb.Append(" RentalAgreementRatesWithTotal: ").Append(RentalAgreementRatesWithTotal).Append("\n");
sb.Append(" AgreementTotal: ").Append(AgreementTotal).Append("\n");
sb.Append(" RentalAgreementRatesWithoutTotal: ").Append(RentalAgreementRatesWithoutTotal).Append("\n");
sb.Append(" RentalAgreementConditions: ").Append(RentalAgreementConditions).Append("\n");
sb.Append(" Note: ").Append(Note).Append("\n");
sb.Append(" EstimateStartWork: ").Append(EstimateStartWork).Append("\n");
sb.Append(" DatedOn: ").Append(DatedOn).Append("\n");
sb.Append(" EstimateHours: ").Append(EstimateHours).Append("\n");
sb.Append(" EquipmentRate: ").Append(EquipmentRate).Append("\n");
sb.Append(" RatePeriod: ").Append(RatePeriod).Append("\n");
sb.Append(" RateComment: ").Append(RateComment).Append("\n");
sb.Append(" ConditionsPresent: ").Append(ConditionsPresent).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((RentalAgreementPdfViewModel)obj);
}
/// <summary>
/// Returns true if RentalAgreementPdfViewModel instances are equal
/// </summary>
/// <param name="other">Instance of RentalAgreementPdfViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RentalAgreementPdfViewModel other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
Id == other.Id ||
Id.Equals(other.Id)
) &&
(
Number == other.Number ||
Number != null &&
Number.Equals(other.Number)
) &&
(
Status == other.Status ||
Status != null &&
Status.Equals(other.Status)
) &&
(
Equipment == other.Equipment ||
Equipment != null &&
Equipment.Equals(other.Equipment)
) &&
(
Project == other.Project ||
Project != null &&
Project.Equals(other.Project)
) &&
(
RentalAgreementRates == other.RentalAgreementRates ||
RentalAgreementRates != null &&
RentalAgreementRates.SequenceEqual(other.RentalAgreementRates)
) &&
(
RentalAgreementRatesWithTotal == other.RentalAgreementRatesWithTotal ||
RentalAgreementRatesWithTotal != null &&
RentalAgreementRatesWithTotal.SequenceEqual(other.RentalAgreementRatesWithTotal)
) &&
(
AgreementTotal == other.AgreementTotal ||
AgreementTotal != null &&
AgreementTotal.Equals(other.AgreementTotal)
) &&
(
RentalAgreementRatesWithoutTotal == other.RentalAgreementRatesWithoutTotal ||
RentalAgreementRatesWithoutTotal != null &&
RentalAgreementRates.SequenceEqual(other.RentalAgreementRatesWithoutTotal)
) &&
(
RentalAgreementConditions == other.RentalAgreementConditions ||
RentalAgreementConditions != null &&
RentalAgreementConditions.SequenceEqual(other.RentalAgreementConditions)
) &&
(
Note == other.Note ||
Note != null &&
Note.Equals(other.Note)
) &&
(
EstimateStartWork == other.EstimateStartWork ||
EstimateStartWork != null &&
EstimateStartWork.Equals(other.EstimateStartWork)
) &&
(
DatedOn == other.DatedOn ||
DatedOn != null &&
DatedOn.Equals(other.DatedOn)
) &&
(
EstimateHours == other.EstimateHours ||
EstimateHours != null &&
EstimateHours.Equals(other.EstimateHours)
) &&
(
EquipmentRate == other.EquipmentRate ||
EquipmentRate != null &&
EquipmentRate.Equals(other.EquipmentRate)
) &&
(
RatePeriod == other.RatePeriod ||
RatePeriod != null &&
RatePeriod.Equals(other.RatePeriod)
) &&
(
RateComment == other.RateComment ||
RateComment != null &&
RateComment.Equals(other.RateComment)
) &&
(
ConditionsPresent == other.ConditionsPresent ||
ConditionsPresent.Equals(other.ConditionsPresent)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + Id.GetHashCode();
if (Number != null)
{
hash = hash * 59 + Number.GetHashCode();
}
if (Status != null)
{
hash = hash * 59 + Status.GetHashCode();
}
if (Equipment != null)
{
hash = hash * 59 + Equipment.GetHashCode();
}
if (Project != null)
{
hash = hash * 59 + Project.GetHashCode();
}
if (RentalAgreementRates != null)
{
hash = hash * 59 + RentalAgreementRates.GetHashCode();
}
if (RentalAgreementRatesWithTotal != null)
{
hash = hash * 59 + RentalAgreementRatesWithTotal.GetHashCode();
}
if (RentalAgreementRatesWithoutTotal != null)
{
hash = hash * 59 + RentalAgreementRatesWithoutTotal.GetHashCode();
}
if (RentalAgreementConditions != null)
{
hash = hash * 59 + RentalAgreementConditions.GetHashCode();
}
if (Note != null)
{
hash = hash * 59 + Note.GetHashCode();
}
if (EstimateStartWork != null)
{
hash = hash * 59 + EstimateStartWork.GetHashCode();
}
if (DatedOn != null)
{
hash = hash * 59 + DatedOn.GetHashCode();
}
if (EstimateHours != null)
{
hash = hash * 59 + EstimateHours.GetHashCode();
}
if (EquipmentRate != null)
{
hash = hash * 59 + EquipmentRate.GetHashCode();
}
if (RatePeriod != null)
{
hash = hash * 59 + RatePeriod.GetHashCode();
}
if (RateComment != null)
{
hash = hash * 59 + RateComment.GetHashCode();
}
hash = hash * 59 + ConditionsPresent.GetHashCode();
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(RentalAgreementPdfViewModel left, RentalAgreementPdfViewModel right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(RentalAgreementPdfViewModel left, RentalAgreementPdfViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
internal class ReaderOutput : XmlReader, RecordOutput
{
private Processor _processor;
private XmlNameTable _nameTable;
// Main node + Fields Collection
private RecordBuilder _builder;
private BuilderInfo _mainNode;
private ArrayList _attributeList;
private int _attributeCount;
private BuilderInfo _attributeValue;
// OutputScopeManager
private OutputScopeManager _manager;
// Current position in the list
private int _currentIndex;
private BuilderInfo _currentInfo;
// Reader state
private ReadState _state = ReadState.Initial;
private bool _haveRecord;
// Static default record
private static BuilderInfo s_DefaultInfo = new BuilderInfo();
private XmlEncoder _encoder = new XmlEncoder();
private XmlCharType _xmlCharType = XmlCharType.Instance;
internal ReaderOutput(Processor processor)
{
Debug.Assert(processor != null);
Debug.Assert(processor.NameTable != null);
_processor = processor;
_nameTable = processor.NameTable;
Reset();
}
// XmlReader abstract methods implementation
public override XmlNodeType NodeType
{
get
{
CheckCurrentInfo();
return _currentInfo.NodeType;
}
}
public override string Name
{
get
{
CheckCurrentInfo();
string prefix = Prefix;
string localName = LocalName;
if (prefix != null && prefix.Length > 0)
{
if (localName.Length > 0)
{
return _nameTable.Add(prefix + ":" + localName);
}
else
{
return prefix;
}
}
else
{
return localName;
}
}
}
public override string LocalName
{
get
{
CheckCurrentInfo();
return _currentInfo.LocalName;
}
}
public override string NamespaceURI
{
get
{
CheckCurrentInfo();
return _currentInfo.NamespaceURI;
}
}
public override string Prefix
{
get
{
CheckCurrentInfo();
return _currentInfo.Prefix;
}
}
public override bool HasValue
{
get
{
return XmlReader.HasValueInternal(NodeType);
}
}
public override string Value
{
get
{
CheckCurrentInfo();
return _currentInfo.Value;
}
}
public override int Depth
{
get
{
CheckCurrentInfo();
return _currentInfo.Depth;
}
}
public override string BaseURI
{
get
{
return string.Empty;
}
}
public override bool IsEmptyElement
{
get
{
CheckCurrentInfo();
return _currentInfo.IsEmptyTag;
}
}
public override char QuoteChar
{
get { return _encoder.QuoteChar; }
}
public override bool IsDefault
{
get { return false; }
}
public override XmlSpace XmlSpace
{
get { return _manager != null ? _manager.XmlSpace : XmlSpace.None; }
}
public override string XmlLang
{
get { return _manager != null ? _manager.XmlLang : string.Empty; }
}
// Attribute Accessors
public override int AttributeCount
{
get { return _attributeCount; }
}
public override string GetAttribute(string name)
{
int ordinal;
if (FindAttribute(name, out ordinal))
{
Debug.Assert(ordinal >= 0);
return ((BuilderInfo)_attributeList[ordinal]).Value;
}
else
{
Debug.Assert(ordinal == -1);
return null;
}
}
public override string GetAttribute(string localName, string namespaceURI)
{
int ordinal;
if (FindAttribute(localName, namespaceURI, out ordinal))
{
Debug.Assert(ordinal >= 0);
return ((BuilderInfo)_attributeList[ordinal]).Value;
}
else
{
Debug.Assert(ordinal == -1);
return null;
}
}
public override string GetAttribute(int i)
{
BuilderInfo attribute = GetBuilderInfo(i);
return attribute.Value;
}
public override string this[int i]
{
get { return GetAttribute(i); }
}
public override string this[string name]
{
get { return GetAttribute(name); }
}
public override string this[string name, string namespaceURI]
{
get { return GetAttribute(name, namespaceURI); }
}
public override bool MoveToAttribute(string name)
{
int ordinal;
if (FindAttribute(name, out ordinal))
{
Debug.Assert(ordinal >= 0);
SetAttribute(ordinal);
return true;
}
else
{
Debug.Assert(ordinal == -1);
return false;
}
}
public override bool MoveToAttribute(string localName, string namespaceURI)
{
int ordinal;
if (FindAttribute(localName, namespaceURI, out ordinal))
{
Debug.Assert(ordinal >= 0);
SetAttribute(ordinal);
return true;
}
else
{
Debug.Assert(ordinal == -1);
return false;
}
}
public override void MoveToAttribute(int i)
{
if (i < 0 || _attributeCount <= i)
{
throw new ArgumentOutOfRangeException(nameof(i));
}
SetAttribute(i);
}
public override bool MoveToFirstAttribute()
{
if (_attributeCount <= 0)
{
Debug.Assert(_attributeCount == 0);
return false;
}
else
{
SetAttribute(0);
return true;
}
}
public override bool MoveToNextAttribute()
{
if (_currentIndex + 1 < _attributeCount)
{
SetAttribute(_currentIndex + 1);
return true;
}
return false;
}
public override bool MoveToElement()
{
if (NodeType == XmlNodeType.Attribute || _currentInfo == _attributeValue)
{
SetMainNode();
return true;
}
return false;
}
// Moving through the Stream
public override bool Read()
{
Debug.Assert(_processor != null || _state == ReadState.Closed);
if (_state != ReadState.Interactive)
{
if (_state == ReadState.Initial)
{
_state = ReadState.Interactive;
}
else
{
return false;
}
}
while (true)
{ // while -- to ignor empty whitespace nodes.
if (_haveRecord)
{
_processor.ResetOutput();
_haveRecord = false;
}
_processor.Execute();
if (_haveRecord)
{
CheckCurrentInfo();
// check text nodes on whitespaces;
switch (this.NodeType)
{
case XmlNodeType.Text:
if (_xmlCharType.IsOnlyWhitespace(this.Value))
{
_currentInfo.NodeType = XmlNodeType.Whitespace;
goto case XmlNodeType.Whitespace;
}
Debug.Assert(this.Value.Length != 0, "It whould be Whitespace in this case");
break;
case XmlNodeType.Whitespace:
if (this.Value.Length == 0)
{
continue; // ignoring emty text nodes
}
if (this.XmlSpace == XmlSpace.Preserve)
{
_currentInfo.NodeType = XmlNodeType.SignificantWhitespace;
}
break;
}
}
else
{
Debug.Assert(_processor.ExecutionDone);
_state = ReadState.EndOfFile;
Reset();
}
return _haveRecord;
}
}
public override bool EOF
{
get { return _state == ReadState.EndOfFile; }
}
public override void Close()
{
_processor = null;
_state = ReadState.Closed;
Reset();
}
public override ReadState ReadState
{
get { return _state; }
}
// Whole Content Read Methods
public override string ReadString()
{
string result = string.Empty;
if (NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || _currentInfo == _attributeValue)
{
if (_mainNode.IsEmptyTag)
{
return result;
}
if (!Read())
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
StringBuilder sb = null;
bool first = true;
while (true)
{
switch (NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
// case XmlNodeType.CharacterEntity:
if (first)
{
result = this.Value;
first = false;
}
else
{
if (sb == null)
{
sb = new StringBuilder(result);
}
sb.Append(this.Value);
}
if (!Read())
throw new InvalidOperationException(SR.Xml_InvalidOperation);
break;
default:
return (sb == null) ? result : sb.ToString();
}
}
}
public override string ReadInnerXml()
{
if (ReadState == ReadState.Interactive)
{
if (NodeType == XmlNodeType.Element && !IsEmptyElement)
{
StringOutput output = new StringOutput(_processor);
output.OmitXmlDecl();
int depth = Depth;
Read(); // skeep begin Element
while (depth < Depth)
{ // process content
Debug.Assert(_builder != null);
output.RecordDone(_builder);
Read();
}
Debug.Assert(NodeType == XmlNodeType.EndElement);
Read(); // skeep end element
output.TheEnd();
return output.Result;
}
else if (NodeType == XmlNodeType.Attribute)
{
return _encoder.AtributeInnerXml(Value);
}
else
{
Read();
}
}
return string.Empty;
}
public override string ReadOuterXml()
{
if (ReadState == ReadState.Interactive)
{
if (NodeType == XmlNodeType.Element)
{
StringOutput output = new StringOutput(_processor);
output.OmitXmlDecl();
bool emptyElement = IsEmptyElement;
int depth = Depth;
// process current record
output.RecordDone(_builder);
Read();
// process internal elements & text nodes
while (depth < Depth)
{
Debug.Assert(_builder != null);
output.RecordDone(_builder);
Read();
}
// process end element
if (!emptyElement)
{
output.RecordDone(_builder);
Read();
}
output.TheEnd();
return output.Result;
}
else if (NodeType == XmlNodeType.Attribute)
{
return _encoder.AtributeOuterXml(Name, Value);
}
else
{
Read();
}
}
return string.Empty;
}
//
// Nametable and Namespace Helpers
//
public override XmlNameTable NameTable
{
get
{
Debug.Assert(_nameTable != null);
return _nameTable;
}
}
public override string LookupNamespace(string prefix)
{
prefix = _nameTable.Get(prefix);
if (_manager != null && prefix != null)
{
return _manager.ResolveNamespace(prefix);
}
return null;
}
public override void ResolveEntity()
{
Debug.Assert(NodeType != XmlNodeType.EntityReference);
if (NodeType != XmlNodeType.EntityReference)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
public override bool ReadAttributeValue()
{
if (ReadState != ReadState.Interactive || NodeType != XmlNodeType.Attribute)
{
return false;
}
if (_attributeValue == null)
{
_attributeValue = new BuilderInfo();
_attributeValue.NodeType = XmlNodeType.Text;
}
if (_currentInfo == _attributeValue)
{
return false;
}
_attributeValue.Value = _currentInfo.Value;
_attributeValue.Depth = _currentInfo.Depth + 1;
_currentInfo = _attributeValue;
return true;
}
//
// RecordOutput interface method implementation
//
public Processor.OutputResult RecordDone(RecordBuilder record)
{
_builder = record;
_mainNode = record.MainNode;
_attributeList = record.AttributeList;
_attributeCount = record.AttributeCount;
_manager = record.Manager;
_haveRecord = true;
SetMainNode();
return Processor.OutputResult.Interrupt;
}
public void TheEnd()
{
// nothing here, was taken care of by RecordBuilder
}
//
// Implementation internals
//
private void SetMainNode()
{
_currentIndex = -1;
_currentInfo = _mainNode;
}
private void SetAttribute(int attrib)
{
Debug.Assert(0 <= attrib && attrib < _attributeCount);
Debug.Assert(0 <= attrib && attrib < _attributeList.Count);
Debug.Assert(_attributeList[attrib] is BuilderInfo);
_currentIndex = attrib;
_currentInfo = (BuilderInfo)_attributeList[attrib];
}
private BuilderInfo GetBuilderInfo(int attrib)
{
if (attrib < 0 || _attributeCount <= attrib)
{
throw new ArgumentOutOfRangeException(nameof(attrib));
}
Debug.Assert(_attributeList[attrib] is BuilderInfo);
return (BuilderInfo)_attributeList[attrib];
}
private bool FindAttribute(String localName, String namespaceURI, out int attrIndex)
{
if (namespaceURI == null)
{
namespaceURI = string.Empty;
}
if (localName == null)
{
localName = string.Empty;
}
for (int index = 0; index < _attributeCount; index++)
{
Debug.Assert(_attributeList[index] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)_attributeList[index];
if (attribute.NamespaceURI == namespaceURI && attribute.LocalName == localName)
{
attrIndex = index;
return true;
}
}
attrIndex = -1;
return false;
}
private bool FindAttribute(String name, out int attrIndex)
{
if (name == null)
{
name = string.Empty;
}
for (int index = 0; index < _attributeCount; index++)
{
Debug.Assert(_attributeList[index] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)_attributeList[index];
if (attribute.Name == name)
{
attrIndex = index;
return true;
}
}
attrIndex = -1;
return false;
}
private void Reset()
{
_currentIndex = -1;
_currentInfo = s_DefaultInfo;
_mainNode = s_DefaultInfo;
_manager = null;
}
[System.Diagnostics.Conditional("DEBUG")]
private void CheckCurrentInfo()
{
Debug.Assert(_currentInfo != null);
Debug.Assert(_attributeCount == 0 || _attributeList != null);
Debug.Assert((_currentIndex == -1) == (_currentInfo == _mainNode));
Debug.Assert((_currentIndex == -1) || (_currentInfo == _attributeValue || _attributeList[_currentIndex] is BuilderInfo && _attributeList[_currentIndex] == _currentInfo));
}
private class XmlEncoder
{
private StringBuilder _buffer = null;
private XmlTextEncoder _encoder = null;
private void Init()
{
_buffer = new StringBuilder();
_encoder = new XmlTextEncoder(new StringWriter(_buffer, CultureInfo.InvariantCulture));
}
public string AtributeInnerXml(string value)
{
if (_encoder == null) Init();
_buffer.Length = 0; // clean buffer
_encoder.StartAttribute(/*save:*/false);
_encoder.Write(value);
_encoder.EndAttribute();
return _buffer.ToString();
}
public string AtributeOuterXml(string name, string value)
{
if (_encoder == null) Init();
_buffer.Length = 0; // clean buffer
_buffer.Append(name);
_buffer.Append('=');
_buffer.Append(QuoteChar);
_encoder.StartAttribute(/*save:*/false);
_encoder.Write(value);
_encoder.EndAttribute();
_buffer.Append(QuoteChar);
return _buffer.ToString();
}
public char QuoteChar
{
get { return '"'; }
}
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System.IO;
using EventStore.Core.Exceptions;
using EventStore.Core.TransactionLog.Checkpoint;
using EventStore.Core.TransactionLog.Chunks;
using EventStore.Core.TransactionLog.FileNamingStrategy;
using NUnit.Framework;
namespace EventStore.Core.Tests.TransactionLog.Validation
{
[TestFixture]
public class when_validating_tfchunk_db : SpecificationWithDirectory
{
[Test]
public void with_file_of_wrong_size_database_corruption_is_detected()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(500),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
File.WriteAllText(GetFilePathFor("chunk-000000.000000"), "this is just some test blahbydy blah");
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test]
public void with_not_enough_files_to_reach_checksum_throws()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(15000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<ChunkNotFoundException>());
}
}
[Test]
public void allows_with_exactly_enough_file_to_reach_checksum()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(10000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
}
}
[Test]
public void does_not_allow_not_completed_not_last_chunks()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
1000,
0,
new InMemoryCheckpoint(4000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateOngoingChunk(config, 1, GetFilePathFor("chunk-000001.000000"));
DbUtil.CreateOngoingChunk(config, 2, GetFilePathFor("chunk-000002.000000"));
DbUtil.CreateOngoingChunk(config, 3, GetFilePathFor("chunk-000003.000000"));
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test]
public void allows_next_new_chunk_when_checksum_is_exactly_in_between_two_chunks()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(10000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateOngoingChunk(config, 1, GetFilePathFor("chunk-000001.000000"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
}
}
[Test, Ignore("Due to truncation such situation can happen, so must be considered valid.")]
public void does_not_allow_next_new_completed_chunk_when_checksum_is_exactly_in_between_two_chunks()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(10000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000000"));
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test]
public void allows_last_chunk_to_be_not_completed_when_checksum_is_exactly_in_between_two_chunks_and_no_next_chunk_exists()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(10000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateOngoingChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
}
}
[Test]
public void does_not_allow_pre_last_chunk_to_be_not_completed_when_checksum_is_exactly_in_between_two_chunks_and_next_chunk_exists()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(10000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateOngoingChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateOngoingChunk(config, 1, GetFilePathFor("chunk-000001.000000"));
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test, Ignore("Not valid test now after disabling size validation on ongoing TFChunk ")]
public void with_wrong_size_file_less_than_checksum_throws()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(15000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000000"), actualDataSize: config.ChunkSize - 1000);
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test]
public void when_in_first_extraneous_files_throws_corrupt_database_exception()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(9000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateOngoingChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000000"));
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<ExtraneousFileFoundException>());
}
}
[Test]
public void when_in_multiple_extraneous_files_throws_corrupt_database_exception()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(15000),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateOngoingChunk(config, 1, GetFilePathFor("chunk-000001.000000"));
DbUtil.CreateSingleChunk(config, 2, GetFilePathFor("chunk-000002.000000"));
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<ExtraneousFileFoundException>());
}
}
[Test]
public void when_in_brand_new_extraneous_files_throws_corrupt_database_exception()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(0),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 4, GetFilePathFor("chunk-000004.000000"));
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<ExtraneousFileFoundException>());
}
}
[Test]
public void when_a_chaser_checksum_is_ahead_of_writer_checksum_throws_corrupt_database_exception()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(0),
new InMemoryCheckpoint(11),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<ReaderCheckpointHigherThanWriterException>());
}
}
[Test]
public void when_an_epoch_checksum_is_ahead_of_writer_checksum_throws_corrupt_database_exception()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(0),
new InMemoryCheckpoint(0),
new InMemoryCheckpoint(11),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<ReaderCheckpointHigherThanWriterException>());
}
}
[Test]
public void allows_no_files_when_checkpoint_is_zero()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000000")));
}
}
[Test]
public void allows_first_correct_ongoing_chunk_when_checkpoint_is_zero()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateOngoingChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
}
}
[Test, Ignore("Due to truncation such situation can happen, so must be considered valid.")]
public void does_not_allow_first_completed_chunk_when_checkpoint_is_zero()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
10000,
0,
new InMemoryCheckpoint(),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test]
public void allows_checkpoint_to_point_into_the_middle_of_completed_chunk_when_enough_actual_data_in_chunk()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
1000,
0,
new InMemoryCheckpoint(1500),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"), actualDataSize: 500);
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000000")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000001.000001")));
Assert.AreEqual(2, Directory.GetFiles(PathName, "*").Length);
}
}
[Test, Ignore("We don't check this as it is too erroneous to read ChunkFooter from ongoing chunk...")]
public void does_not_allow_checkpoint_to_point_into_the_middle_of_completed_chunk_when_not_enough_actual_data()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
1000,
0,
new InMemoryCheckpoint(1500),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"), actualDataSize: 499);
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test]
public void does_not_allow_checkpoint_to_point_into_the_middle_of_scavenged_chunk()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
1000,
0,
new InMemoryCheckpoint(1500),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"), isScavenged: true, actualDataSize: 1000);
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test]
public void old_version_of_chunks_are_removed()
{
File.Create(GetFilePathFor("foo")).Close();
File.Create(GetFilePathFor("bla")).Close();
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
100,
0,
new InMemoryCheckpoint(350),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000002"));
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000005"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"));
DbUtil.CreateSingleChunk(config, 2, GetFilePathFor("chunk-000002.000000"));
DbUtil.CreateSingleChunk(config, 3, GetFilePathFor("chunk-000003.000007"));
DbUtil.CreateOngoingChunk(config, 3, GetFilePathFor("chunk-000003.000008"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsTrue(File.Exists(GetFilePathFor("foo")));
Assert.IsTrue(File.Exists(GetFilePathFor("bla")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000005")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000001.000001")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000002.000000")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000003.000008")));
Assert.AreEqual(6, Directory.GetFiles(PathName, "*").Length);
}
}
[Test]
public void when_checkpoint_is_on_boundary_of_chunk_last_chunk_is_preserved()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
100,
0,
new InMemoryCheckpoint(200),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"));
DbUtil.CreateOngoingChunk(config, 2, GetFilePathFor("chunk-000002.000005"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000000")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000001.000001")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000002.000005")));
Assert.AreEqual(3, Directory.GetFiles(PathName, "*").Length);
}
}
[Test]
public void when_checkpoint_is_on_boundary_of_new_chunk_last_chunk_is_preserved_and_excessive_versions_are_removed_if_present()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
100,
0,
new InMemoryCheckpoint(200),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"));
DbUtil.CreateSingleChunk(config, 2, GetFilePathFor("chunk-000002.000000"));
DbUtil.CreateOngoingChunk(config, 2, GetFilePathFor("chunk-000002.000001"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000000")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000001.000001")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000002.000001")));
Assert.AreEqual(3, Directory.GetFiles(PathName, "*").Length);
}
}
[Test]
public void when_checkpoint_is_exactly_on_the_boundary_of_chunk_the_last_chunk_could_be_not_present_but_should_be_created()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
100,
0,
new InMemoryCheckpoint(200),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsNotNull(db.Manager.GetChunk(2));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000000")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000001.000001")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000002.000000")));
Assert.AreEqual(3, Directory.GetFiles(PathName, "*").Length);
}
}
[Test]
public void when_checkpoint_is_exactly_on_the_boundary_of_chunk_the_last_chunk_could_be_present()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
100,
0,
new InMemoryCheckpoint(200),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"));
DbUtil.CreateOngoingChunk(config, 2, GetFilePathFor("chunk-000002.000000"));
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsNotNull(db.Manager.GetChunk(2));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000000")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000001.000001")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000002.000000")));
Assert.AreEqual(3, Directory.GetFiles(PathName, "*").Length);
}
}
[Test]
public void when_checkpoint_is_on_boundary_of_new_chunk_and_last_chunk_is_truncated_no_exception_is_thrown()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
100,
0,
new InMemoryCheckpoint(200),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateSingleChunk(config, 1, GetFilePathFor("chunk-000001.000001"), actualDataSize: config.ChunkSize - 10);
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsNotNull(db.Manager.GetChunk(2));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000000")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000001.000001")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000002.000000")));
Assert.AreEqual(3, Directory.GetFiles(PathName, "*").Length);
}
}
[Test, Ignore("Not valid test now after disabling size validation on ongoing TFChunk ")]
public void when_checkpoint_is_on_boundary_of_new_chunk_and_last_chunk_is_truncated_but_not_completed_exception_is_thrown()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
100,
0,
new InMemoryCheckpoint(200),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateOngoingChunk(config, 1, GetFilePathFor("chunk-000001.000001"), actualSize: config.ChunkSize - 10);
Assert.That(() => db.Open(verifyHash: false),
Throws.Exception.InstanceOf<CorruptDatabaseException>()
.With.InnerException.InstanceOf<BadChunkInDatabaseException>());
}
}
[Test]
public void temporary_files_are_removed()
{
var config = new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
100,
0,
new InMemoryCheckpoint(150),
new InMemoryCheckpoint(),
new InMemoryCheckpoint(-1),
new InMemoryCheckpoint(-1));
using (var db = new TFChunkDb(config))
{
DbUtil.CreateSingleChunk(config, 0, GetFilePathFor("chunk-000000.000000"));
DbUtil.CreateOngoingChunk(config, 1, GetFilePathFor("chunk-000001.000001"));
File.Create(GetFilePathFor("bla")).Close();
File.Create(GetFilePathFor("bla.scavenge.tmp")).Close();
File.Create(GetFilePathFor("bla.tmp")).Close();
Assert.DoesNotThrow(() => db.Open(verifyHash: false));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000000.000000")));
Assert.IsTrue(File.Exists(GetFilePathFor("chunk-000001.000001")));
Assert.IsTrue(File.Exists(GetFilePathFor("bla")));
Assert.AreEqual(3, Directory.GetFiles(PathName, "*").Length);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace UWOLMaps
{
public partial class LevelProperties : UserControl
{
public event EventHandler ObjectChanged;
public LevelProperties()
{
InitializeComponent();
loadCombos();
if (!this.DesignMode)
{
cboInk.MeasureItem += new MeasureItemEventHandler(cboMeasureItem);
cboPaper.MeasureItem += new MeasureItemEventHandler(cboMeasureItem);
cboInk.DrawItem += new DrawItemEventHandler(cboDrawItem);
cboPaper.DrawItem += new DrawItemEventHandler(cboDrawItem);
cboTileFondo.MeasureItem += new MeasureItemEventHandler(cboTileFondo_MeasureItem);
cboTileFondo.DrawItem += new DrawItemEventHandler(cboTileFondo_DrawItem);
}
}
private Level level;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public Level Level
{
get { return level; }
set
{
level = value;
UpdateBinding();
}
}
private Dictionary<string, Image> imageList;
public Dictionary<string, Image> ImageList
{
get { return imageList; }
set { imageList = value; }
}
private Version version;
public Version Version
{
get { return version; }
set { version = value; }
}
public object SelectedObject
{
get { return properties.SelectedObject; }
set
{
lblTipo.Text = "";
properties.SelectedObject = value;
if (value is Moneda) lblTipo.Text = "Moneda";
if (value is Enemigo) lblTipo.Text = "Enemigo";
if (value is Plataforma) lblTipo.Text = "Plataforma";
}
}
void cboDrawItem(object sender, DrawItemEventArgs e)
{
ColorZX col;
SolidBrush br;
SolidBrush textBr;
ComboBox cbo = sender as ComboBox;
e.DrawBackground();
if (e.Index != -1)
{
col = (ColorZX)((ComboBox)sender).Items[e.Index];
br = new SolidBrush(Utils.ColorZXToColor(col));
if ((e.State & (DrawItemState.Selected | DrawItemState.HotLight)) != 0)
{
textBr = new SolidBrush(Color.FromKnownColor(KnownColor.HighlightText));
}
else
{
textBr = new SolidBrush(Color.FromKnownColor(KnownColor.WindowText));
}
e.Graphics.FillRectangle(br, e.Bounds.X + 1, e.Bounds.Y + 1, cbo.ItemHeight - 1, cbo.ItemHeight - 1);
e.Graphics.DrawRectangle(Pens.Black, e.Bounds.X, e.Bounds.Y, cbo.ItemHeight, cbo.ItemHeight);
e.Graphics.DrawString(col.ToString(), cbo.Font, textBr, cbo.ItemHeight + 3, e.Bounds.Y + 1);
br.Dispose();
textBr.Dispose();
}
}
void cboMeasureItem(object sender, MeasureItemEventArgs e)
{
ComboBox cbo = sender as ComboBox;
if (e.Index != -1)
{
e.ItemHeight = cbo.ItemHeight;
e.ItemWidth = cbo.ItemHeight + 6 +
(int)e.Graphics.MeasureString(((ColorZX)cbo.Items[e.Index]).ToString(), cbo.Font).Width;
}
}
void cboTileFondo_DrawItem(object sender, DrawItemEventArgs e)
{
ComboBox cbo = sender as ComboBox;
e.DrawBackground();
if (!this.DesignMode)
{
if (e.Index != -1)
{
TilesFondo tile = (TilesFondo)cbo.Items[e.Index];
if (this.imageList != null)
{
e.Graphics.SmoothingMode = SmoothingMode.None;
e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
e.Graphics.DrawImage(this.imageList[this.version.CPU.ToString() + tile.ToString()], e.Bounds.X + 2, e.Bounds.Y + 2, 32, 32);
e.Graphics.DrawRectangle(Pens.Black, e.Bounds.X + 1, e.Bounds.Y + 1, 32, 32);
}
else
{
SolidBrush textBr;
if ((e.State & (DrawItemState.Selected | DrawItemState.HotLight)) != 0)
{
textBr = new SolidBrush(Color.FromKnownColor(KnownColor.HighlightText));
}
else
{
textBr = new SolidBrush(Color.FromKnownColor(KnownColor.WindowText));
}
e.Graphics.DrawString(tile.ToString(), cbo.Font, textBr, e.Bounds.X + 1, e.Bounds.Y + 1);
textBr.Dispose();
}
}
}
}
void cboTileFondo_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 34;
e.ItemWidth = 34;
}
private void loadCombos()
{
// Load color combos.
foreach (ColorZX col in System.Enum.GetValues(typeof(ColorZX)))
{
cboInk.Items.Add(col);
cboPaper.Items.Add(col);
}
// Load tile combos.
foreach (TilesFondo tile in System.Enum.GetValues(typeof(TilesFondo)))
{
cboTileFondo.Items.Add(tile);
}
}
private void UpdateBinding()
{
this.levelBindingSource.DataSource = this.level;
}
private void cboTileFondo_SelectedIndexChanged(object sender, EventArgs e)
{
this.level.TileFondo = (TilesFondo)cboTileFondo.Items[cboTileFondo.SelectedIndex];
}
private void cboPaper_SelectedIndexChanged(object sender, EventArgs e)
{
this.level.PaperColor = (ColorZX)cboPaper.Items[cboPaper.SelectedIndex];
}
private void cboInk_SelectedIndexChanged(object sender, EventArgs e)
{
this.level.InkColor = (ColorZX)cboInk.Items[cboInk.SelectedIndex];
}
private void numPantalla_ValueChanged(object sender, EventArgs e)
{
this.level.NumPantalla = (byte)numPantalla.Value;
}
private void properties_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
this.OnObjectChanged(EventArgs.Empty);
}
private void OnObjectChanged(EventArgs e)
{
if (this.ObjectChanged != null)
{
this.ObjectChanged(this, e);
}
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.38.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Cloud Text-to-Speech API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/text-to-speech/'>Cloud Text-to-Speech API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20190201 (1492)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/text-to-speech/'>
* https://cloud.google.com/text-to-speech/</a>
* <tr><th>Discovery Name<td>texttospeech
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Cloud Text-to-Speech API can be found at
* <a href='https://cloud.google.com/text-to-speech/'>https://cloud.google.com/text-to-speech/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Texttospeech.v1
{
/// <summary>The Texttospeech Service.</summary>
public class TexttospeechService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public TexttospeechService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public TexttospeechService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
text = new TextResource(this);
voices = new VoicesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "texttospeech"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://texttospeech.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://texttospeech.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Cloud Text-to-Speech API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Cloud Text-to-Speech API.</summary>
public static class ScopeConstants
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
private readonly TextResource text;
/// <summary>Gets the Text resource.</summary>
public virtual TextResource Text
{
get { return text; }
}
private readonly VoicesResource voices;
/// <summary>Gets the Voices resource.</summary>
public virtual VoicesResource Voices
{
get { return voices; }
}
}
///<summary>A base abstract class for Texttospeech requests.</summary>
public abstract class TexttospeechBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new TexttospeechBaseServiceRequest instance.</summary>
protected TexttospeechBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Texttospeech parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "text" collection of methods.</summary>
public class TextResource
{
private const string Resource = "text";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public TextResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Synthesizes speech synchronously: receive results after all text input has been
/// processed.</summary>
/// <param name="body">The body of the request.</param>
public virtual SynthesizeRequest Synthesize(Google.Apis.Texttospeech.v1.Data.SynthesizeSpeechRequest body)
{
return new SynthesizeRequest(service, body);
}
/// <summary>Synthesizes speech synchronously: receive results after all text input has been
/// processed.</summary>
public class SynthesizeRequest : TexttospeechBaseServiceRequest<Google.Apis.Texttospeech.v1.Data.SynthesizeSpeechResponse>
{
/// <summary>Constructs a new Synthesize request.</summary>
public SynthesizeRequest(Google.Apis.Services.IClientService service, Google.Apis.Texttospeech.v1.Data.SynthesizeSpeechRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Texttospeech.v1.Data.SynthesizeSpeechRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "synthesize"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/text:synthesize"; }
}
/// <summary>Initializes Synthesize parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
/// <summary>The "voices" collection of methods.</summary>
public class VoicesResource
{
private const string Resource = "voices";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public VoicesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Returns a list of Voice supported for synthesis.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Returns a list of Voice supported for synthesis.</summary>
public class ListRequest : TexttospeechBaseServiceRequest<Google.Apis.Texttospeech.v1.Data.ListVoicesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>Optional (but recommended) [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
/// If specified, the ListVoices call will only return voices that can be used to synthesize this
/// language_code. E.g. when specifying "en-NZ", you will get supported "en-*" voices; when specifying "no",
/// you will get supported "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices; specifying "zh" will
/// also get supported "cmn-*" voices; specifying "zh-hk" will also get supported "yue-*" voices.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/voices"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Texttospeech.v1.Data
{
/// <summary>Description of audio data to be synthesized.</summary>
public class AudioConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The format of the requested audio byte stream.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audioEncoding")]
public virtual string AudioEncoding { get; set; }
/// <summary>An identifier which selects 'audio effects' profiles that are applied on (post synthesized) text to
/// speech. Effects are applied on top of each other in the order they are given. See
///
/// [audio-profiles](https: //cloud.google.com/text-to-speech/docs/audio-profiles) for current supported profile
/// ids.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("effectsProfileId")]
public virtual System.Collections.Generic.IList<string> EffectsProfileId { get; set; }
/// <summary>Optional speaking pitch, in the range [-20.0, 20.0]. 20 means increase 20 semitones from the
/// original pitch. -20 means decrease 20 semitones from the original pitch.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pitch")]
public virtual System.Nullable<double> Pitch { get; set; }
/// <summary>The synthesis sample rate (in hertz) for this audio. Optional. If this is different from the
/// voice's natural sample rate, then the synthesizer will honor this request by converting to the desired
/// sample rate (which might result in worse audio quality), unless the specified sample rate is not supported
/// for the encoding chosen, in which case it will fail the request and return
/// google.rpc.Code.INVALID_ARGUMENT.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sampleRateHertz")]
public virtual System.Nullable<int> SampleRateHertz { get; set; }
/// <summary>Optional speaking rate/speed, in the range [0.25, 4.0]. 1.0 is the normal native speed supported by
/// the specific voice. 2.0 is twice as fast, and 0.5 is half as fast. If unset(0.0), defaults to the native 1.0
/// speed. Any other values < 0.25 or > 4.0 will return an error.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("speakingRate")]
public virtual System.Nullable<double> SpeakingRate { get; set; }
/// <summary>Optional volume gain (in dB) of the normal native volume supported by the specific voice, in the
/// range [-96.0, 16.0]. If unset, or set to a value of 0.0 (dB), will play at normal native signal amplitude. A
/// value of -6.0 (dB) will play at approximately half the amplitude of the normal native signal amplitude. A
/// value of +6.0 (dB) will play at approximately twice the amplitude of the normal native signal amplitude.
/// Strongly recommend not to exceed +10 (dB) as there's usually no effective increase in loudness for any value
/// greater than that.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("volumeGainDb")]
public virtual System.Nullable<double> VolumeGainDb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The message returned to the client by the `ListVoices` method.</summary>
public class ListVoicesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of voices.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("voices")]
public virtual System.Collections.Generic.IList<Voice> Voices { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Contains text input to be synthesized. Either `text` or `ssml` must be supplied. Supplying both or
/// neither returns google.rpc.Code.INVALID_ARGUMENT. The input size is limited to 5000 characters.</summary>
public class SynthesisInput : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The SSML document to be synthesized. The SSML document must be valid and well-formed. Otherwise the
/// RPC will fail and return google.rpc.Code.INVALID_ARGUMENT. For more information, see [SSML](/speech/text-to-
/// speech/docs/ssml).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ssml")]
public virtual string Ssml { get; set; }
/// <summary>The raw text to be synthesized.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual string Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The top-level message sent by the client for the `SynthesizeSpeech` method.</summary>
public class SynthesizeSpeechRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The configuration of the synthesized audio.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audioConfig")]
public virtual AudioConfig AudioConfig { get; set; }
/// <summary>Required. The Synthesizer requires either plain text or SSML as input.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("input")]
public virtual SynthesisInput Input { get; set; }
/// <summary>Required. The desired voice of the synthesized audio.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("voice")]
public virtual VoiceSelectionParams Voice { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The message returned to the client by the `SynthesizeSpeech` method.</summary>
public class SynthesizeSpeechResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The audio data bytes encoded as specified in the request, including the header (For LINEAR16 audio,
/// we include the WAV header). Note: as with all bytes fields, protobuffers use a pure binary representation,
/// whereas JSON representations use base64.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audioContent")]
public virtual string AudioContent { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Description of a voice supported by the TTS service.</summary>
public class Voice : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The languages that this voice supports, expressed as [BCP-47](https://www.rfc-
/// editor.org/rfc/bcp/bcp47.txt) language tags (e.g. "en-US", "es-419", "cmn-tw").</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCodes")]
public virtual System.Collections.Generic.IList<string> LanguageCodes { get; set; }
/// <summary>The name of this voice. Each distinct voice has a unique name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The natural sample rate (in hertz) for this voice.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("naturalSampleRateHertz")]
public virtual System.Nullable<int> NaturalSampleRateHertz { get; set; }
/// <summary>The gender of this voice.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ssmlGender")]
public virtual string SsmlGender { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Description of which voice to use for a synthesis request.</summary>
public class VoiceSelectionParams : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The language (and optionally also the region) of the voice expressed as a [BCP-47](https://www.rfc-
/// editor.org/rfc/bcp/bcp47.txt) language tag, e.g. "en-US". Required. This should not include a script tag
/// (e.g. use "cmn-cn" rather than "cmn-Hant-cn"), because the script will be inferred from the input provided
/// in the SynthesisInput. The TTS service will use this parameter to help choose an appropriate voice. Note
/// that the TTS service may choose a voice with a slightly different language code than the one selected; it
/// may substitute a different region (e.g. using en-US rather than en-CA if there isn't a Canadian voice
/// available), or even a different language, e.g. using "nb" (Norwegian Bokmal) instead of "no"
/// (Norwegian)".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>The name of the voice. Optional; if not set, the service will choose a voice based on the other
/// parameters such as language_code and gender.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The preferred gender of the voice. Optional; if not set, the service will choose a voice based on
/// the other parameters such as language_code and name. Note that this is only a preference, not requirement;
/// if a voice of the appropriate gender is not available, the synthesizer should substitute a voice with a
/// different gender rather than failing the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ssmlGender")]
public virtual string SsmlGender { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
//
// ClassicTrackInfoDisplay.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 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 Gdk;
using Gtk;
using Cairo;
using Hyena.Gui;
using Banshee.Collection;
using Banshee.Collection.Gui;
namespace Banshee.Gui.Widgets
{
public class ClassicTrackInfoDisplay : TrackInfoDisplay
{
private Gdk.Window event_window;
private ArtworkPopup popup;
private uint popup_timeout_id;
private bool in_popup;
private bool in_thumbnail_region;
private Pango.Layout first_line_layout;
private Pango.Layout second_line_layout;
public ClassicTrackInfoDisplay () : base ()
{
}
protected ClassicTrackInfoDisplay (IntPtr native) : base (native)
{
}
public override void Dispose ()
{
base.Dispose ();
HidePopup ();
}
#region Widget Window Management
protected override void OnRealized ()
{
base.OnRealized ();
WindowAttr attributes = new WindowAttr ();
attributes.WindowType = Gdk.WindowType.Child;
attributes.X = Allocation.X;
attributes.Y = Allocation.Y;
attributes.Width = Allocation.Width;
attributes.Height = Allocation.Height;
attributes.Wclass = WindowClass.InputOnly;
attributes.EventMask = (int)(
EventMask.PointerMotionMask |
EventMask.EnterNotifyMask |
EventMask.LeaveNotifyMask |
EventMask.ExposureMask);
WindowAttributesType attributes_mask =
WindowAttributesType.X | WindowAttributesType.Y | WindowAttributesType.Wmclass;
event_window = new Gdk.Window (GdkWindow, attributes, attributes_mask);
event_window.UserData = Handle;
}
protected override void OnUnrealized ()
{
WidgetFlags ^= WidgetFlags.Realized;
event_window.UserData = IntPtr.Zero;
Hyena.Gui.GtkWorkarounds.WindowDestroy (event_window);
event_window = null;
base.OnUnrealized ();
}
protected override void OnMapped ()
{
event_window.Show ();
base.OnMapped ();
}
protected override void OnUnmapped ()
{
event_window.Hide ();
base.OnUnmapped ();
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
if (IsRealized) {
event_window.MoveResize (allocation);
}
}
protected override void OnSizeRequested (ref Requisition requisition)
{
requisition.Height = ComputeWidgetHeight ();
}
private int ComputeWidgetHeight ()
{
int width, height;
Pango.Layout layout = new Pango.Layout (PangoContext);
layout.SetText ("W");
layout.GetPixelSize (out width, out height);
layout.Dispose ();
return 2 * height;
}
protected override void OnThemeChanged ()
{
if (first_line_layout != null) {
first_line_layout.Dispose ();
first_line_layout = null;
}
if (second_line_layout != null) {
second_line_layout.Dispose ();
second_line_layout = null;
}
}
#endregion
#region Drawing
protected override void RenderTrackInfo (Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum)
{
if (track == null) {
return;
}
double offset = Allocation.Height + 10, y = 0;
double x = Allocation.X + offset;
double width = Allocation.Width - offset;
int fl_width, fl_height, sl_width, sl_height;
int pango_width = (int)(width * Pango.Scale.PangoScale);
if (first_line_layout == null) {
first_line_layout = CairoExtensions.CreateLayout (this, cr);
first_line_layout.Ellipsize = Pango.EllipsizeMode.End;
}
if (second_line_layout == null) {
second_line_layout = CairoExtensions.CreateLayout (this, cr);
second_line_layout.Ellipsize = Pango.EllipsizeMode.End;
}
// Set up the text layouts
first_line_layout.Width = pango_width;
second_line_layout.Width = pango_width;
// Compute the layout coordinates
first_line_layout.SetMarkup (GetFirstLineText (track));
first_line_layout.GetPixelSize (out fl_width, out fl_height);
second_line_layout.SetMarkup (GetSecondLineText (track));
second_line_layout.GetPixelSize (out sl_width, out sl_height);
if (fl_height + sl_height > Allocation.Height) {
SetSizeRequest (-1, fl_height + sl_height);
}
y = Allocation.Y + (Allocation.Height - (fl_height + sl_height)) / 2;
// Render the layouts
cr.Antialias = Cairo.Antialias.Default;
if (renderTrack) {
cr.MoveTo (x, y);
cr.Color = TextColor;
PangoCairoHelper.ShowLayout (cr, first_line_layout);
}
if (!renderArtistAlbum) {
return;
}
cr.MoveTo (x, y + fl_height);
PangoCairoHelper.ShowLayout (cr, second_line_layout);
}
#endregion
#region Interaction Events
protected override bool OnEnterNotifyEvent (EventCrossing evnt)
{
in_thumbnail_region = evnt.X <= Allocation.Height;
return ShowHideCoverArt ();
}
protected override bool OnLeaveNotifyEvent (EventCrossing evnt)
{
in_thumbnail_region = false;
return ShowHideCoverArt ();
}
protected override bool OnMotionNotifyEvent (EventMotion evnt)
{
in_thumbnail_region = evnt.X <= Allocation.Height;
return ShowHideCoverArt ();
}
private void OnPopupEnterNotifyEvent (object o, EnterNotifyEventArgs args)
{
in_popup = true;
}
private void OnPopupLeaveNotifyEvent (object o, LeaveNotifyEventArgs args)
{
in_popup = false;
HidePopup ();
}
private bool ShowHideCoverArt ()
{
if (!in_thumbnail_region) {
if (popup_timeout_id > 0) {
GLib.Source.Remove (popup_timeout_id);
popup_timeout_id = 0;
}
GLib.Timeout.Add (100, delegate {
if (!in_popup) {
HidePopup ();
}
return false;
});
} else {
if (popup_timeout_id > 0) {
return false;
}
popup_timeout_id = GLib.Timeout.Add (500, delegate {
if (in_thumbnail_region) {
UpdatePopup ();
}
popup_timeout_id = 0;
return false;
});
}
return true;
}
#endregion
#region Popup Window
protected override void OnArtworkChanged ()
{
UpdatePopup ();
}
private bool UpdatePopup ()
{
if (CurrentTrack == null || ArtworkManager == null) {
HidePopup ();
return false;
}
Gdk.Pixbuf pixbuf = ArtworkManager.LookupPixbuf (CurrentTrack.ArtworkId);
if (pixbuf == null) {
HidePopup ();
return false;
}
if (popup == null) {
popup = new ArtworkPopup ();
popup.EnterNotifyEvent += OnPopupEnterNotifyEvent;
popup.LeaveNotifyEvent += OnPopupLeaveNotifyEvent;
}
popup.Label = String.Format ("{0} - {1}", CurrentTrack.DisplayArtistName,
CurrentTrack.DisplayAlbumTitle);
popup.Image = pixbuf;
if (in_thumbnail_region) {
popup.Show ();
}
return true;
}
private void HidePopup ()
{
if (popup != null) {
ArtworkManager.DisposePixbuf (popup.Image);
popup.Destroy ();
popup.EnterNotifyEvent -= OnPopupEnterNotifyEvent;
popup.LeaveNotifyEvent -= OnPopupLeaveNotifyEvent;
popup = null;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Baseline;
using LamarCodeGeneration.Frames;
using Marten.Linq.Parsing;
using Marten.Schema;
using Marten.Schema.Identity;
using Marten.Schema.Identity.Sequences;
using Marten.Schema.Indexing.Unique;
using Marten.Storage;
using Marten.Storage.Metadata;
using NpgsqlTypes;
using Remotion.Linq.Parsing.ExpressionVisitors.Transformation.PredefinedTransformations;
using Weasel.Postgresql;
using Weasel.Postgresql.Tables;
#nullable enable
namespace Marten
{
internal interface IDocumentMappingBuilder
{
DocumentMapping Build(StoreOptions options);
Type DocumentType { get; }
void Include(IDocumentMappingBuilder include);
}
internal class DocumentMappingBuilder<T>: IDocumentMappingBuilder
{
private readonly IList<Action<DocumentMapping<T>>> _alterations
= new List<Action<DocumentMapping<T>>>();
internal Action<DocumentMapping<T>> Alter
{
set => _alterations.Add(value);
}
public DocumentMapping Build(StoreOptions options)
{
var mapping = new DocumentMapping<T>(options);
foreach (var alteration in _alterations) alteration(mapping);
return mapping;
}
public Type DocumentType => typeof(T);
public void Include(IDocumentMappingBuilder include)
{
_alterations.AddRange(include.As<DocumentMappingBuilder<T>>()._alterations);
}
}
/// <summary>
/// Used to customize or optimize the storage and retrieval of document types
/// </summary>
public class MartenRegistry
{
private readonly StoreOptions _storeOptions;
internal MartenRegistry(StoreOptions storeOptions)
{
_storeOptions = storeOptions;
}
protected MartenRegistry() : this(new StoreOptions())
{
}
/// <summary>
/// Include the declarations from another MartenRegistry type
/// </summary>
/// <typeparam name="T"></typeparam>
public void Include<T>() where T : MartenRegistry, new()
{
Include(new T());
}
/// <summary>
/// Include the declarations from another MartenRegistry object
/// </summary>
/// <param name="registry"></param>
public void Include(MartenRegistry registry)
{
_storeOptions.Storage.IncludeDocumentMappingBuilders(registry._storeOptions.Storage);
}
/// <summary>
/// Configure a single document type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public DocumentMappingExpression<T> For<T>()
{
return new DocumentMappingExpression<T>(_storeOptions.Storage.BuilderFor<T>());
}
public class DocumentMappingExpression<T>
{
private readonly DocumentMappingBuilder<T> _builder;
internal DocumentMappingExpression(DocumentMappingBuilder<T> builder)
{
_builder = builder;
}
/// <summary>
/// Specify the property searching mechanism for this document type. The default is
/// JSON_Locator_Only
/// </summary>
/// <param name="searching"></param>
/// <returns></returns>
public DocumentMappingExpression<T> PropertySearching(PropertySearching searching)
{
_builder.Alter = m => m.PropertySearching = searching;
return this;
}
/// <summary>
/// Override the Postgresql schema alias for this document type in order
/// to disambiguate similarly named document types. The default is just
/// the document type name to lower case.
/// </summary>
/// <param name="alias"></param>
/// <returns></returns>
public DocumentMappingExpression<T> DocumentAlias(string alias)
{
_builder.Alter = m => m.Alias = alias;
return this;
}
/// <summary>
/// Marks a property or field on this document type as a searchable field that is also duplicated in the
/// database document table
/// </summary>
/// <param name="expression"></param>
/// <param name="pgType">Optional, overrides the Postgresql column type for the duplicated field</param>
/// <param name="configure">
/// Optional, allows you to customize the Postgresql database index configured for the duplicated
/// field
/// </param>
/// <returns></returns>
[Obsolete(
"Prefer Index() if you just want to optimize querying, or choose Duplicate() if you really want a duplicated field")]
public DocumentMappingExpression<T> Searchable(Expression<Func<T, object>> expression, string? pgType = null,
NpgsqlDbType? dbType = null, Action<DocumentIndex>? configure = null)
{
return Duplicate(expression, pgType, dbType, configure);
}
/// <summary>
/// Marks a property or field on this document type as a searchable field that is also duplicated in the
/// database document table
/// </summary>
/// <param name="expression"></param>
/// <param name="pgType">Optional, overrides the Postgresql column type for the duplicated field</param>
/// <param name="configure">
/// Optional, allows you to customize the Postgresql database index configured for the duplicated
/// field
/// </param>
/// <param name="dbType">Optional, overrides the Npgsql DbType for any parameter usage of this property</param>
/// <returns></returns>
public DocumentMappingExpression<T> Duplicate(Expression<Func<T, object>> expression, string? pgType = null,
NpgsqlDbType? dbType = null, Action<DocumentIndex>? configure = null, bool notNull = false)
{
_builder.Alter = mapping =>
{
mapping.Duplicate(expression, pgType, dbType, configure, notNull);
};
return this;
}
/// <summary>
/// Creates a computed index on this data member within the JSON data storage
/// </summary>
/// <param name="expression"></param>
/// <param name="configure"></param>
/// <returns></returns>
public DocumentMappingExpression<T> Index(Expression<Func<T, object>> expression,
Action<ComputedIndex>? configure = null)
{
_builder.Alter = m => m.Index(expression, configure);
return this;
}
/// <summary>
/// Creates a computed index on this data member within the JSON data storage
/// </summary>
/// <param name="expressions"></param>
/// <param name="configure"></param>
/// <returns></returns>
public DocumentMappingExpression<T> Index(IReadOnlyCollection<Expression<Func<T, object>>> expressions,
Action<ComputedIndex>? configure = null)
{
_builder.Alter = m => m.Index(expressions, configure);
return this;
}
/// <summary>
/// Creates a unique index on this data member within the JSON data storage
/// </summary>
/// <param name="expressions"></param>
/// <returns></returns>
public DocumentMappingExpression<T> UniqueIndex(params Expression<Func<T, object>>[] expressions)
{
_builder.Alter = m => m.UniqueIndex(UniqueIndexType.Computed, null, expressions);
return this;
}
/// <summary>
/// Creates a unique index on this data member within the JSON data storage
/// </summary>
/// <param name="indexName">Name of the index</param>
/// <param name="expressions"></param>
/// <returns></returns>
public DocumentMappingExpression<T> UniqueIndex(string indexName,
params Expression<Func<T, object>>[] expressions)
{
_builder.Alter = m => m.UniqueIndex(UniqueIndexType.Computed, indexName, expressions);
return this;
}
/// <summary>
/// Creates a unique index on this data member within the JSON data storage
/// </summary>
/// <param name="indexType">Type of the index</param>
/// <param name="expressions"></param>
/// <returns></returns>
public DocumentMappingExpression<T> UniqueIndex(UniqueIndexType indexType,
params Expression<Func<T, object>>[] expressions)
{
_builder.Alter = m => m.UniqueIndex(indexType, null, expressions);
return this;
}
/// <summary>
/// Creates a unique index on this data member within the JSON data storage
/// </summary>
/// <param name="indexType">Type of the index</param>
/// <param name="indexName">Name of the index</param>
/// <param name="expressions"></param>
/// <returns></returns>
public DocumentMappingExpression<T> UniqueIndex(UniqueIndexType indexType, string indexName,
params Expression<Func<T, object>>[] expressions)
{
_builder.Alter = m => m.UniqueIndex(indexType, indexName, expressions);
return this;
}
/// <summary>
/// Creates a unique index on this data member within the JSON data storage
/// </summary>
/// <param name="indexType">Type of the index</param>
/// <param name="indexTenancyStyle">Style of tenancy</param>
/// <param name="indexName">Name of the index</param>
/// <param name="tenancyScope">Whether the unique index applies on a per tenant basis</param>
/// <param name="expressions"></param>
/// <returns></returns>
public DocumentMappingExpression<T> UniqueIndex(UniqueIndexType indexType, string indexName,
TenancyScope tenancyScope = TenancyScope.Global, params Expression<Func<T, object>>[] expressions)
{
_builder.Alter = m => m.UniqueIndex(indexType, indexName, tenancyScope, expressions);
return this;
}
/// <summary>
/// Creates an index on the predefined Last Modified column
/// </summary>
/// <param name="configure"></param>
/// <returns></returns>
public DocumentMappingExpression<T> IndexLastModified(Action<DocumentIndex>? configure = null)
{
_builder.Alter = m => m.AddLastModifiedIndex(configure);
return this;
}
public DocumentMappingExpression<T> FullTextIndex(string regConfig = Schema.FullTextIndex.DefaultRegConfig,
Action<FullTextIndex>? configure = null)
{
_builder.Alter = m => m.AddFullTextIndex(regConfig, configure);
return this;
}
public DocumentMappingExpression<T> FullTextIndex(Action<FullTextIndex> configure)
{
_builder.Alter = m => m.AddFullTextIndex(Schema.FullTextIndex.DefaultRegConfig, configure);
return this;
}
public DocumentMappingExpression<T> FullTextIndex(params Expression<Func<T, object>>[] expressions)
{
FullTextIndex(Schema.FullTextIndex.DefaultRegConfig, expressions);
return this;
}
public DocumentMappingExpression<T> FullTextIndex(string regConfig,
params Expression<Func<T, object>>[] expressions)
{
_builder.Alter = m => m.FullTextIndex(regConfig, expressions);
return this;
}
public DocumentMappingExpression<T> FullTextIndex(Action<FullTextIndex> configure,
params Expression<Func<T, object>>[] expressions)
{
_builder.Alter = m =>
{
var index = m.FullTextIndex(Schema.FullTextIndex.DefaultRegConfig, expressions);
configure(index);
var temp = index;
};
return this;
}
/// <summary>
/// Add a foreign key reference to another document type
/// </summary>
/// <param name="expression"></param>
/// <param name="foreignKeyConfiguration"></param>
/// <param name="indexConfiguration"></param>
/// <typeparam name="TReference"></typeparam>
/// <returns></returns>
public DocumentMappingExpression<T> ForeignKey<TReference>(
Expression<Func<T, object>> expression,
Action<DocumentForeignKey>? foreignKeyConfiguration = null,
Action<DocumentIndex>? indexConfiguration = null)
{
_builder.Alter = m =>
{
var visitor = new FindMembers();
visitor.Visit(expression);
var foreignKeyDefinition = m.AddForeignKey(visitor.Members.ToArray(), typeof(TReference));
foreignKeyConfiguration?.Invoke(foreignKeyDefinition);
var indexDefinition = m.AddIndex(foreignKeyDefinition.ColumnNames[0]);
indexConfiguration?.Invoke(indexDefinition);
};
return this;
}
public DocumentMappingExpression<T> ForeignKey(Expression<Func<T, object>> expression, string schemaName,
string tableName, string columnName,
Action<ForeignKey>? foreignKeyConfiguration = null)
{
_builder.Alter = m =>
{
var members = FindMembers.Determine(expression);
var duplicateField = m.DuplicateField(members);
var foreignKey =
new ForeignKey($"{m.TableName.Name}_{duplicateField.ColumnName}_fkey")
{
LinkedTable = new DbObjectName(schemaName ?? m.DatabaseSchemaName, tableName),
ColumnNames = new[] {duplicateField.ColumnName},
LinkedNames = new[] {columnName}
};
foreignKeyConfiguration?.Invoke(foreignKey);
m.ForeignKeys.Add(foreignKey);
};
return this;
}
/// <summary>
/// Overrides the Hilo sequence increment and "maximum low" number for document types that
/// use numeric id's and the Hilo Id assignment
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public DocumentMappingExpression<T> HiloSettings(HiloSettings settings)
{
_builder.Alter = mapping => mapping.HiloSettings = settings;
return this;
}
/// <summary>
/// Overrides the database schema name used to store the documents.
/// </summary>
public DocumentMappingExpression<T> DatabaseSchemaName(string databaseSchemaName)
{
_builder.Alter = mapping => mapping.DatabaseSchemaName = databaseSchemaName;
return this;
}
/// <summary>
/// Overrides the stragtegy used for id generation.
/// </summary>
public DocumentMappingExpression<T> IdStrategy(IIdGeneration idStrategy)
{
_builder.Alter = mapping => mapping.IdStrategy = idStrategy;
return this;
}
public DocumentMappingExpression<T> Identity(Expression<Func<T, object>> member)
{
_builder.Alter = mapping =>
{
var members = FindMembers.Determine(member);
if (members.Length != 1)
throw new InvalidOperationException(
$"The expression {member} is not valid as an id column in Marten");
mapping.IdMember = members.Single();
};
return this;
}
/// <summary>
/// Adds a Postgresql Gin index to the JSONB data column for this document type. Leads to faster
/// querying, but does add overhead to storage and database writes
/// </summary>
/// <param name="configureIndex"></param>
/// <returns></returns>
public DocumentMappingExpression<T> GinIndexJsonData(Action<DocumentIndex>? configureIndex = null)
{
_builder.Alter = mapping =>
{
var index = mapping.AddGinIndexToData();
configureIndex?.Invoke(index);
};
return this;
}
/// <summary>
/// Programmatically directs Marten to map this type to a hierarchy of types
/// </summary>
/// <param name="subclassType"></param>
/// <param name="alias"></param>
/// <returns></returns>
public DocumentMappingExpression<T> AddSubClass(Type subclassType, string? alias = null)
{
_builder.Alter = mapping => mapping.SubClasses.Add(subclassType, alias);
return this;
}
/// <summary>
/// Programmatically directs Marten to map all the subclasses of <cref name="T" /> to a hierarchy of types
/// </summary>
/// <param name="allSubclassTypes">
/// All the subclass types of <cref name="T" /> that you wish to map.
/// You can use either params of <see cref="Type" /> or <see cref="MappedType" /> or a mix, since Type can implicitly
/// convert to MappedType (without an alias)
/// </param>
/// <returns></returns>
public DocumentMappingExpression<T> AddSubClassHierarchy(params MappedType[] allSubclassTypes)
{
_builder.Alter = m => m.SubClasses.AddHierarchy(allSubclassTypes);
return this;
}
/// <summary>
/// Programmatically directs Marten to map all the subclasses of <cref name="T" /> to a hierarchy of types.
/// <c>Unadvised in projects with many types.</c>
/// </summary>
/// <returns></returns>
public DocumentMappingExpression<T> AddSubClassHierarchy()
{
_builder.Alter = m => m.SubClasses.AddHierarchy();
return this;
}
public DocumentMappingExpression<T> AddSubClass<TSubclass>(string? alias = null) where TSubclass : T
{
return AddSubClass(typeof(TSubclass), alias);
}
/// <summary>
/// Directs Marten to use the optimistic versioning checks upon updates
/// to this document type
/// </summary>
/// <returns></returns>
public DocumentMappingExpression<T> UseOptimisticConcurrency(bool enabled)
{
_builder.Alter = m =>
{
m.UseOptimisticConcurrency = enabled;
if (enabled)
{
m.Metadata.Version.Enabled = true;
}
};
return this;
}
/// <summary>
/// Directs Marten to apply "soft deletes" to this document type
/// </summary>
/// <returns></returns>
public DocumentMappingExpression<T> SoftDeleted()
{
_builder.Alter = m => m.DeleteStyle = DeleteStyle.SoftDelete;
return this;
}
public DocumentMappingExpression<T> SoftDeletedWithIndex(Action<DocumentIndex>? configure = null)
{
SoftDeleted();
_builder.Alter = m => m.AddDeletedAtIndex(configure);
return this;
}
/// <summary>
/// Direct this document type's DDL to be created with the named template
/// </summary>
/// <param name="templateName"></param>
/// <returns></returns>
public DocumentMappingExpression<T> DdlTemplate(string templateName)
{
_builder.Alter = m => m.DdlTemplate = templateName;
return this;
}
/// <summary>
/// Marks just this document type as being stored with conjoined multi-tenancy
/// </summary>
/// <returns></returns>
public DocumentMappingExpression<T> MultiTenanted()
{
_builder.Alter = m => m.TenancyStyle = TenancyStyle.Conjoined;
return this;
}
/// <summary>
/// Opt into the identity key generation strategy
/// </summary>
/// <returns></returns>
public DocumentMappingExpression<T> UseIdentityKey()
{
_builder.Alter = m => m.IdStrategy = new IdentityKeyGeneration(m, m.HiloSettings);
return this;
}
public DocumentMappingExpression<T> Metadata(Action<MetadataConfig> configure)
{
var metadata = new MetadataConfig(this);
configure(metadata);
return this;
}
public class MetadataConfig
{
private readonly DocumentMappingExpression<T> _parent;
public MetadataConfig(DocumentMappingExpression<T> parent)
{
_parent = parent;
}
/// <summary>
/// The current version of this document in the database
/// </summary>
public Column<Guid> Version => new Column<Guid>(_parent, m => m.Version);
/// <summary>
/// Timestamp of the last time this document was modified
/// </summary>
public Column<DateTimeOffset> LastModified =>
new Column<DateTimeOffset>(_parent, m => m.LastModified);
/// <summary>
/// The stored tenant id of this document
/// </summary>
public Column<string> TenantId => new Column<string>(_parent, m => m.TenantId);
/// <summary>
/// If soft-deleted, whether or not the document is marked as deleted
/// </summary>
public Column<bool> IsSoftDeleted => new Column<bool>(_parent, m => m.IsSoftDeleted);
/// <summary>
/// If soft-deleted, the time at which the document was marked as deleted
/// </summary>
public Column<DateTimeOffset?> SoftDeletedAt =>
new Column<DateTimeOffset?>(_parent, m => m.SoftDeletedAt);
/// <summary>
/// If the document is part of a type hierarchy, this designates
/// Marten's internal name for the sub type
/// </summary>
public Column<string> DocumentType => new Column<string>(_parent, m => m.DocumentType);
/// <summary>
/// The full name of the .Net type that was persisted
/// </summary>
public Column<string> DotNetType => new Column<string>(_parent, m => m.DotNetType);
/// <summary>
/// Optional metadata describing the correlation id for a
/// unit of work
/// </summary>
public Column<string> CorrelationId => new Column<string>(_parent, m => m.CorrelationId);
/// <summary>
/// Optional metadata describing the correlation id for a
/// unit of work
/// </summary>
public Column<string> CausationId => new Column<string>(_parent, m => m.CausationId);
/// <summary>
/// Optional metadata describing the user name or
/// process name for this unit of work
/// </summary>
public Column<string> LastModifiedBy => new Column<string>(_parent, m => m.LastModifiedBy);
/// <summary>
/// Optional, user defined headers
/// </summary>
public Column<Dictionary<string, object>> Headers => new Column<Dictionary<string, object>>(_parent, m => m.Headers);
public class Column<TProperty>
{
private readonly DocumentMappingExpression<T> _parent;
private readonly Func<DocumentMetadataCollection, MetadataColumn> _source;
internal Column(DocumentMappingExpression<T> parent, Func<DocumentMetadataCollection, MetadataColumn> source)
{
_parent = parent;
_source = source;
}
/// <summary>
/// Is the metadata field enabled. Note that this can not
/// be overridden in some cases like the "version" column
/// when a document uses optimistic versioning
/// </summary>
public bool Enabled
{
set
{
_parent._builder.Alter = m => _source(m.Metadata).Enabled = value;
}
}
/// <summary>
/// Map this metadata information to the designated Field or Property
/// on the document type. This will also enable the tracking column
/// in the underlying database table
/// </summary>
/// <param name="memberExpression"></param>
public void MapTo(Expression<Func<T, TProperty>> memberExpression)
{
var member = FindMembers.Determine(memberExpression).Single();
_parent._builder.Alter = m =>
{
var metadataColumn = _source(m.Metadata);
metadataColumn.Enabled = true;
metadataColumn.Member = member;
};
}
}
/// <summary>
/// Turn off the informational metadata columns
/// in storage like the last modified, version, and
/// dot net type for leaner storage
/// </summary>
public void DisableInformationalFields()
{
LastModified.Enabled = false;
DotNetType.Enabled = false;
Version.Enabled = false;
}
}
}
}
/// <summary>
/// Configures hierarchical type mapping to its parent
/// </summary>
public class MappedType
{
public MappedType(Type type, string? alias = null)
{
Type = type;
Alias = alias;
}
/// <summary>
/// The .Net Type
/// </summary>
public Type Type { get; set; }
/// <summary>
/// String alias that will be used to persist or load the documents
/// from the underlying database
/// </summary>
public string? Alias { get; set; }
public static implicit operator MappedType(Type type)
{
return new MappedType(type);
}
}
}
| |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// (3) Neither the name of the newtelligence AG 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.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using System;
using System.Globalization;
using System.Resources;
using System.Web.UI;
using System.Web.UI.WebControls;
using newtelligence.DasBlog.Runtime;
namespace newtelligence.DasBlog.Web
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public partial class EventlogBox : UserControl
{
protected ResourceManager resmgr;
protected void Page_Load(object sender, EventArgs e)
{
resmgr = ApplicationResourceTable.Get();
}
#region Web Form Designer generated code
protected override void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
this.PreRender += new EventHandler(this.EventlogBox_PreRender);
}
#endregion
private void EventlogBox_PreRender(object sender, EventArgs e)
{
SiteConfig siteConfig = SiteConfig.GetSiteConfig();
Control root = contentPlaceHolder;
ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
Table table = new Table();
table.CssClass = "statsTableStyle";
TableRow row = new TableRow();
row.CssClass = "statsTableHeaderRowStyle";
row.Cells.Add(new TableCell());
row.Cells.Add(new TableCell());
row.Cells.Add(new TableCell());
row.Cells[0].CssClass = "statsTableDateColumnStyle";
row.Cells[1].CssClass = "statsTableNumColumnStyle";
row.Cells[2].CssClass = "statsTableColumnStyle";
row.Cells[0].Text = "<b>" + resmgr.GetString("text_time") + "</b>";
row.Cells[1].Text = "<b>" + resmgr.GetString("text_message_code") + "</b>";
row.Cells[2].Text = "<b>" + resmgr.GetString("text_message_text") + "</b>";
table.Rows.Add(row);
// get the user's local time
DateTime utcTime = DateTime.UtcNow;
DateTime localTime = siteConfig.GetConfiguredTimeZone().ToLocalTime(utcTime);
if (Request.QueryString["date"] != null)
{
try
{
DateTime popUpTime = DateTime.ParseExact(Request.QueryString["date"], "yyyy-MM-dd", CultureInfo.InvariantCulture);
utcTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, utcTime.Hour, utcTime.Minute, utcTime.Second);
localTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, localTime.Hour, localTime.Minute, localTime.Second);
}
catch (FormatException ex)
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
}
}
EventDataItemCollection logItems = new EventDataItemCollection();
logItems.AddRange(logService.GetEventsForDay(localTime));
if (siteConfig.AdjustDisplayTimeZone)
{
newtelligence.DasBlog.Util.WindowsTimeZone tz = siteConfig.GetConfiguredTimeZone();
TimeSpan ts = tz.GetUtcOffset(DateTime.UtcNow);
int offset = ts.Hours;
if (offset < 0)
{
logItems.AddRange(logService.GetEventsForDay(localTime.AddDays(1)));
}
else
{
logItems.AddRange(logService.GetEventsForDay(localTime.AddDays(-1)));
}
}
EventDataItem[] sortedLogItems = logItems.ToSortedArray();
foreach (EventDataItem eventItem in sortedLogItems)
{
if (siteConfig.AdjustDisplayTimeZone)
{
if (siteConfig.GetConfiguredTimeZone().ToLocalTime(eventItem.EventTimeUtc).Date != localTime.Date)
{
continue;
}
}
row = new TableRow();
row.CssClass = "statsTableRowStyle";
switch (eventItem.EventCode)
{
case ((int)EventCodes.Error):
case ((int)EventCodes.PingbackServerError):
case ((int)EventCodes.PingWeblogsError):
case ((int)EventCodes.Pop3ServerError):
case ((int)EventCodes.SmtpError):
row.CssClass = "statsTableRowStyleError";
break;
case ((int)EventCodes.SecurityFailure):
row.CssClass = "statsTableRowStyleSecurityFailure";
break;
case ((int)EventCodes.TrackbackBlocked):
case ((int)EventCodes.ReferralBlocked):
case ((int)EventCodes.ItemReferralBlocked):
case ((int)EventCodes.CommentBlocked):
case ((int)EventCodes.PingbackBlocked):
row.CssClass = "statsTableRowStyleBlocked";
break;
default:
break;
}
row.Cells.Add(new TableCell());
row.Cells.Add(new TableCell());
row.Cells.Add(new TableCell());
row.Cells[0].CssClass = "statsTableDateColumnStyle";
row.Cells[1].CssClass = "statsTableNumColumnStyle";
row.Cells[2].CssClass = "statsTableColumnStyle";
if (siteConfig.AdjustDisplayTimeZone)
{
row.Cells[0].Text = siteConfig.GetConfiguredTimeZone().ToLocalTime(eventItem.EventTimeUtc).ToString("yyyy-MM-dd HH:mm:ss tt");
}
else
{
row.Cells[0].Text = eventItem.EventTimeUtc.ToString("yyyy-MM-dd HH:mm:ss tt") + " UTC";
}
row.Cells[1].Text = eventItem.EventCode.ToString();
row.Cells[2].Text = eventItem.HtmlMessage;
table.Rows.Add(row);
}
root.Controls.Add(table);
DataBind();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Messaging;
namespace Orleans.Runtime
{
internal class SocketManager
{
private readonly LRU<IPEndPoint, Socket> cache;
private readonly TimeSpan connectionTimeout;
private readonly ILogger logger;
internal SocketManager(IOptions<NetworkingOptions> options, ILoggerFactory loggerFactory)
{
var networkingOptions = options.Value;
connectionTimeout = networkingOptions.OpenConnectionTimeout;
cache = new LRU<IPEndPoint, Socket>(networkingOptions.MaxSockets, networkingOptions.MaxSocketAge, SendingSocketCreator);
this.logger = loggerFactory.CreateLogger<SocketManager>();
cache.RaiseFlushEvent += FlushHandler;
}
/// <summary>
/// Creates a socket bound to an address for use accepting connections.
/// This is for use by client gateways and other acceptors.
/// </summary>
/// <param name="address">The address to bind to.</param>
/// <returns>The new socket, appropriately bound.</returns>
internal Socket GetAcceptingSocketForEndpoint(IPEndPoint address)
{
var s = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
// Prep the socket so it will reset on close
s.LingerState = new LingerOption(true, 0);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
s.EnableFastpath();
// The following timeout is only effective when calling the synchronous
// Socket.Receive method. We should only use this method when we are reading
// the connection preamble
s.ReceiveTimeout = (int) this.connectionTimeout.TotalMilliseconds;
// And bind it to the address
s.Bind(address);
}
catch (Exception)
{
CloseSocket(s);
throw;
}
return s;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal bool CheckSendingSocket(IPEndPoint target)
{
return cache.ContainsKey(target);
}
internal Socket GetSendingSocket(IPEndPoint target)
{
return cache.Get(target);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Socket SendingSocketCreator(IPEndPoint target)
{
var s = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
s.EnableFastpath();
Connect(s, target, connectionTimeout);
// Prep the socket so it will reset on close and won't Nagle
s.LingerState = new LingerOption(true, 0);
s.NoDelay = true;
WriteConnectionPreamble(s, Constants.SiloDirectConnectionId); // Identifies this client as a direct silo-to-silo socket
// Start an asynch receive off of the socket to detect closure
var receiveAsyncEventArgs = new SocketAsyncEventArgs
{
BufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[4]) },
UserToken = new Tuple<Socket, IPEndPoint, SocketManager>(s, target, this)
};
receiveAsyncEventArgs.Completed += ReceiveCallback;
bool receiveCompleted = s.ReceiveAsync(receiveAsyncEventArgs);
NetworkingStatisticsGroup.OnOpenedSendingSocket();
if (!receiveCompleted)
{
ReceiveCallback(this, receiveAsyncEventArgs);
}
}
catch (Exception)
{
try
{
s.Dispose();
}
catch (Exception)
{
// ignore
}
throw;
}
return s;
}
internal static void WriteConnectionPreamble(Socket socket, GrainId grainId)
{
int size = 0;
byte[] grainIdByteArray = null;
if (grainId != null)
{
grainIdByteArray = grainId.ToByteArray();
size += grainIdByteArray.Length;
}
ByteArrayBuilder sizeArray = new ByteArrayBuilder();
sizeArray.Append(size);
socket.Send(sizeArray.ToBytes()); // The size of the data that is coming next.
//socket.Send(guid.ToByteArray()); // The guid of client/silo id
if (grainId != null)
{
// No need to send in a loop.
// From MSDN: If you are using a connection-oriented protocol, Send will block until all of the bytes in the buffer are sent,
// unless a time-out was set by using Socket.SendTimeout.
// If the time-out value was exceeded, the Send call will throw a SocketException.
socket.Send(grainIdByteArray); // The grainId of the client
}
}
// We start an asynch receive, with this callback, off of every send socket.
// Since we should never see data coming in on these sockets, having the receive complete means that
// the socket is in an unknown state and we should close it and try again.
private static void ReceiveCallback(object sender, SocketAsyncEventArgs socketAsyncEventArgs)
{
var t = socketAsyncEventArgs.UserToken as Tuple<Socket, IPEndPoint, SocketManager>;
try
{
t?.Item3.InvalidateEntry(t.Item2);
}
catch (Exception ex)
{
t?.Item3.logger.Error(ErrorCode.Messaging_Socket_ReceiveError, $"ReceiveCallback: {t?.Item2}", ex);
}
finally
{
socketAsyncEventArgs.Dispose();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s")]
internal void ReturnSendingSocket(Socket s)
{
// Do nothing -- the socket will get cleaned up when it gets flushed from the cache
}
private static void FlushHandler(Object sender, LRU<IPEndPoint, Socket>.FlushEventArgs args)
{
if (args.Value == null) return;
CloseSocket(args.Value);
NetworkingStatisticsGroup.OnClosedSendingSocket();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void InvalidateEntry(IPEndPoint target)
{
Socket socket;
if (!cache.RemoveKey(target, out socket)) return;
CloseSocket(socket);
NetworkingStatisticsGroup.OnClosedSendingSocket();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
// Note that this method assumes that there are no other threads accessing this object while this method runs.
// Since this is true for the MessageCenter's use of this object, we don't lock around all calls to avoid the overhead.
internal void Stop()
{
// Clear() on an LRU<> calls the flush handler on every item, so no need to manually close the sockets.
cache.Clear();
}
/// <summary>
/// Connect the socket to the target endpoint
/// </summary>
/// <param name="s">The socket</param>
/// <param name="endPoint">The target endpoint</param>
/// <param name="connectionTimeout">The timeout value to use when opening the connection</param>
/// <exception cref="TimeoutException">When the connection could not be established in time</exception>
internal static void Connect(Socket s, IPEndPoint endPoint, TimeSpan connectionTimeout)
{
var signal = new AutoResetEvent(false);
var e = new SocketAsyncEventArgs();
e.RemoteEndPoint = endPoint;
e.Completed += (sender, eventArgs) => signal.Set();
s.ConnectAsync(e);
if (!signal.WaitOne(connectionTimeout))
throw new TimeoutException($"Connection to {endPoint} could not be established in {connectionTimeout}");
if (e.SocketError != SocketError.Success || !s.Connected)
throw new OrleansException($"Could not connect to {endPoint}: {e.SocketError}");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static void CloseSocket(Socket s)
{
if (s == null)
{
return;
}
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (ObjectDisposedException)
{
// Socket is already closed -- we're done here
return;
}
catch (Exception)
{
// Ignore
}
try
{
if (s.Connected)
s.Disconnect(false);
else
s.Close();
}
catch (Exception)
{
// Ignore
}
try
{
s.Dispose();
}
catch (Exception)
{
// Ignore
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NLog.Targets;
namespace NLog.UnitTests.Config
{
using System;
using System.IO;
using NLog.Config;
using Xunit;
public class IncludeTests : NLogTestBase
{
[Fact]
public void IncludeTest()
{
LogManager.ThrowExceptions = true;
var includeAttrValue = @"included.nlog";
IncludeTest_inner(includeAttrValue, GetTempDir());
}
[Fact]
public void IncludeWildcardTest_relative()
{
var includeAttrValue = @"*.nlog";
IncludeTest_inner(includeAttrValue, GetTempDir());
}
[Fact]
public void IncludeWildcardTest_absolute()
{
var includeAttrValue = @"*.nlog";
var tempPath = GetTempDir();
includeAttrValue = Path.Combine(tempPath, includeAttrValue);
IncludeTest_inner(includeAttrValue, tempPath);
}
private void IncludeTest_inner(string includeAttrValue, string tempDir)
{
Directory.CreateDirectory(tempDir);
CreateConfigFile(tempDir, "included.nlog", @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>");
CreateConfigFile(tempDir, "main.nlog", $@"<nlog>
<include file='{includeAttrValue}' />
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
string fileToLoad = Path.Combine(tempDir, "main.nlog");
try
{
// load main.nlog from the XAP
LogManager.Configuration = new XmlLoggingConfiguration(fileToLoad);
LogManager.GetLogger("A").Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
}
finally
{
if (Directory.Exists(tempDir))
Directory.Delete(tempDir, true);
}
}
[Fact]
public void IncludeNotExistingTest()
{
LogManager.ThrowConfigExceptions = true;
string tempPath = GetTempDir();
Directory.CreateDirectory(tempPath);
using (StreamWriter fs = File.CreateText(Path.Combine(tempPath, "main.nlog")))
{
fs.Write(@"<nlog>
<include file='included.nlog' />
</nlog>");
}
string fileToLoad = Path.Combine(tempPath, "main.nlog");
try
{
Assert.Throws<NLogConfigurationException>(() => new XmlLoggingConfiguration(fileToLoad));
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void IncludeNotExistingIgnoredTest()
{
var tempPath = GetTempDir();
Directory.CreateDirectory(tempPath);
var config = @"<nlog>
<include file='included-notpresent.nlog' ignoreErrors='true' />
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>";
CreateConfigFile(tempPath, "main.nlog", config);
string fileToLoad = Path.Combine(tempPath, "main.nlog");
try
{
LogManager.Configuration = new XmlLoggingConfiguration(fileToLoad);
LogManager.GetLogger("A").Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void IncludeNotExistingIgnoredTest_DoesNotThrow()
{
LogManager.ThrowExceptions = true;
var tempPath = GetTempDir();
Directory.CreateDirectory(tempPath);
var config = @"<nlog>
<include file='included-notpresent.nlog' ignoreErrors='true' />
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>";
CreateConfigFile(tempPath, "main.nlog", config);
string fileToLoad = Path.Combine(tempPath, "main.nlog");
var ex = Record.Exception(() => new XmlLoggingConfiguration(fileToLoad));
Assert.Null(ex);
}
/// <summary>
/// Create config file in dir
/// </summary>
/// <param name="tempPath"></param>
/// <param name="filename"></param>
/// <param name="config"></param>
private static void CreateConfigFile(string tempPath, string filename, string config)
{
using (var fs = File.CreateText(Path.Combine(tempPath, filename)))
{
fs.Write(config);
}
}
private static string GetTempDir()
{
return Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
}
}
}
| |
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
using scg = global::System.Collections.Generic;
namespace PhoneNumbers {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public static partial class Phonenumber {
#region Static variables
#endregion
#region Extensions
internal static readonly object Descriptor;
static Phonenumber() {
Descriptor = null;
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public partial class PhoneNumber {
private static readonly PhoneNumber defaultInstance = new Builder().BuildPartial();
public static PhoneNumber DefaultInstance {
get { return defaultInstance; }
}
public PhoneNumber DefaultInstanceForType {
get { return defaultInstance; }
}
protected PhoneNumber ThisMessage {
get { return this; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public static class Types {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public enum CountryCodeSource {
FROM_NUMBER_WITH_PLUS_SIGN = 1,
FROM_NUMBER_WITH_IDD = 5,
FROM_NUMBER_WITHOUT_PLUS_SIGN = 10,
FROM_DEFAULT_COUNTRY = 20,
}
}
#endregion
public const int CountryCodeFieldNumber = 1;
private bool hasCountryCode;
private int countryCode_ = 0;
public bool HasCountryCode {
get { return hasCountryCode; }
}
public int CountryCode {
get { return countryCode_; }
}
public const int NationalNumberFieldNumber = 2;
private bool hasNationalNumber;
private ulong nationalNumber_ = 0UL;
public bool HasNationalNumber {
get { return hasNationalNumber; }
}
public ulong NationalNumber {
get { return nationalNumber_; }
}
public const int ExtensionFieldNumber = 3;
private bool hasExtension;
private string extension_ = "";
public bool HasExtension {
get { return hasExtension; }
}
public string Extension {
get { return extension_; }
}
public const int ItalianLeadingZeroFieldNumber = 4;
private bool hasItalianLeadingZero;
private bool italianLeadingZero_ = false;
public bool HasItalianLeadingZero {
get { return hasItalianLeadingZero; }
}
public bool ItalianLeadingZero {
get { return italianLeadingZero_; }
}
public const int NumberOfLeadingZerosFieldNumber = 8;
private bool hasNumberOfLeadingZeros;
private int numberOfLeadingZeros_ = 1;
public bool HasNumberOfLeadingZeros {
get { return hasNumberOfLeadingZeros; }
}
public int NumberOfLeadingZeros {
get { return numberOfLeadingZeros_; }
}
public const int RawInputFieldNumber = 5;
private bool hasRawInput;
private string rawInput_ = "";
public bool HasRawInput {
get { return hasRawInput; }
}
public string RawInput {
get { return rawInput_; }
}
public const int CountryCodeSourceFieldNumber = 6;
private bool hasCountryCodeSource;
private global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource countryCodeSource_ = global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
public bool HasCountryCodeSource {
get { return hasCountryCodeSource; }
}
public global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource CountryCodeSource {
get { return countryCodeSource_; }
}
public const int PreferredDomesticCarrierCodeFieldNumber = 7;
private bool hasPreferredDomesticCarrierCode;
private string preferredDomesticCarrierCode_ = "";
public bool HasPreferredDomesticCarrierCode {
get { return hasPreferredDomesticCarrierCode; }
}
public string PreferredDomesticCarrierCode {
get { return preferredDomesticCarrierCode_; }
}
public bool IsInitialized {
get {
if (!hasCountryCode) return false;
if (!hasNationalNumber) return false;
return true;
}
}
#region Lite runtime methods
public override int GetHashCode() {
int hash = GetType().GetHashCode();
if (hasCountryCode) hash ^= countryCode_.GetHashCode();
if (hasNationalNumber) hash ^= nationalNumber_.GetHashCode();
if (hasExtension) hash ^= extension_.GetHashCode();
if (hasItalianLeadingZero) hash ^= italianLeadingZero_.GetHashCode();
if (hasNumberOfLeadingZeros) hash ^= numberOfLeadingZeros_.GetHashCode();
if (hasRawInput) hash ^= rawInput_.GetHashCode();
if (hasCountryCodeSource) hash ^= countryCodeSource_.GetHashCode();
if (hasPreferredDomesticCarrierCode) hash ^= preferredDomesticCarrierCode_.GetHashCode();
return hash;
}
public override bool Equals(object obj) {
PhoneNumber other = obj as PhoneNumber;
if (other == null) return false;
if (hasCountryCode != other.hasCountryCode || (hasCountryCode && !countryCode_.Equals(other.countryCode_))) return false;
if (hasNationalNumber != other.hasNationalNumber || (hasNationalNumber && !nationalNumber_.Equals(other.nationalNumber_))) return false;
if (hasExtension != other.hasExtension || (hasExtension && !extension_.Equals(other.extension_))) return false;
if (hasItalianLeadingZero != other.hasItalianLeadingZero || (hasItalianLeadingZero && !italianLeadingZero_.Equals(other.italianLeadingZero_))) return false;
if (hasNumberOfLeadingZeros != other.hasNumberOfLeadingZeros || (hasNumberOfLeadingZeros && !numberOfLeadingZeros_.Equals(other.numberOfLeadingZeros_))) return false;
if (hasRawInput != other.hasRawInput || (hasRawInput && !rawInput_.Equals(other.rawInput_))) return false;
if (hasCountryCodeSource != other.hasCountryCodeSource || (hasCountryCodeSource && !countryCodeSource_.Equals(other.countryCodeSource_))) return false;
if (hasPreferredDomesticCarrierCode != other.hasPreferredDomesticCarrierCode || (hasPreferredDomesticCarrierCode && !preferredDomesticCarrierCode_.Equals(other.preferredDomesticCarrierCode_))) return false;
return true;
}
#endregion
public static Builder CreateBuilder() { return new Builder(); }
public Builder ToBuilder() { return CreateBuilder(this); }
public Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(PhoneNumber prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public partial class Builder {
protected Builder ThisBuilder {
get { return this; }
}
public Builder() {}
PhoneNumber result = new PhoneNumber();
protected PhoneNumber MessageBeingBuilt {
get { return result; }
}
public Builder Clear() {
result = new PhoneNumber();
return this;
}
public Builder Clone() {
return new Builder().MergeFrom(result);
}
public PhoneNumber DefaultInstanceForType {
get { return global::PhoneNumbers.PhoneNumber.DefaultInstance; }
}
public PhoneNumber Build() { return BuildPartial(); }
public PhoneNumber BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
PhoneNumber returnMe = result;
result = null;
return returnMe;
}
public Builder MergeFrom(PhoneNumber other) {
if (other == global::PhoneNumbers.PhoneNumber.DefaultInstance) return this;
if (other.HasCountryCode) {
CountryCode = other.CountryCode;
}
if (other.HasNationalNumber) {
NationalNumber = other.NationalNumber;
}
if (other.HasExtension) {
Extension = other.Extension;
}
if (other.HasItalianLeadingZero) {
ItalianLeadingZero = other.ItalianLeadingZero;
}
if (other.HasNumberOfLeadingZeros) {
NumberOfLeadingZeros = other.NumberOfLeadingZeros;
}
if (other.HasRawInput) {
RawInput = other.RawInput;
}
if (other.HasCountryCodeSource) {
CountryCodeSource = other.CountryCodeSource;
}
if (other.HasPreferredDomesticCarrierCode) {
PreferredDomesticCarrierCode = other.PreferredDomesticCarrierCode;
}
return this;
}
public bool HasCountryCode {
get { return result.HasCountryCode; }
}
public int CountryCode {
get { return result.CountryCode; }
set { SetCountryCode(value); }
}
public Builder SetCountryCode(int value) {
result.hasCountryCode = true;
result.countryCode_ = value;
return this;
}
public Builder ClearCountryCode() {
result.hasCountryCode = false;
result.countryCode_ = 0;
return this;
}
public bool HasNationalNumber {
get { return result.HasNationalNumber; }
}
public ulong NationalNumber {
get { return result.NationalNumber; }
set { SetNationalNumber(value); }
}
public Builder SetNationalNumber(ulong value) {
result.hasNationalNumber = true;
result.nationalNumber_ = value;
return this;
}
public Builder ClearNationalNumber() {
result.hasNationalNumber = false;
result.nationalNumber_ = 0UL;
return this;
}
public bool HasExtension {
get { return result.HasExtension; }
}
public string Extension {
get { return result.Extension; }
set { SetExtension(value); }
}
public Builder SetExtension(string value) {
if(value == null) throw new global::System.ArgumentNullException("value");
result.hasExtension = true;
result.extension_ = value;
return this;
}
public Builder ClearExtension() {
result.hasExtension = false;
result.extension_ = "";
return this;
}
public bool HasItalianLeadingZero {
get { return result.HasItalianLeadingZero; }
}
public bool ItalianLeadingZero {
get { return result.ItalianLeadingZero; }
set { SetItalianLeadingZero(value); }
}
public Builder SetItalianLeadingZero(bool value) {
result.hasItalianLeadingZero = true;
result.italianLeadingZero_ = value;
return this;
}
public Builder ClearItalianLeadingZero() {
result.hasItalianLeadingZero = false;
result.italianLeadingZero_ = false;
return this;
}
public bool HasNumberOfLeadingZeros {
get { return result.HasNumberOfLeadingZeros; }
}
public int NumberOfLeadingZeros {
get { return result.NumberOfLeadingZeros; }
set { SetNumberOfLeadingZeros(value); }
}
public Builder SetNumberOfLeadingZeros(int value) {
result.hasNumberOfLeadingZeros = true;
result.numberOfLeadingZeros_ = value;
return this;
}
public Builder ClearNumberOfLeadingZeros() {
result.hasNumberOfLeadingZeros = false;
result.numberOfLeadingZeros_ = 1;
return this;
}
public bool HasRawInput {
get { return result.HasRawInput; }
}
public string RawInput {
get { return result.RawInput; }
set { SetRawInput(value); }
}
public Builder SetRawInput(string value) {
if(value == null) throw new global::System.ArgumentNullException("value");
result.hasRawInput = true;
result.rawInput_ = value;
return this;
}
public Builder ClearRawInput() {
result.hasRawInput = false;
result.rawInput_ = "";
return this;
}
public bool HasCountryCodeSource {
get { return result.HasCountryCodeSource; }
}
public global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource CountryCodeSource {
get { return result.CountryCodeSource; }
set { SetCountryCodeSource(value); }
}
public Builder SetCountryCodeSource(global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource value) {
result.hasCountryCodeSource = true;
result.countryCodeSource_ = value;
return this;
}
public Builder ClearCountryCodeSource() {
result.hasCountryCodeSource = false;
result.countryCodeSource_ = global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
return this;
}
public bool HasPreferredDomesticCarrierCode {
get { return result.HasPreferredDomesticCarrierCode; }
}
public string PreferredDomesticCarrierCode {
get { return result.PreferredDomesticCarrierCode; }
set { SetPreferredDomesticCarrierCode(value); }
}
public Builder SetPreferredDomesticCarrierCode(string value) {
if(value == null) throw new global::System.ArgumentNullException("value");
result.hasPreferredDomesticCarrierCode = true;
result.preferredDomesticCarrierCode_ = value;
return this;
}
public Builder ClearPreferredDomesticCarrierCode() {
result.hasPreferredDomesticCarrierCode = false;
result.preferredDomesticCarrierCode_ = "";
return this;
}
}
static PhoneNumber() {
object.ReferenceEquals(global::PhoneNumbers.Phonenumber.Descriptor, null);
}
}
#endregion
}
| |
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Strings;
using umbraco.interfaces;
namespace Umbraco.Core.Services
{
//TODO: Move the rest of the logic for the PackageService.Export methods to here!
/// <summary>
/// A helper class to serialize entities to XML
/// </summary>
internal class EntityXmlSerializer
{
/// <summary>
/// Exports an <see cref="IContent"/> item to xml as an <see cref="XElement"/>
/// </summary>
/// <param name="contentService"></param>
/// <param name="dataTypeService"></param>
/// <param name="userService"></param>
/// <param name="content">Content to export</param>
/// <param name="deep">Optional parameter indicating whether to include descendents</param>
/// <returns><see cref="XElement"/> containing the xml representation of the Content object</returns>
public XElement Serialize(IContentService contentService, IDataTypeService dataTypeService, IUserService userService, IContent content, bool deep = false)
{
//nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias);
var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : content.ContentType.Alias.ToSafeAliasWithForcingCheck();
var xml = Serialize(dataTypeService, content, nodeName);
xml.Add(new XAttribute("nodeType", content.ContentType.Id));
xml.Add(new XAttribute("creatorName", content.GetCreatorProfile(userService).Name));
xml.Add(new XAttribute("writerName", content.GetWriterProfile(userService).Name));
xml.Add(new XAttribute("writerID", content.WriterId));
xml.Add(new XAttribute("template", content.Template == null ? "0" : content.Template.Id.ToString(CultureInfo.InvariantCulture)));
xml.Add(new XAttribute("nodeTypeAlias", content.ContentType.Alias));
if (deep)
{
var descendants = contentService.GetDescendants(content).ToArray();
var currentChildren = descendants.Where(x => x.ParentId == content.Id);
AddChildXml(contentService, dataTypeService, userService, descendants, currentChildren, xml);
}
return xml;
}
/// <summary>
/// Exports an <see cref="IMedia"/> item to xml as an <see cref="XElement"/>
/// </summary>
/// <param name="mediaService"></param>
/// <param name="dataTypeService"></param>
/// <param name="userService"></param>
/// <param name="media">Media to export</param>
/// <param name="deep">Optional parameter indicating whether to include descendents</param>
/// <returns><see cref="XElement"/> containing the xml representation of the Media object</returns>
public XElement Serialize(IMediaService mediaService, IDataTypeService dataTypeService, IUserService userService, IMedia media, bool deep = false)
{
//nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias);
var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : media.ContentType.Alias.ToSafeAliasWithForcingCheck();
var xml = Serialize(dataTypeService, media, nodeName);
xml.Add(new XAttribute("nodeType", media.ContentType.Id));
xml.Add(new XAttribute("writerName", media.GetCreatorProfile(userService).Name));
xml.Add(new XAttribute("writerID", media.CreatorId));
xml.Add(new XAttribute("version", media.Version));
xml.Add(new XAttribute("template", 0));
xml.Add(new XAttribute("nodeTypeAlias", media.ContentType.Alias));
if (deep)
{
var descendants = mediaService.GetDescendants(media).ToArray();
var currentChildren = descendants.Where(x => x.ParentId == media.Id);
AddChildXml(mediaService, dataTypeService, userService, descendants, currentChildren, xml);
}
return xml;
}
/// <summary>
/// Exports an <see cref="IMember"/> item to xml as an <see cref="XElement"/>
/// </summary>
/// <param name="dataTypeService"></param>
/// <param name="member">Member to export</param>
/// <returns><see cref="XElement"/> containing the xml representation of the Member object</returns>
public XElement Serialize(IDataTypeService dataTypeService, IMember member)
{
//nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias);
var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : member.ContentType.Alias.ToSafeAliasWithForcingCheck();
var xml = Serialize(dataTypeService, member, nodeName);
xml.Add(new XAttribute("nodeType", member.ContentType.Id));
xml.Add(new XAttribute("nodeTypeAlias", member.ContentType.Alias));
xml.Add(new XAttribute("loginName", member.Username));
xml.Add(new XAttribute("email", member.Email));
xml.Add(new XAttribute("key", member.Key));
return xml;
}
public XElement Serialize(IDataTypeService dataTypeService, Property property)
{
var propertyType = property.PropertyType;
var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "data" : property.Alias.ToSafeAlias();
var xElement = new XElement(nodeName);
//Add the property alias to the legacy schema
if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
var a = new XAttribute("alias", property.Alias.ToSafeAlias());
xElement.Add(a);
}
//Get the property editor for thsi property and let it convert it to the xml structure
var propertyEditor = PropertyEditorResolver.Current.GetByAlias(property.PropertyType.PropertyEditorAlias);
if (propertyEditor != null)
{
var xmlValue = propertyEditor.ValueEditor.ConvertDbToXml(property, propertyType, dataTypeService);
xElement.Add(xmlValue);
}
return xElement;
}
/// <summary>
/// Exports an <see cref="IDataTypeDefinition"/> item to xml as an <see cref="XElement"/>
/// </summary>
/// <param name="dataTypeService"></param>
/// <param name="dataTypeDefinition">IDataTypeDefinition type to export</param>
/// <returns><see cref="XElement"/> containing the xml representation of the IDataTypeDefinition object</returns>
public XElement Serialize(IDataTypeService dataTypeService, IDataTypeDefinition dataTypeDefinition)
{
var prevalues = new XElement("PreValues");
var prevalueList = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id)
.FormatAsDictionary();
var sort = 0;
foreach (var pv in prevalueList)
{
var prevalue = new XElement("PreValue");
prevalue.Add(new XAttribute("Id", pv.Value.Id));
prevalue.Add(new XAttribute("Value", pv.Value.Value ?? ""));
prevalue.Add(new XAttribute("Alias", pv.Key));
prevalue.Add(new XAttribute("SortOrder", sort));
prevalues.Add(prevalue);
sort++;
}
var xml = new XElement("DataType", prevalues);
xml.Add(new XAttribute("Name", dataTypeDefinition.Name));
//The 'ID' when exporting is actually the property editor alias (in pre v7 it was the IDataType GUID id)
xml.Add(new XAttribute("Id", dataTypeDefinition.PropertyEditorAlias));
xml.Add(new XAttribute("Definition", dataTypeDefinition.Key));
xml.Add(new XAttribute("DatabaseType", dataTypeDefinition.DatabaseType.ToString()));
return xml;
}
public XElement Serialize(IDictionaryItem dictionaryItem)
{
var xml = new XElement("DictionaryItem", new XAttribute("Key", dictionaryItem.ItemKey));
foreach (var translation in dictionaryItem.Translations)
{
xml.Add(new XElement("Value",
new XAttribute("LanguageId", translation.Language.Id),
new XAttribute("LanguageCultureAlias", translation.Language.IsoCode),
new XCData(translation.Value)));
}
return xml;
}
public XElement Serialize(Stylesheet stylesheet)
{
var xml = new XElement("Stylesheet",
new XElement("Name", stylesheet.Alias),
new XElement("FileName", stylesheet.Path),
new XElement("Content", new XCData(stylesheet.Content)));
var props = new XElement("Properties");
xml.Add(props);
foreach (var prop in stylesheet.Properties)
{
props.Add(new XElement("Property",
new XElement("Name", prop.Name),
new XElement("Alias", prop.Alias),
new XElement("Value", prop.Value)));
}
return xml;
}
public XElement Serialize(ILanguage language)
{
var xml = new XElement("Language",
new XAttribute("Id", language.Id),
new XAttribute("CultureAlias", language.IsoCode),
new XAttribute("FriendlyName", language.CultureName));
return xml;
}
public XElement Serialize(ITemplate template)
{
var xml = new XElement("Template");
xml.Add(new XElement("Name", template.Name));
xml.Add(new XElement("Alias", template.Alias));
xml.Add(new XElement("Design", new XCData(template.Content)));
var concreteTemplate = template as Template;
if (concreteTemplate != null && concreteTemplate.MasterTemplateId != null)
{
if (concreteTemplate.MasterTemplateId.IsValueCreated &&
concreteTemplate.MasterTemplateId.Value != default(int))
{
xml.Add(new XElement("Master", concreteTemplate.MasterTemplateId.ToString()));
xml.Add(new XElement("MasterAlias", concreteTemplate.MasterTemplateAlias));
}
}
return xml;
}
public XElement Serialize(IDataTypeService dataTypeService, IMediaType mediaType)
{
var info = new XElement("Info",
new XElement("Name", mediaType.Name),
new XElement("Alias", mediaType.Alias),
new XElement("Icon", mediaType.Icon),
new XElement("Thumbnail", mediaType.Thumbnail),
new XElement("Description", mediaType.Description),
new XElement("AllowAtRoot", mediaType.AllowedAsRoot.ToString()));
var masterContentType = mediaType.CompositionAliases().FirstOrDefault();
if (masterContentType != null)
info.Add(new XElement("Master", masterContentType));
var structure = new XElement("Structure");
foreach (var allowedType in mediaType.AllowedContentTypes)
{
structure.Add(new XElement("MediaType", allowedType.Alias));
}
var genericProperties = new XElement("GenericProperties");
foreach (var propertyType in mediaType.PropertyTypes)
{
var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);
var propertyGroup = mediaType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value);
var genericProperty = new XElement("GenericProperty",
new XElement("Name", propertyType.Name),
new XElement("Alias", propertyType.Alias),
new XElement("Type", propertyType.PropertyEditorAlias),
new XElement("Definition", definition.Key),
new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name),
new XElement("Mandatory", propertyType.Mandatory.ToString()),
new XElement("Validation", propertyType.ValidationRegExp),
new XElement("Description", new XCData(propertyType.Description)));
genericProperties.Add(genericProperty);
}
var tabs = new XElement("Tabs");
foreach (var propertyGroup in mediaType.PropertyGroups)
{
var tab = new XElement("Tab",
new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)),
new XElement("Caption", propertyGroup.Name),
new XElement("SortOrder", propertyGroup.SortOrder));
tabs.Add(tab);
}
var xml = new XElement("MediaType",
info,
structure,
genericProperties,
tabs);
return xml;
}
public XElement Serialize(IMacro macro)
{
var xml = new XElement("macro");
xml.Add(new XElement("name", macro.Name));
xml.Add(new XElement("alias", macro.Alias));
xml.Add(new XElement("scriptType", macro.ControlType));
xml.Add(new XElement("scriptAssembly", macro.ControlAssembly));
xml.Add(new XElement("scriptingFile", macro.ScriptPath));
xml.Add(new XElement("xslt", macro.XsltPath));
xml.Add(new XElement("useInEditor", macro.UseInEditor.ToString()));
xml.Add(new XElement("dontRender", macro.DontRender.ToString()));
xml.Add(new XElement("refreshRate", macro.CacheDuration.ToString(CultureInfo.InvariantCulture)));
xml.Add(new XElement("cacheByMember", macro.CacheByMember.ToString()));
xml.Add(new XElement("cacheByPage", macro.CacheByPage.ToString()));
var properties = new XElement("properties");
foreach (var property in macro.Properties)
{
properties.Add(new XElement("property",
new XAttribute("name", property.Name),
new XAttribute("alias", property.Alias),
new XAttribute("sortOrder", property.SortOrder),
new XAttribute("propertyType", property.EditorAlias)));
}
xml.Add(properties);
return xml;
}
/// <summary>
/// Exports an <see cref="IContentType"/> item to xml as an <see cref="XElement"/>
/// </summary>
/// <param name="dataTypeService"></param>
/// <param name="contentType">Content type to export</param>
/// <returns><see cref="XElement"/> containing the xml representation of the IContentType object</returns>
public XElement Serialize(IDataTypeService dataTypeService, IContentType contentType)
{
var info = new XElement("Info",
new XElement("Name", contentType.Name),
new XElement("Alias", contentType.Alias),
new XElement("Icon", contentType.Icon),
new XElement("Thumbnail", contentType.Thumbnail),
new XElement("Description", contentType.Description),
new XElement("AllowAtRoot", contentType.AllowedAsRoot.ToString()),
new XElement("IsListView", contentType.IsContainer.ToString()));
var masterContentType = contentType.ContentTypeComposition.FirstOrDefault(x => x.Id == contentType.ParentId);
if(masterContentType != null)
info.Add(new XElement("Master", masterContentType.Alias));
var compositionsElement = new XElement("Compositions");
var compositions = contentType.ContentTypeComposition;
foreach (var composition in compositions)
{
compositionsElement.Add(new XElement("Composition", composition.Alias));
}
info.Add(compositionsElement);
var allowedTemplates = new XElement("AllowedTemplates");
foreach (var template in contentType.AllowedTemplates)
{
allowedTemplates.Add(new XElement("Template", template.Alias));
}
info.Add(allowedTemplates);
if (contentType.DefaultTemplate != null && contentType.DefaultTemplate.Id != 0)
info.Add(new XElement("DefaultTemplate", contentType.DefaultTemplate.Alias));
else
info.Add(new XElement("DefaultTemplate", ""));
var structure = new XElement("Structure");
foreach (var allowedType in contentType.AllowedContentTypes)
{
structure.Add(new XElement("DocumentType", allowedType.Alias));
}
var genericProperties = new XElement("GenericProperties");
foreach (var propertyType in contentType.PropertyTypes)
{
var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);
var propertyGroup = propertyType.PropertyGroupId == null
? null
: contentType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value);
var genericProperty = new XElement("GenericProperty",
new XElement("Name", propertyType.Name),
new XElement("Alias", propertyType.Alias),
new XElement("Type", propertyType.PropertyEditorAlias),
new XElement("Definition", definition.Key),
new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name),
new XElement("Mandatory", propertyType.Mandatory.ToString()),
new XElement("Validation", propertyType.ValidationRegExp),
new XElement("Description", new XCData(propertyType.Description)));
genericProperties.Add(genericProperty);
}
var tabs = new XElement("Tabs");
foreach (var propertyGroup in contentType.PropertyGroups)
{
var tab = new XElement("Tab",
new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)),
new XElement("Caption", propertyGroup.Name),
new XElement("SortOrder", propertyGroup.SortOrder));
tabs.Add(tab);
}
return new XElement("DocumentType",
info,
structure,
genericProperties,
tabs);
}
/// <summary>
/// Used by Media Export to recursively add children
/// </summary>
/// <param name="mediaService"></param>
/// <param name="dataTypeService"></param>
/// <param name="userService"></param>
/// <param name="originalDescendants"></param>
/// <param name="currentChildren"></param>
/// <param name="currentXml"></param>
private void AddChildXml(IMediaService mediaService, IDataTypeService dataTypeService, IUserService userService, IMedia[] originalDescendants, IEnumerable<IMedia> currentChildren, XElement currentXml)
{
foreach (var child in currentChildren)
{
//add the child's xml
var childXml = Serialize(mediaService, dataTypeService, userService, child);
currentXml.Add(childXml);
//copy local (out of closure)
var c = child;
//get this item's children
var children = originalDescendants.Where(x => x.ParentId == c.Id);
//recurse and add it's children to the child xml element
AddChildXml(mediaService, dataTypeService, userService, originalDescendants, children, childXml);
}
}
/// <summary>
/// Part of the export of IContent and IMedia and IMember which is shared
/// </summary>
/// <param name="dataTypeService"></param>
/// <param name="contentBase">Base Content or Media to export</param>
/// <param name="nodeName">Name of the node</param>
/// <returns><see cref="XElement"/></returns>
private XElement Serialize(IDataTypeService dataTypeService, IContentBase contentBase, string nodeName)
{
//NOTE: that one will take care of umbracoUrlName
var url = contentBase.GetUrlSegment();
var xml = new XElement(nodeName,
new XAttribute("id", contentBase.Id),
new XAttribute("parentID", contentBase.Level > 1 ? contentBase.ParentId : -1),
new XAttribute("level", contentBase.Level),
new XAttribute("creatorID", contentBase.CreatorId),
new XAttribute("sortOrder", contentBase.SortOrder),
new XAttribute("createDate", contentBase.CreateDate.ToString("s")),
new XAttribute("updateDate", contentBase.UpdateDate.ToString("s")),
new XAttribute("nodeName", contentBase.Name),
new XAttribute("urlName", url),
new XAttribute("path", contentBase.Path),
new XAttribute("isDoc", ""));
foreach (var property in contentBase.Properties.Where(p => p != null && p.Value != null && p.Value.ToString().IsNullOrWhiteSpace() == false))
{
xml.Add(Serialize(dataTypeService, property));
}
return xml;
}
/// <summary>
/// Used by Content Export to recursively add children
/// </summary>
/// <param name="contentService"></param>
/// <param name="dataTypeService"></param>
/// <param name="userService"></param>
/// <param name="originalDescendants"></param>
/// <param name="currentChildren"></param>
/// <param name="currentXml"></param>
private void AddChildXml(IContentService contentService, IDataTypeService dataTypeService, IUserService userService, IContent[] originalDescendants, IEnumerable<IContent> currentChildren, XElement currentXml)
{
foreach (var child in currentChildren)
{
//add the child's xml
var childXml = Serialize(contentService, dataTypeService, userService, child);
currentXml.Add(childXml);
//copy local (out of closure)
var c = child;
//get this item's children
var children = originalDescendants.Where(x => x.ParentId == c.Id);
//recurse and add it's children to the child xml element
AddChildXml(contentService, dataTypeService, userService, originalDescendants, children, childXml);
}
}
}
}
| |
// EasyTouch library is copyright (c) of Hedgehog Team
// Please send feedback or bug reports to the.hedgehog.team@gmail.com
/// <summary>
/// Release notes:
///
/// V2.5 November 2012
/// =============================
/// * EasyJoystick
/// --------------
/// - First release of EasyJoystick
///
/// * EasyTouch class
/// -----------------
/// - Add static method IsRectUnderTouch : to get if a touch is in a rect.
///
/// * Inpsector
/// ------------
/// - New inspector style for pro & free skin
/// - Add hierarchy icon to identify EasyTouch gameObject
///
/// * Gesture class
/// -----------------
/// - Add method IsInRect( Rect rect) that return true if the touch is in the rect.
///
/// * Bugs fixed
/// ------------
/// - Fix 2 static methods that didn't properly reference the EasyTouch instance
/// -
///
/// V2.4 october 2012
/// =============================
/// * News
/// --------------
/// - Remove string comparisons by enumeration, for better performance
///
/// V2.3 october 2012
/// =============================
/// * News
/// --------------
/// - Added support for the Unity Remote (tested on iPad & Nexus7)
/// Thank you to fulvio Massini for the support he has given us to implement this functionality
///
///
/// V2.2 october 2012
/// =============================
/// * News
/// --------------
/// - Add new Static method : GetCurrentPickedObject(int fingerIndex) taht return the current gameobject under touch
/// Look at CameController example.
///
///
/// V2.1 september 2012
/// =============================
/// * Bug fixed
/// - On_TouchStart & On_TouchTap events and are no longer sent after the end of a two-fingers gesture
//
/// V2.0 september 2012
/// =============================
/// * Bugs fixed
/// ------------
/// - On_DragEnd2Fingers and On_SwipeEnd2Fingers messages were sent to wrong during a drag or a swipe.
/// - On_Cancel2Fingers is new sent to the picked object (if auto-select)
///
/// * News
/// --------------
/// - C# migration
/// - Implementing delegate for sending messages. (Broadcast messages is retained with a parameter for javascript developpers)
/// - Management of multiple layer for the auto selection
/// - Management of fake singleton, in case you have more than one EasyTouch per scene by error
/// - Add custom inspector
/// - Add Debug.LogError if no camera with flag MainCamera was found in the scene
///
/// * EasyTouch class
/// -----------------
/// - remove SetPickableLayer & GetPickableLayer static methods
/// - Add static method GetTouchCount : to get the number of touches.
///
/// * Gesture class
/// -----------------
/// - Add method (GetScreenToWordlPoint( Camera cam,float z) that return the world coordinate position for a camera and z position
/// - Add method (GetSwipeOrDragAngle()) that return the swipe or drag angle in degree
using UnityEngine;
using System.Collections;
/// <summary>
/// This is the main class, you need to add it to your main camera or on a empty gameobject in your scene (or use Hedgehog Team menu).
/// </summary>
public class EasyTouch : MonoBehaviour {
#region Delegate
public delegate void TouchCancelHandler(Gesture gesture);
public delegate void Cancel2FingersHandler(Gesture gesture);
public delegate void TouchStartHandler(Gesture gesture);
public delegate void TouchDownHandler(Gesture gesture);
public delegate void TouchUpHandler(Gesture gesture);
public delegate void SimpleTapHandler(Gesture gesture);
public delegate void DoubleTapHandler(Gesture gesture);
public delegate void LongTapStartHandler(Gesture gesture);
public delegate void LongTapHandler(Gesture gesture);
public delegate void LongTapEndHandler(Gesture gesture);
public delegate void DragStartHandler(Gesture gesture);
public delegate void DragHandler(Gesture gesture);
public delegate void DragEndHandler(Gesture gesture);
public delegate void SwipeStartHandler(Gesture gesture);
public delegate void SwipeHandler(Gesture gesture);
public delegate void SwipeEndHandler(Gesture gesture);
public delegate void TouchStart2FingersHandler(Gesture gesture);
public delegate void TouchDown2FingersHandler(Gesture gesture);
public delegate void TouchUp2FingersHandler(Gesture gesture);
public delegate void SimpleTap2FingersHandler(Gesture gesture);
public delegate void DoubleTap2FingersHandler(Gesture gesture);
public delegate void LongTapStart2FingersHandler(Gesture gesture);
public delegate void LongTap2FingersHandler(Gesture gesture);
public delegate void LongTapEnd2FingersHandler(Gesture gesture);
public delegate void TwistHandler(Gesture gesture);
public delegate void TwistEndHandler(Gesture gesture);
public delegate void PinchInHandler(Gesture gesture);
public delegate void PinchOutHandler(Gesture gesture);
public delegate void PinchEndHandler(Gesture gesture);
public delegate void DragStart2FingersHandler(Gesture gesture);
public delegate void Drag2FingersHandler(Gesture gesture);
public delegate void DragEnd2FingersHandler(Gesture gesture);
public delegate void SwipeStart2FingersHandler(Gesture gesture);
public delegate void Swipe2FingersHandler(Gesture gesture);
public delegate void SwipeEnd2FingersHandler(Gesture gesture);
#endregion
#region Events
/// <summary>
/// Occurs when The system cancelled tracking for the touch, as when (for example) the user puts the device to her face.
/// </summary>
public static event TouchCancelHandler On_Cancel;
/// <summary>
/// Occurs when the touch count is no longer egal to 2 and different to 0, after the begining of a two fingers gesture.
/// </summary>
public static event Cancel2FingersHandler On_Cancel2Fingers;
/// <summary>
/// Occurs when a finger touched the screen.
/// </summary>
public static event TouchStartHandler On_TouchStart;
/// <summary>
/// Occurs as the touch is active.
/// </summary>
public static event TouchDownHandler On_TouchDown;
/// <summary>
/// Occurs when a finger was lifted from the screen.
/// </summary>
public static event TouchUpHandler On_TouchUp;
/// <summary>
/// Occurs when a finger was lifted from the screen, and the time elapsed since the beginning of the touch is less than the time required for the detection of a long tap.
/// </summary>
public static event SimpleTapHandler On_SimpleTap;
/// <summary>
/// Occurs when the number of taps is egal to 2 in a short time.
/// </summary>
public static event DoubleTapHandler On_DoubleTap;
/// <summary>
/// Occurs when a finger is touching the screen, but hasn't moved since the time required for the detection of a long tap.
/// </summary>
public static event LongTapStartHandler On_LongTapStart;
/// <summary>
/// Occurs as the touch is active after a LongTapStart
/// </summary>
public static event LongTapHandler On_LongTap;
/// <summary>
/// Occurs when a finger was lifted from the screen, and the time elapsed since the beginning of the touch is more than the time required for the detection of a long tap.
/// </summary>
public static event LongTapEndHandler On_LongTapEnd;
/// <summary>
/// Occurs when a drag start. A drag is a swipe on a pickable object
/// </summary>
public static event DragStartHandler On_DragStart;
/// <summary>
/// Occurs as the drag is active.
/// </summary>
public static event DragHandler On_Drag;
/// <summary>
/// Occurs when a finger that raise the drag event , is lifted from the screen.
/// </summary>/
public static event DragEndHandler On_DragEnd;
/// <summary>
/// Occurs when swipe start.
/// </summary>
public static event SwipeStartHandler On_SwipeStart;
/// <summary>
/// Occurs as the swipe is active.
/// </summary>
public static event SwipeHandler On_Swipe;
/// <summary>
/// Occurs when a finger that raise the swipe event , is lifted from the screen.
/// </summary>
public static event SwipeEndHandler On_SwipeEnd;
/// <summary>
/// Like On_TouchStart but for a 2 fingers gesture.
/// </summary>
public static event TouchStart2FingersHandler On_TouchStart2Fingers;
/// <summary>
/// Like On_TouchDown but for a 2 fingers gesture.
/// </summary>
public static event TouchDown2FingersHandler On_TouchDown2Fingers;
/// <summary>
/// Like On_TouchUp but for a 2 fingers gesture.
/// </summary>
public static event TouchUp2FingersHandler On_TouchUp2Fingers;
/// <summary>
/// Like On_SimpleTap but for a 2 fingers gesture.
/// </summary>
public static event SimpleTap2FingersHandler On_SimpleTap2Fingers;
/// <summary>
/// Like On_DoubleTap but for a 2 fingers gesture.
/// </summary>
public static event DoubleTap2FingersHandler On_DoubleTap2Fingers;
/// <summary>
/// Like On_LongTapStart but for a 2 fingers gesture.
/// </summary>
public static event LongTapStart2FingersHandler On_LongTapStart2Fingers;
/// <summary>
/// Like On_LongTap but for a 2 fingers gesture.
/// </summary>
public static event LongTap2FingersHandler On_LongTap2Fingers;
/// <summary>
/// Like On_LongTapEnd but for a 2 fingers gesture.
/// </summary>
public static event LongTapEnd2FingersHandler On_LongTapEnd2Fingers;
/// <summary>
/// Occurs when a twist gesture start
/// </summary>
public static event TwistHandler On_Twist;
/// <summary>
/// Occurs as the twist gesture is active.
/// </summary>
public static event TwistEndHandler On_TwistEnd;
/// <summary>
/// Occurs as the twist in gesture is active.
/// </summary>
public static event PinchInHandler On_PinchIn;
/// <summary>
/// Occurs as the pinch out gesture is active.
/// </summary>
public static event PinchOutHandler On_PinchOut;
/// <summary>
/// Occurs when the 2 fingers that raise the pinch event , are lifted from the screen.
/// </summary>
public static event PinchEndHandler On_PinchEnd;
/// <summary>
/// Like On_DragStart but for a 2 fingers gesture.
/// </summary>
public static event DragStart2FingersHandler On_DragStart2Fingers;
/// <summary>
/// Like On_Drag but for a 2 fingers gesture.
/// </summary>
public static event Drag2FingersHandler On_Drag2Fingers;
/// <summary>
/// Like On_DragEnd2Fingers but for a 2 fingers gesture.
/// </summary>
public static event DragEnd2FingersHandler On_DragEnd2Fingers;
/// <summary>
/// Like On_SwipeStart but for a 2 fingers gesture.
/// </summary>
public static event SwipeStart2FingersHandler On_SwipeStart2Fingers;
/// <summary>
/// Like On_Swipe but for a 2 fingers gesture.
/// </summary>
public static event Swipe2FingersHandler On_Swipe2Fingers;
/// <summary>
/// Like On_SwipeEnd but for a 2 fingers gesture.
/// </summary>
public static event SwipeEnd2FingersHandler On_SwipeEnd2Fingers;
#endregion
#region Enumerations
public enum GestureType{ Tap, Drag, Swipe, None, LongTap, Pinch, Twist, Cancel, Acquisition };
/// <summary>
/// Represents the different directions for a swipe or drag gesture.
/// </summary>
public enum SwipeType{ None, Left, Right, Up, Down, Other};
/// <summary>
/// Event name.
/// </summary>
public enum EventName{ None,On_Cancel, On_Cancel2Fingers, On_TouchStart,On_TouchDown,On_TouchUp,On_SimpleTap,On_DoubleTap,On_LongTapStart,On_LongTap,
On_LongTapEnd,On_DragStart,On_Drag,On_DragEnd,On_SwipeStart,On_Swipe,On_SwipeEnd,On_TouchStart2Fingers,On_TouchDown2Fingers,On_TouchUp2Fingers,On_SimpleTap2Fingers,
On_DoubleTap2Fingers,On_LongTapStart2Fingers,On_LongTap2Fingers,On_LongTapEnd2Fingers,On_Twist,On_TwistEnd,On_PinchIn,On_PinchOut,On_PinchEnd,On_DragStart2Fingers,
On_Drag2Fingers,On_DragEnd2Fingers,On_SwipeStart2Fingers,On_Swipe2Fingers,On_SwipeEnd2Fingers }
#endregion
#region Public members
public bool enable = true; // Enables or disables Easy Touch
public bool enableRemote=false; // Enables or disables Unity remote
public bool useBroadcastMessage = true; //
public bool joystickAddon = false;
public bool enable2FingersGesture=true; // Enables 2 fingers gesture.
public bool enableTwist=true; // Enables or disables recognition of the twist
public bool enablePinch=true; // Enables or disables recognition of the Pinch
public bool autoSelect = true; // Enables or disables auto select
public LayerMask pickableLayers; // Layer detectable by default.
public float StationnaryTolerance=25f; //
public float longTapTime = 1f; // The time required for the detection of a long tap.
public float swipeTolerance= 0.85f; // Determines the accuracy of detecting a drag movement 0 => no precision 1=> high precision.
public float minPinchLength=0f; // The minimum length for a pinch detection.
public float minTwistAngle =1f; // The minimum angle for a twist detection.
// Inspectori
public bool showGeneral = true;
public bool showSelect = true;
public bool showGesture = true;
public bool showTwoFinger = true;
#endregion
#region Private members
public static EasyTouch instance; // Fake singleton
private EasyTouchInput input;
private GestureType complexCurrentGesture = GestureType.None; // The current gesture 2 fingers
private GestureType oldGesture= GestureType.None;
private float startTimeAction; // The time of onset of action.
private Finger[] fingers=new Finger[100]; // The informations of the touch for finger 1.
private Camera mainCam; // The main camera of the scene, it has possessed the tag "MainCamera".
private GameObject pickObject2Finger;
private GameObject oldPickObject2Finger;
private GameObject receiverObject = null; // Other object that can receive messages.
private Texture secondFingerTexture; // The texture to display the simulation of the second finger.
private Vector2 startPosition2Finger; // Start position for two fingers gesture
private int twoFinger0; // finger index
private int twoFinger1; // finger index
private Vector2 oldStartPosition2Finger;
private float oldFingerDistance;
private bool twoFingerDragStart=false;
private bool twoFingerSwipeStart=false;
private int oldTouchCount=0;
#endregion
#region Constructor
public EasyTouch(){
enable = true;
useBroadcastMessage = false;
enable2FingersGesture=true;
enableTwist=true;
enablePinch=true;
autoSelect = true;
StationnaryTolerance=25f;
longTapTime = 1f;
swipeTolerance= 0.85f;
minPinchLength=0f;
minTwistAngle =1f;
}
#endregion
#region MonoBehaviour methods
void OnEnable(){
if (Application.isPlaying && Application.isEditor){
InitEasyTouch();
}
}
void Start(){
InitEasyTouch();
}
void InitEasyTouch(){
input = new EasyTouchInput();
// Assing the fake singleton
if (EasyTouch.instance == null)
instance = this;
// We search the main camera with the tag MainCamera.
// For automatic object selection.
mainCam = Camera.main;
if (mainCam==null){
Debug.LogError("No camera with flag \"MainCam\" was found in the scene");
}
// The texture to display the simulation of the second finger.
#if ((!UNITY_ANDROID && !UNITY_IPHONE) || UNITY_EDITOR)
secondFingerTexture =Resources.Load("secondFinger") as Texture;
#endif
}
// Display the simulation of the second finger
void OnGUI(){
#if ((!UNITY_ANDROID && !UNITY_IPHONE) || UNITY_EDITOR)
Vector2 finger = input.GetSecondFingerPosition();
if (finger!=new Vector2(-1,-1)){
GUI.DrawTexture( new Rect(finger.x-16,Screen.height-finger.y-16,32,32),secondFingerTexture);
}
#endif
}
void OnDrawGizmos(){
}
// Non comments.
void Update(){
if (enable && EasyTouch.instance==this){
int i;
// How many finger do we have ?
int count = input.TouchCount();
// Reste after two finger gesture;
if (oldTouchCount==2 && count!=2 && count>0){
CreateGesture2Finger(EventName.On_Cancel2Fingers,Vector2.zero,Vector2.zero,Vector2.zero,0,SwipeType.None,0,Vector2.zero,0,0);
}
// Get touches
#if (((UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR))
UpdateTouches(true, count);
#else
UpdateTouches(false, count);
#endif
// two fingers gesture
oldPickObject2Finger = pickObject2Finger;
if (enable2FingersGesture){
if (count==2){
TwoFinger();
}
else{
complexCurrentGesture = GestureType.None;
pickObject2Finger=null;
twoFingerSwipeStart = false;
twoFingerDragStart = false;
}
}
// Other fingers gesture
for (i=0;i<100;i++){
if (fingers[i]!=null){
OneFinger(i);
}
else{
fingers[i]=null;
}
}
oldTouchCount = count;
}
}
void UpdateTouches(bool realTouch, int touchCount){
if (realTouch || enableRemote){
foreach (Touch touch in Input.touches){
if (fingers[touch.fingerId]==null){
fingers[touch.fingerId]= new Finger();
fingers[touch.fingerId].fingerIndex = touch.fingerId;
fingers[touch.fingerId].gesture = GestureType.None;
}
fingers[touch.fingerId].position = touch.position;
fingers[touch.fingerId].deltaPosition = touch.deltaPosition;
fingers[touch.fingerId].tapCount = touch.tapCount;
fingers[touch.fingerId].deltaTime = touch.deltaTime;
fingers[touch.fingerId].phase = touch.phase;
fingers[touch.fingerId].touchCount = touchCount;
}
}
else{
int i=0;
while (i<touchCount){
fingers[i] = input.GetMouseTouch(i,fingers[i]) as Finger;
fingers[i].touchCount = touchCount;
i++;
}
}
}
#endregion
#region One finger Private methods
private void OneFinger(int fingerIndex){
float timeSinceStartAction=0;
// A tap starts ?
if ( fingers[fingerIndex].gesture==GestureType.None){
startTimeAction = Time.time;
fingers[fingerIndex].gesture=GestureType.Tap;
fingers[fingerIndex].startPosition = fingers[fingerIndex].position;
// do we touch a pickable gameobject ?
if (autoSelect)
fingers[fingerIndex].pickedObject = GetPickeGameObject(fingers[fingerIndex].startPosition);
// we notify a touch
CreateGesture(EventName.On_TouchStart,fingers[fingerIndex],0, SwipeType.None,0,Vector2.zero);
}
// Calculates the time since the beginning of the action.
timeSinceStartAction = Time.time -startTimeAction;
// touch canceled?
if (fingers[fingerIndex].phase == TouchPhase.Canceled){
fingers[fingerIndex].gesture = GestureType.Cancel;
}
if (fingers[fingerIndex].phase != TouchPhase.Ended && fingers[fingerIndex].phase != TouchPhase.Canceled){
// Are we stationary ?
if (fingers[fingerIndex].phase == TouchPhase.Stationary && timeSinceStartAction >= longTapTime && fingers[fingerIndex].gesture == GestureType.Tap){
fingers[fingerIndex].gesture = GestureType.LongTap;
CreateGesture(EventName.On_LongTapStart,fingers[fingerIndex],timeSinceStartAction, SwipeType.None,0,Vector2.zero);
}
// Let's move us?
if ((fingers[fingerIndex].gesture == GestureType.Tap ||fingers[fingerIndex].gesture == GestureType.LongTap) && (FingerInTolerance(fingers[fingerIndex])==false) ){
// long touch => cancel
if (fingers[fingerIndex].gesture == GestureType.LongTap){
fingers[fingerIndex].gesture = GestureType.Cancel;
CreateGesture(EventName.On_LongTapEnd,fingers[fingerIndex],timeSinceStartAction,SwipeType.None,0,Vector2.zero);
}
else{
// If an object is selected we drag
if (fingers[fingerIndex].pickedObject){
fingers[fingerIndex].gesture = GestureType.Drag;
CreateGesture(EventName.On_DragStart,fingers[fingerIndex],timeSinceStartAction,SwipeType.None,0, Vector2.zero);
}
// If not swipe
else{
fingers[fingerIndex].gesture = GestureType.Swipe;
CreateGesture(EventName.On_SwipeStart,fingers[fingerIndex],timeSinceStartAction, SwipeType.None,0,Vector2.zero);
}
}
}
// Gesture update
EventName message = EventName.None;
switch (fingers[fingerIndex].gesture){
case GestureType.LongTap:
message=EventName.On_LongTap;
break;
case GestureType.Drag:
message=EventName.On_Drag;
break;
case GestureType.Swipe:
message=EventName.On_Swipe;
break;
}
// Send gesture
SwipeType currentSwipe = SwipeType.None;
if (message!=EventName.None){
currentSwipe = GetSwipe(new Vector2(0,0),fingers[fingerIndex].deltaPosition);
CreateGesture(message,fingers[fingerIndex],timeSinceStartAction, currentSwipe ,0,fingers[fingerIndex].deltaPosition);
}
// Stationnary
CreateGesture(EventName.On_TouchDown,fingers[fingerIndex],timeSinceStartAction, currentSwipe,0,fingers[fingerIndex].deltaPosition);
}
else{
// End of the touch
switch (fingers[fingerIndex].gesture){
// tap
case GestureType.Tap:
if (fingers[fingerIndex].tapCount<2){
CreateGesture( EventName.On_SimpleTap,fingers[fingerIndex], timeSinceStartAction, SwipeType.None,0,Vector2.zero);
}
else{
CreateGesture( EventName.On_DoubleTap,fingers[fingerIndex], timeSinceStartAction, SwipeType.None,0,Vector2.zero);
}
break;
// long tap
case GestureType.LongTap:
CreateGesture( EventName.On_LongTapEnd,fingers[fingerIndex], timeSinceStartAction, SwipeType.None,0,Vector2.zero);
break;
// drag
case GestureType.Drag:
CreateGesture( EventName.On_DragEnd,fingers[fingerIndex], timeSinceStartAction, GetSwipe(fingers[fingerIndex].startPosition,fingers[fingerIndex].position), (fingers[fingerIndex].startPosition-fingers[fingerIndex].position).magnitude,fingers[fingerIndex].position-fingers[fingerIndex].startPosition);
break;
// swipe
case GestureType.Swipe:
CreateGesture( EventName.On_SwipeEnd,fingers[fingerIndex], timeSinceStartAction, GetSwipe(fingers[fingerIndex].startPosition, fingers[fingerIndex].position), (fingers[fingerIndex].position-fingers[fingerIndex].startPosition).magnitude,fingers[fingerIndex].position-fingers[fingerIndex].startPosition);
break;
// cancel
case GestureType.Cancel:
CreateGesture(EventName.On_Cancel,fingers[fingerIndex],0,SwipeType.None,0,Vector2.zero);
break;
}
CreateGesture( EventName.On_TouchUp,fingers[fingerIndex], timeSinceStartAction, SwipeType.None,0,Vector2.zero);
fingers[fingerIndex]=null;
}
}
private bool CreateGesture(EventName message,Finger finger,float actionTime, SwipeType swipe, float swipeLength, Vector2 swipeVector){
//Creating the structure with the required information
Gesture gesture = new Gesture();
gesture.fingerIndex = finger.fingerIndex;
gesture.touchCount = finger.touchCount;
gesture.startPosition = finger.startPosition;
gesture.position = finger.position;
gesture.deltaPosition = finger.deltaPosition;
gesture.actionTime = actionTime;
gesture.deltaTime = finger.deltaTime;
gesture.swipe = swipe;
gesture.swipeLength = swipeLength;
gesture.swipeVector = swipeVector;
gesture.deltaPinch = 0;
gesture.twistAngle = 0;
gesture.pickObject = finger.pickedObject;
gesture.otherReceiver = receiverObject;
if (useBroadcastMessage){
SendGesture(message,gesture);
}
if (!useBroadcastMessage || joystickAddon){
RaiseEvent(message, gesture);
}
return true;
}
private void SendGesture(EventName message, Gesture gesture){
if (useBroadcastMessage){
// Sent to user GameObject
if (receiverObject!=null){
if (receiverObject != gesture.pickObject){
receiverObject.SendMessage(message.ToString(), gesture,SendMessageOptions.DontRequireReceiver );
}
}
// Sent to the GameObject who is selected
if ( gesture.pickObject){
gesture.pickObject.SendMessage(message.ToString(), gesture,SendMessageOptions.DontRequireReceiver );
}
// sent to gameobject
else{
SendMessage(message.ToString(), gesture,SendMessageOptions.DontRequireReceiver);
}
}
}
#endregion
#region Two finger private methods
private void TwoFinger(){
float timeSinceStartAction=0;
bool move=false;
Vector2 position = Vector2.zero;
Vector2 deltaPosition = Vector2.zero;
float fingerDistance = 0;
// A touch starts
if ( complexCurrentGesture==GestureType.None){
twoFinger0 = GetTwoFinger(-1);
twoFinger1 = GetTwoFinger(twoFinger0);
startTimeAction = Time.time;
complexCurrentGesture=GestureType.Tap;
fingers[twoFinger0].complexStartPosition = fingers[twoFinger0].position;
fingers[twoFinger1].complexStartPosition = fingers[twoFinger1].position;
fingers[twoFinger0].oldPosition = fingers[twoFinger0].position;
fingers[twoFinger1].oldPosition = fingers[twoFinger1].position;
oldFingerDistance = Mathf.Abs( Vector2.Distance(fingers[twoFinger0].position, fingers[twoFinger1].position));
startPosition2Finger = new Vector2((fingers[twoFinger0].position.x+fingers[twoFinger1].position.x)/2, (fingers[twoFinger0].position.y+fingers[twoFinger1].position.y)/2);
deltaPosition = Vector2.zero;
// do we touch a pickable gameobject ?
if (autoSelect){
pickObject2Finger = GetPickeGameObject(fingers[twoFinger0].complexStartPosition);
if (pickObject2Finger!= GetPickeGameObject(fingers[twoFinger1].complexStartPosition)){
pickObject2Finger =null;
}
}
// we notify the touch
CreateGesture2Finger(EventName.On_TouchStart2Fingers,startPosition2Finger,startPosition2Finger,deltaPosition,timeSinceStartAction, SwipeType.None,0,Vector2.zero,0,0);
}
// Calculates the time since the beginning of the action.
timeSinceStartAction = Time.time -startTimeAction;
// Position & deltaPosition
position = new Vector2((fingers[twoFinger0].position.x+fingers[twoFinger1].position.x)/2, (fingers[twoFinger0].position.y+fingers[twoFinger1].position.y)/2);
deltaPosition = position - oldStartPosition2Finger;
fingerDistance = Mathf.Abs(Vector2.Distance(fingers[twoFinger0].position, fingers[twoFinger1].position));
// Cancel
if (fingers[twoFinger0].phase == TouchPhase.Canceled ||fingers[twoFinger1].phase == TouchPhase.Canceled){
complexCurrentGesture = GestureType.Cancel;
}
// Let's go
if (fingers[twoFinger0].phase != TouchPhase.Ended && fingers[twoFinger1].phase != TouchPhase.Ended && complexCurrentGesture != GestureType.Cancel ){
// Are we stationary ?
if (complexCurrentGesture == GestureType.Tap && timeSinceStartAction >= longTapTime && FingerInTolerance(fingers[twoFinger0]) && FingerInTolerance(fingers[twoFinger1])){
complexCurrentGesture = GestureType.LongTap;
// we notify the beginning of a longtouch
CreateGesture2Finger(EventName.On_LongTapStart2Fingers,startPosition2Finger,position,deltaPosition,timeSinceStartAction, SwipeType.None,0,Vector2.zero,0,0);
}
// Let's move us ?
//if (FingerInTolerance(fingers[twoFinger0])==false ||FingerInTolerance(fingers[twoFinger1])==false){
move=true;
//}
// we move
if (move){
float dot = Vector2.Dot(fingers[twoFinger0].deltaPosition.normalized, fingers[twoFinger1].deltaPosition.normalized);
// Pinch
if (enablePinch && fingerDistance != oldFingerDistance ){
// Pinch
if (Mathf.Abs( fingerDistance-oldFingerDistance)>=minPinchLength){
complexCurrentGesture = GestureType.Pinch;
}
// update pinch
if (complexCurrentGesture == GestureType.Pinch){
//complexCurrentGesture = GestureType.Acquisition;
if (fingerDistance<oldFingerDistance){
// Send end message
if (oldGesture != GestureType.Pinch){
CreateStateEnd2Fingers(oldGesture,startPosition2Finger,position,deltaPosition,timeSinceStartAction,false);
startTimeAction = Time.time;
}
// Send pinch
CreateGesture2Finger(EventName.On_PinchIn,startPosition2Finger,position,deltaPosition,timeSinceStartAction, GetSwipe(fingers[twoFinger0].complexStartPosition,fingers[twoFinger0].position),0,Vector2.zero,0,Mathf.Abs(fingerDistance-oldFingerDistance));
complexCurrentGesture = GestureType.Pinch;
}
else if (fingerDistance>oldFingerDistance){
// Send end message
if (oldGesture != GestureType.Pinch){
CreateStateEnd2Fingers(oldGesture,startPosition2Finger,position,deltaPosition,timeSinceStartAction,false);
startTimeAction = Time.time;
}
// Send pinch
CreateGesture2Finger(EventName.On_PinchOut,startPosition2Finger,position,deltaPosition,timeSinceStartAction, GetSwipe(fingers[twoFinger0].complexStartPosition,fingers[twoFinger0].position),0,Vector2.zero,0,Mathf.Abs(fingerDistance-oldFingerDistance));
complexCurrentGesture = GestureType.Pinch;
}
}
}
// Twist
if (enableTwist){
if (Mathf.Abs(TwistAngle())>minTwistAngle){
// Send end message
if (complexCurrentGesture != GestureType.Twist){
CreateStateEnd2Fingers(complexCurrentGesture,startPosition2Finger,position,deltaPosition,timeSinceStartAction,false);
startTimeAction = Time.time;
}
complexCurrentGesture = GestureType.Twist;
}
// Update Twist
if (complexCurrentGesture == GestureType.Twist){
CreateGesture2Finger(EventName.On_Twist,startPosition2Finger,position,deltaPosition,timeSinceStartAction, SwipeType.None,0,Vector2.zero,TwistAngle(),0);
}
fingers[twoFinger0].oldPosition = fingers[twoFinger0].position;
fingers[twoFinger1].oldPosition = fingers[twoFinger1].position;
}
// Drag
if (dot>0 ){
if (pickObject2Finger && !twoFingerDragStart){
// Send end message
if (complexCurrentGesture != GestureType.Tap){
CreateStateEnd2Fingers(complexCurrentGesture,startPosition2Finger,position,deltaPosition,timeSinceStartAction,false);
startTimeAction = Time.time;
}
//
CreateGesture2Finger(EventName.On_DragStart2Fingers,startPosition2Finger,position,deltaPosition,timeSinceStartAction, SwipeType.None,0,Vector2.zero,0,0);
twoFingerDragStart = true;
}
else if (!pickObject2Finger && !twoFingerSwipeStart ) {
// Send end message
if (complexCurrentGesture!= GestureType.Tap){
CreateStateEnd2Fingers(complexCurrentGesture,startPosition2Finger,position,deltaPosition,timeSinceStartAction,false);
startTimeAction = Time.time;
}
//
CreateGesture2Finger(EventName.On_SwipeStart2Fingers,startPosition2Finger,position,deltaPosition,timeSinceStartAction, SwipeType.None,0,Vector2.zero,0,0);
twoFingerSwipeStart=true;
}
}
else{
if (dot<0){
twoFingerDragStart=false;
twoFingerSwipeStart=false;
}
}
//
if (twoFingerDragStart){
CreateGesture2Finger(EventName.On_Drag2Fingers,startPosition2Finger,position,deltaPosition,timeSinceStartAction, GetSwipe(oldStartPosition2Finger,position),0,deltaPosition,0,0);
}
if (twoFingerSwipeStart){
CreateGesture2Finger(EventName.On_Swipe2Fingers,startPosition2Finger,position,deltaPosition,timeSinceStartAction, GetSwipe(oldStartPosition2Finger,position),0,deltaPosition,0,0);
}
}
else{
// Long tap update
if (complexCurrentGesture == GestureType.LongTap){
CreateGesture2Finger(EventName.On_LongTap2Fingers,startPosition2Finger,position,deltaPosition,timeSinceStartAction, SwipeType.None,0,Vector2.zero,0,0);
}
}
CreateGesture2Finger(EventName.On_TouchDown2Fingers,startPosition2Finger,position,deltaPosition,timeSinceStartAction, GetSwipe(oldStartPosition2Finger,position),0,deltaPosition,0,0);
oldFingerDistance = fingerDistance;
oldStartPosition2Finger = position;
oldGesture = complexCurrentGesture;
}
else{
CreateStateEnd2Fingers(complexCurrentGesture,startPosition2Finger,position,deltaPosition,timeSinceStartAction,true);
complexCurrentGesture = GestureType.None;
pickObject2Finger=null;
twoFingerSwipeStart = false;
twoFingerDragStart = false;
}
}
private int GetTwoFinger( int index){
int i=index+1;
bool find=false;
while (i<100 && !find){
if (fingers[i]!=null ){
if( i>=index){
find=true;
}
}
i++;
}
i--;
return i;
}
private void CreateStateEnd2Fingers(GestureType gesture, Vector2 startPosition, Vector2 position, Vector2 deltaPosition,float time, bool realEnd){
switch (gesture){
// Tap
case GestureType.Tap:
if (fingers[twoFinger0].tapCount<2 && fingers[twoFinger1].tapCount<2){
CreateGesture2Finger(EventName.On_SimpleTap2Fingers,startPosition,position,deltaPosition,
time, SwipeType.None,0,Vector2.zero,0,0);
}
else{
CreateGesture2Finger(EventName.On_DoubleTap2Fingers,startPosition,position,deltaPosition,
time, SwipeType.None,0,Vector2.zero,0,0);
}
break;
// Long tap
case GestureType.LongTap:
CreateGesture2Finger(EventName.On_LongTapEnd2Fingers,startPosition,position,deltaPosition,
time, SwipeType.None,0,Vector2.zero,0,0);
break;
// Pinch
case GestureType.Pinch:
CreateGesture2Finger(EventName.On_PinchEnd,startPosition,position,deltaPosition,
time, SwipeType.None,0,Vector2.zero,0,0);
break;
// twist
case GestureType.Twist:
CreateGesture2Finger(EventName.On_TwistEnd,startPosition,position,deltaPosition,
time, SwipeType.None,0,Vector2.zero,0,0);
break;
}
if (realEnd){
// Drag
if ( twoFingerDragStart){
CreateGesture2Finger(EventName.On_DragEnd2Fingers,startPosition,position,deltaPosition,
time, GetSwipe( startPosition, position),( position-startPosition).magnitude,position-startPosition,0,0);
};
// Swipe
if ( twoFingerSwipeStart){
CreateGesture2Finger(EventName.On_SwipeEnd2Fingers,startPosition,position,deltaPosition,
time, GetSwipe( startPosition, position),( position-startPosition).magnitude,position-startPosition,0,0);
}
CreateGesture2Finger(EventName.On_TouchUp2Fingers,startPosition,position,deltaPosition,time, SwipeType.None,0,Vector2.zero,0,0);
}
}
private void CreateGesture2Finger(EventName message,Vector2 startPosition,Vector2 position,Vector2 deltaPosition,
float actionTime, SwipeType swipe, float swipeLength,Vector2 swipeVector,float twist,float pinch){
//Creating the structure with the required information
Gesture gesture = new Gesture();
gesture.touchCount=2;
gesture.fingerIndex=-1;
gesture.startPosition = startPosition;
gesture.position = position;
gesture.deltaPosition = deltaPosition;
gesture.actionTime = actionTime;
if (fingers[twoFinger0]!=null)
gesture.deltaTime = fingers[twoFinger0].deltaTime;
else if (fingers[twoFinger1]!=null)
gesture.deltaTime = fingers[twoFinger1].deltaTime;
else
gesture.deltaTime=0;
gesture.swipe = swipe;
gesture.swipeLength = swipeLength;
gesture.swipeVector = swipeVector;
gesture.deltaPinch = pinch;
gesture.twistAngle = twist;
if (message!= EventName.On_Cancel2Fingers){
gesture.pickObject = pickObject2Finger;
}
else {
gesture.pickObject = oldPickObject2Finger;
}
gesture.otherReceiver = receiverObject;
if (useBroadcastMessage){
SendGesture2Finger(message,gesture );
}
else{
RaiseEvent(message, gesture);
}
}
private void SendGesture2Finger(EventName message, Gesture gesture){
// Sent to user GameObject
if (receiverObject!=null){
if (receiverObject != gesture.pickObject){
receiverObject.SendMessage(message.ToString(), gesture,SendMessageOptions.DontRequireReceiver );
}
}
// Sent to the GameObject who is selected
if ( gesture.pickObject!=null){
gesture.pickObject.SendMessage(message.ToString(), gesture,SendMessageOptions.DontRequireReceiver );
}
// sent to gameobject
else{
SendMessage(message.ToString(), gesture,SendMessageOptions.DontRequireReceiver);
}
}
#endregion
#region General private methods
private void RaiseEvent(EventName evnt, Gesture gesture){
switch(evnt){
case EventName.On_Cancel:
if (On_Cancel!=null)
On_Cancel( gesture);
break;
case EventName.On_Cancel2Fingers:
if (On_Cancel2Fingers!=null)
On_Cancel2Fingers( gesture );
break;
case EventName.On_TouchStart:
if (On_TouchStart!=null)
On_TouchStart( gesture);
break;
case EventName.On_TouchDown:
if (On_TouchDown!=null)
On_TouchDown( gesture);
break;
case EventName.On_TouchUp:
if (On_TouchUp!=null)
On_TouchUp( gesture );
break;
case EventName.On_SimpleTap:
if (On_SimpleTap!=null)
On_SimpleTap( gesture);
break;
case EventName.On_DoubleTap:
if (On_DoubleTap!=null)
On_DoubleTap(gesture);
break;
case EventName.On_LongTapStart:
if (On_LongTapStart!=null)
On_LongTapStart(gesture);
break;
case EventName.On_LongTap:
if (On_LongTap!=null)
On_LongTap(gesture);
break;
case EventName.On_LongTapEnd:
if (On_LongTapEnd!=null)
On_LongTapEnd(gesture);
break;
case EventName.On_DragStart:
if (On_DragStart!=null)
On_DragStart(gesture);
break;
case EventName.On_Drag:
if (On_Drag!=null)
On_Drag(gesture);
break;
case EventName.On_DragEnd:
if (On_DragEnd!=null)
On_DragEnd(gesture);
break;
case EventName.On_SwipeStart:
if (On_SwipeStart!=null)
On_SwipeStart( gesture);
break;
case EventName.On_Swipe:
if (On_Swipe!=null)
On_Swipe( gesture);
break;
case EventName.On_SwipeEnd:
if (On_SwipeEnd!=null)
On_SwipeEnd(gesture);
break;
case EventName.On_TouchStart2Fingers:
if (On_TouchStart2Fingers!=null)
On_TouchStart2Fingers( gesture);
break;
case EventName.On_TouchDown2Fingers:
if (On_TouchDown2Fingers!=null)
On_TouchDown2Fingers(gesture);
break;
case EventName.On_TouchUp2Fingers:
if (On_TouchUp2Fingers!=null)
On_TouchUp2Fingers(gesture);
break;
case EventName.On_SimpleTap2Fingers:
if (On_SimpleTap2Fingers!=null)
On_SimpleTap2Fingers(gesture);
break;
case EventName.On_DoubleTap2Fingers:
if (On_DoubleTap2Fingers!=null)
On_DoubleTap2Fingers(gesture);
break;
case EventName.On_LongTapStart2Fingers:
if (On_LongTapStart2Fingers!=null)
On_LongTapStart2Fingers(gesture);
break;
case EventName.On_LongTap2Fingers:
if (On_LongTap2Fingers!=null)
On_LongTap2Fingers(gesture);
break;
case EventName.On_LongTapEnd2Fingers:
if (On_LongTapEnd2Fingers!=null)
On_LongTapEnd2Fingers(gesture);
break;
case EventName.On_Twist:
if (On_Twist!=null)
On_Twist(gesture);
break;
case EventName.On_TwistEnd:
if (On_TwistEnd!=null)
On_TwistEnd(gesture);
break;
case EventName.On_PinchIn:
if (On_PinchIn!=null)
On_PinchIn(gesture);
break;
case EventName.On_PinchOut:
if (On_PinchOut!=null)
On_PinchOut(gesture);
break;
case EventName.On_PinchEnd:
if (On_PinchEnd!=null)
On_PinchEnd(gesture);
break;
case EventName.On_DragStart2Fingers:
if (On_DragStart2Fingers!=null)
On_DragStart2Fingers(gesture);
break;
case EventName.On_Drag2Fingers:
if (On_Drag2Fingers!=null)
On_Drag2Fingers(gesture);
break;
case EventName.On_DragEnd2Fingers:
if (On_DragEnd2Fingers!=null)
On_DragEnd2Fingers(gesture);
break;
case EventName.On_SwipeStart2Fingers:
if (On_SwipeStart2Fingers!=null)
On_SwipeStart2Fingers(gesture);
break;
case EventName.On_Swipe2Fingers:
if (On_Swipe2Fingers!=null)
On_Swipe2Fingers(gesture);
break;
case EventName.On_SwipeEnd2Fingers:
if (On_SwipeEnd2Fingers!=null)
On_SwipeEnd2Fingers(gesture);
break;
}
}
private GameObject GetPickeGameObject(Vector2 screenPos){
Ray ray = mainCam.ScreenPointToRay( screenPos );
RaycastHit hit;
if( Physics.Raycast( ray, out hit,float.MaxValue,pickableLayers ) ){
return hit.collider.gameObject;
}
return null;
}
private SwipeType GetSwipe(Vector2 start, Vector2 end){
Vector2 linear;
linear = (end - start).normalized;
if (Mathf.Abs(linear.y)>Mathf.Abs(linear.x)){
if ( Vector2.Dot( linear, Vector2.up) >= swipeTolerance)
return SwipeType.Up;
if ( Vector2.Dot( linear, -Vector2.up) >= swipeTolerance)
return SwipeType.Down;
}
else{
if ( Vector2.Dot( linear, Vector2.right) >= swipeTolerance)
return SwipeType.Right;
if ( Vector2.Dot( linear, -Vector2.right) >= swipeTolerance)
return SwipeType.Left;
}
return SwipeType.Other;
}
private bool FingerInTolerance(Finger finger ){
if ((finger.position-finger.startPosition).sqrMagnitude <= (StationnaryTolerance*StationnaryTolerance)){
return true;
}
else{
return false;
}
}
private float DeltaAngle(Vector2 start, Vector2 end){
var tmp = (start.x * end.y)-(start.y*end.x);
return Mathf.Atan2(tmp,Vector2.Dot( start,end));
}
private float TwistAngle(){
Vector2 dir = (fingers[twoFinger0].position-fingers[twoFinger1].position);
Vector2 refDir =(fingers[twoFinger0].oldPosition - fingers[twoFinger1].oldPosition);
float angle = Mathf.Rad2Deg * DeltaAngle(refDir,dir);
return angle;
}
#endregion
#region public static methods
/// <summary>
/// Enables or disables Easy Touch.
/// </summary>
/// <param name='enable'>
/// true = enabled
/// false = disabld
/// </param>
public static void SetEnabled( bool enable){
EasyTouch.instance.enable = enable;
}
/// <summary>
/// Return if EasyTouch is enabled or disabled
/// </summary>
/// <returns>
/// True = Enabled
/// False = Disabled
/// </returns>
public static bool GetEnabled(){
return EasyTouch.instance.enable;
}
/// <summary>
/// Return the current touches count.
/// </summary>
/// <returns>
/// int
/// </returns>
public static int GetTouchCount(){
return EasyTouch.instance.input.TouchCount();
}
/// <summary>
/// Return the camera used by EasyTouch for the auto-selection. EasyTouch research at start the camera with the tag MainCamera.
/// </summary>
/// <returns>
/// Camera
/// </returns>
public static Camera GetCamera(){
return EasyTouch.instance.mainCam;
}
/// <summary>
/// Enables or disables the recognize of 2 fingers gesture.
/// </summary>
/// <param name='enable'>
/// true = enabled
/// false = disabled
/// </param>
public static void SetEnable2FingersGesture( bool enable){
EasyTouch.instance.enable2FingersGesture = enable;
}
/// <summary>
/// Return if 2 fingers gesture is enabled or disabled
/// </summary>
/// <returns>
/// true = enabled
/// false = disabled
/// </returns>
public static bool GetEnable2FingersGesture(){
return EasyTouch.instance.enable2FingersGesture;
}
/// <summary>
/// Enables or disables the recognize of twist gesture
/// </summary>
/// <param name='enable'>
/// true = enabled
/// false = disables
/// </param>
public static void SetEnableTwist( bool enable){
EasyTouch.instance.enableTwist = enable;
}
/// <summary>
/// Return if 2 twist gesture is enabled or disabled
/// </summary>
/// <returns>
/// true = enabled
/// false = disables
/// </returns>
public static bool GetEnableTwist(){
return EasyTouch.instance.enableTwist;
}
/// <summary>
/// Enables or disables the recognize of pinch gesture
/// </summary>
/// <param name='enable'>
/// true = enabled
/// false = disables
/// </param>
public static void SetEnablePinch( bool enable){
EasyTouch.instance.enablePinch = enable;
}
/// <summary>
/// Return if 2 pinch gesture is enabled or disabled
/// </summary>
/// <returns>
/// true = enabled
/// false = disables
/// </returns>
public static bool GetEnablePinch(){
return EasyTouch.instance.enablePinch;
}
/// <summary>
/// Enables or disables auto select.
/// </summary>
/// <param name='enable'>
/// true = enabled
/// false = disables
/// </param>
public static void SetEnableAutoSelect( bool enable){
EasyTouch.instance.autoSelect = enable;
}
/// <summary>
/// Return if auto select is enabled or disabled
/// </summary>
/// <returns>
/// true = enabled
/// false = disables
/// </returns>
public static bool GetEnableAutoSelect(){
return EasyTouch.instance.autoSelect;
}
/// <summary>
/// Sets the other receiver for EasyTouch event.
/// </summary>
/// <param name='receiver'>
/// GameObject.
/// </param>
public static void SetOtherReceiverObject( GameObject receiver){
EasyTouch.instance.receiverObject = receiver;
}
/// <summary>
/// Return the other event receiver.
/// </summary>
/// <returns>
/// GameObject
/// </returns>
public static GameObject GetOtherReceiverObject(){
return EasyTouch.instance.receiverObject;
}
/// <summary>
/// Sets the stationnary tolerance.
/// </summary>
/// <param name='tolerance'>
/// float Tolerance.
/// </param>
public static void SetStationnaryTolerance(float tolerance){
EasyTouch.instance.StationnaryTolerance = tolerance;
}
/// <summary>
/// Return the stationnary tolerance.
/// </summary>
/// <returns>
/// Float
/// </returns>
public static float GetStationnaryTolerance(){
return EasyTouch.instance.StationnaryTolerance;
}
/// <summary>
/// Set the long tap time in second
/// </summary>
/// <param name='time'>
/// Float
/// </param>
public static void SetlongTapTime(float time){
EasyTouch.instance.longTapTime = time;
}
/// <summary>
/// Return the longs the tap time.
/// </summary>
/// <returns>
/// Float.
/// </returns>
public static float GetlongTapTime(){
return EasyTouch.instance.longTapTime;
}
/// <summary>
/// Sets the swipe tolerance.
/// </summary>
/// <param name='tolerance'>
/// Float
/// </param>
public static void SetSwipeTolerance( float tolerance){
EasyTouch.instance.swipeTolerance = tolerance;
}
/// <summary>
/// Return the swipe tolerance.
/// </summary>
/// <returns>
/// Float.
/// </returns>
public static float GetSwipeTolerance(){
return EasyTouch.instance.swipeTolerance;
}
/// <summary>
/// Sets the minimum length of the pinch.
/// </summary>
/// <param name='length'>
/// Float.
/// </param>
public static void SetMinPinchLength(float length){
EasyTouch.instance.minPinchLength=length;
}
/// <summary>
/// Return the minimum length of the pinch.
/// </summary>
/// <returns>
/// Float
/// </returns>
public static float GetMinPinchLength(){
return EasyTouch.instance.minPinchLength;
}
/// <summary>
/// Sets the minimum twist angle.
/// </summary>
/// <param name='angle'>
/// Float
/// </param>
public static void SetMinTwistAngle(float angle){
EasyTouch.instance.minTwistAngle = angle;
}
/// <summary>
/// Gets the minimum twist angle.
/// </summary>
/// <returns>
/// Float
/// </returns>
public static float GetMinTwistAngle(){
return EasyTouch.instance.minTwistAngle;
}
/// <summary>
/// Gets the current picked object.
/// </summary>
/// <returns>
/// The current picked object.
/// </returns>
/// <param name='fingerIndex'>
/// Finger index.
/// </param>
public static GameObject GetCurrentPickedObject(int fingerIndex){
return EasyTouch.instance.GetPickeGameObject(EasyTouch.instance.fingers[fingerIndex].position);
}
/// <summary>
/// Determines whether a touch is under a specified rect.
/// </summary>
/// <returns>
/// <c>true</c> if this a touch is rect under the specified rect; otherwise, <c>false</c>.
/// </returns>
/// <param name='rect'>
/// If set to <c>true</c> rect.
/// </param>
public static bool IsRectUnderTouch( Rect rect){
bool find=false;
for (int i=0;i<100;i++){
if ( EasyTouch.instance.fingers[i]!=null){
find = rect.Contains( EasyTouch.instance.fingers[i].position);
break;
}
}
return find;
}
#endregion
}
| |
// 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.AcceptanceTestsAzureBodyDuration
{
using Azure;
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>
/// DurationOperations operations.
/// </summary>
internal partial class DurationOperations : IServiceOperations<AutoRestDurationTestServiceClient>, IDurationOperations
{
/// <summary>
/// Initializes a new instance of the DurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DurationOperations(AutoRestDurationTestServiceClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDurationTestServiceClient
/// </summary>
public AutoRestDurationTestServiceClient Client { get; private set; }
/// <summary>
/// Get null duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<System.TimeSpan?>> 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 = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<System.TimeSpan?>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_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>
/// Put a positive duration value
/// </summary>
/// <param name='durationBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(System.TimeSpan durationBody, 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("durationBody", durationBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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;
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(durationBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a positive duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<System.TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(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, "GetPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<System.TimeSpan?>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_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 an invalid duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<System.TimeSpan?>> 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 = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<System.TimeSpan?>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_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;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="NameValueCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Ordered String/String[] collection of name/value pairs with support for null key
* Wraps NameObject collection
*
* Copyright (c) 2000 Microsoft Corporation
*/
namespace System.Collections.Specialized {
using Microsoft.Win32;
using System.Collections;
using System.Runtime.Serialization;
using System.Text;
using System.Globalization;
/// <devdoc>
/// <para>Represents a sorted collection of associated <see cref='System.String' qualify='true'/> keys and <see cref='System.String' qualify='true'/> values that
/// can be accessed either with the hash code of the key or with the index.</para>
/// </devdoc>
[Serializable()]
public class NameValueCollection : NameObjectCollectionBase {
private String[] _all;
private String[] _allKeys;
//
// Constructors
//
/// <devdoc>
/// <para>Creates an empty <see cref='System.Collections.Specialized.NameValueCollection'/> with the default initial capacity
/// and using the default case-insensitive hash code provider and the default
/// case-insensitive comparer.</para>
/// </devdoc>
public NameValueCollection() : base() {
}
/// <devdoc>
/// <para>Copies the entries from the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to a new <see cref='System.Collections.Specialized.NameValueCollection'/> with the same initial capacity as
/// the number of entries copied and using the default case-insensitive hash code
/// provider and the default case-insensitive comparer.</para>
/// </devdoc>
public NameValueCollection(NameValueCollection col)
: base( col != null? col.Comparer : null) {
Add(col);
}
/// <devdoc>
/// <para>Creates an empty <see cref='System.Collections.Specialized.NameValueCollection'/> with the default initial capacity
/// and using the specified case-insensitive hash code provider and the specified
/// case-insensitive comparer.</para>
/// </devdoc>
#pragma warning disable 618
[Obsolete("Please use NameValueCollection(IEqualityComparer) instead.")]
public NameValueCollection(IHashCodeProvider hashProvider, IComparer comparer)
: base(hashProvider, comparer) {
}
#pragma warning restore 618
/// <devdoc>
/// <para>Creates an empty <see cref='System.Collections.Specialized.NameValueCollection'/> with
/// the specified initial capacity and using the default case-insensitive hash code
/// provider and the default case-insensitive comparer.</para>
/// </devdoc>
public NameValueCollection(int capacity) : base(capacity) {
}
public NameValueCollection(IEqualityComparer equalityComparer) : base( equalityComparer) {
}
public NameValueCollection(Int32 capacity, IEqualityComparer equalityComparer)
: base(capacity, equalityComparer) {
}
/// <devdoc>
/// <para>Copies the entries from the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to a new <see cref='System.Collections.Specialized.NameValueCollection'/> with the specified initial capacity or the
/// same initial capacity as the number of entries copied, whichever is greater, and
/// using the default case-insensitive hash code provider and the default
/// case-insensitive comparer.</para>
/// </devdoc>
public NameValueCollection(int capacity, NameValueCollection col)
: base(capacity, (col != null ? col.Comparer : null)) {
if( col == null) {
throw new ArgumentNullException("col");
}
this.Comparer = col.Comparer;
Add(col);
}
/// <devdoc>
/// <para>Creates an empty <see cref='System.Collections.Specialized.NameValueCollection'/> with the specified initial capacity and
/// using the specified case-insensitive hash code provider and the specified
/// case-insensitive comparer.</para>
/// </devdoc>
#pragma warning disable 618
[Obsolete("Please use NameValueCollection(Int32, IEqualityComparer) instead.")]
public NameValueCollection(int capacity, IHashCodeProvider hashProvider, IComparer comparer)
: base(capacity, hashProvider, comparer) {
}
#pragma warning restore 618
// Allow internal extenders to avoid creating the hashtable/arraylist.
internal NameValueCollection(DBNull dummy) : base(dummy)
{
}
//
// Serialization support
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected NameValueCollection(SerializationInfo info, StreamingContext context) : base(info, context) {
}
//
// Helper methods
//
/// <devdoc>
/// <para> Resets the cached arrays of the collection to <see langword='null'/>.</para>
/// </devdoc>
protected void InvalidateCachedArrays() {
_all = null;
_allKeys = null;
}
private static String GetAsOneString(ArrayList list) {
int n = (list != null) ? list.Count : 0;
if (n == 1) {
return (String)list[0];
}
else if (n > 1) {
StringBuilder s = new StringBuilder((String)list[0]);
for (int i = 1; i < n; i++) {
s.Append(',');
s.Append((String)list[i]);
}
return s.ToString();
}
else {
return null;
}
}
private static String[] GetAsStringArray(ArrayList list)
{
int n = (list != null) ? list.Count : 0;
if (n == 0)
return null;
String [] array = new String[n];
list.CopyTo(0, array, 0, n);
return array;
}
//
// Misc public APIs
//
/// <devdoc>
/// <para>Copies the entries in the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to the current <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public void Add(NameValueCollection c) {
if( c == null) {
throw new ArgumentNullException("c");
}
InvalidateCachedArrays();
int n = c.Count;
for (int i = 0; i < n; i++) {
String key = c.GetKey(i);
String[] values = c.GetValues(i);
if (values != null) {
for (int j = 0; j < values.Length; j++)
Add(key, values[j]);
}
else {
Add(key, null);
}
}
}
/// <devdoc>
/// <para>Invalidates the cached arrays and removes all entries
/// from the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public virtual void Clear() {
if (IsReadOnly)
throw new NotSupportedException(SR.GetString(SR.CollectionReadOnly));
InvalidateCachedArrays();
BaseClear();
}
public void CopyTo(Array dest, int index) {
if (dest==null) {
throw new ArgumentNullException("dest");
}
if (dest.Rank != 1) {
throw new ArgumentException(SR.GetString(SR.Arg_MultiRank));
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index",SR.GetString(SR.IndexOutOfRange, index.ToString(CultureInfo.CurrentCulture)) );
}
if (dest.Length - index < Count) {
throw new ArgumentException(SR.GetString(SR.Arg_InsufficientSpace));
}
int n = Count;
if (_all == null) {
String[] all = new String[n];
for (int i = 0; i < n; i++) {
all[i] = Get(i);
dest.SetValue( all[i], i + index);
}
_all = all; // wait until end of loop to set _all reference in case Get throws
}
else {
for (int i = 0; i < n; i++) {
dest.SetValue( _all[i], i + index);
}
}
}
/// <devdoc>
/// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.NameValueCollection'/> contains entries whose keys are not <see langword='null'/>.</para>
/// </devdoc>
public bool HasKeys() {
return InternalHasKeys();
}
/// <devdoc>
/// <para>Allows derived classes to alter HasKeys().</para>
/// </devdoc>
internal virtual bool InternalHasKeys()
{
return BaseHasKeys();
}
//
// Access by name
//
/// <devdoc>
/// <para>Adds an entry with the specified name and value into the
/// <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public virtual void Add(String name, String value) {
if (IsReadOnly)
throw new NotSupportedException(SR.GetString(SR.CollectionReadOnly));
InvalidateCachedArrays();
ArrayList values = (ArrayList)BaseGet(name);
if (values == null) {
// new key - add new key with single value
values = new ArrayList(1);
if (value != null)
values.Add(value);
BaseAdd(name, values);
}
else {
// old key -- append value to the list of values
if (value != null)
values.Add(value);
}
}
/// <devdoc>
/// <para> Gets the values associated with the specified key from the <see cref='System.Collections.Specialized.NameValueCollection'/> combined into one comma-separated list.</para>
/// </devdoc>
public virtual String Get(String name) {
ArrayList values = (ArrayList)BaseGet(name);
return GetAsOneString(values);
}
/// <devdoc>
/// <para>Gets the values associated with the specified key from the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public virtual String[] GetValues(String name) {
ArrayList values = (ArrayList)BaseGet(name);
return GetAsStringArray(values);
}
/// <devdoc>
/// <para>Adds a value to an entry in the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public virtual void Set(String name, String value) {
if (IsReadOnly)
throw new NotSupportedException(SR.GetString(SR.CollectionReadOnly));
InvalidateCachedArrays();
ArrayList values = new ArrayList(1);
values.Add(value);
BaseSet(name, values);
}
/// <devdoc>
/// <para>Removes the entries with the specified key from the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
public virtual void Remove(String name) {
InvalidateCachedArrays();
BaseRemove(name);
}
/// <devdoc>
/// <para> Represents the entry with the specified key in the
/// <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public String this[String name] {
get {
return Get(name);
}
set {
Set(name, value);
}
}
//
// Indexed access
//
/// <devdoc>
/// <para>
/// Gets the values at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/> combined into one
/// comma-separated list.</para>
/// </devdoc>
public virtual String Get(int index) {
ArrayList values = (ArrayList)BaseGet(index);
return GetAsOneString(values);
}
/// <devdoc>
/// <para> Gets the values at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public virtual String[] GetValues(int index) {
ArrayList values = (ArrayList)BaseGet(index);
return GetAsStringArray(values);
}
/// <devdoc>
/// <para>Gets the key at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public virtual String GetKey(int index) {
return BaseGetKey(index);
}
/// <devdoc>
/// <para>Represents the entry at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public String this[int index] {
get {
return Get(index);
}
}
//
// Access to keys and values as arrays
//
/// <devdoc>
/// <para>Gets all the keys in the <see cref='System.Collections.Specialized.NameValueCollection'/>. </para>
/// </devdoc>
public virtual String[] AllKeys {
get {
if (_allKeys == null)
_allKeys = BaseGetAllKeys();
return _allKeys;
}
}
}
}
| |
/*
* 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.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework
{
public enum ProfileShape : byte
{
Circle = 0,
Square = 1,
IsometricTriangle = 2,
EquilateralTriangle = 3,
RightTriangle = 4,
HalfCircle = 5
}
public enum HollowShape : byte
{
Same = 0,
Circle = 16,
Square = 32,
Triangle = 48
}
public enum PCodeEnum : byte
{
Primitive = 9,
Avatar = 47,
Grass = 95,
NewTree = 111,
ParticleSystem = 143,
Tree = 255
}
public enum Extrusion : byte
{
Straight = 16,
Curve1 = 32,
Curve2 = 48,
Flexible = 128
}
[Serializable]
public class PrimitiveBaseShape
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly byte[] DEFAULT_TEXTURE = new Primitive.TextureEntry(new UUID("89556747-24cb-43ed-920b-47caed15465f")).GetBytes();
private byte[] m_textureEntry;
private ushort _pathBegin;
private byte _pathCurve;
private ushort _pathEnd;
private sbyte _pathRadiusOffset;
private byte _pathRevolutions;
private byte _pathScaleX;
private byte _pathScaleY;
private byte _pathShearX;
private byte _pathShearY;
private sbyte _pathSkew;
private sbyte _pathTaperX;
private sbyte _pathTaperY;
private sbyte _pathTwist;
private sbyte _pathTwistBegin;
private byte _pCode;
private ushort _profileBegin;
private ushort _profileEnd;
private ushort _profileHollow;
private Vector3 _scale;
private byte _state;
private ProfileShape _profileShape;
private HollowShape _hollowShape;
// Sculpted
[XmlIgnore] private UUID _sculptTexture;
[XmlIgnore] private byte _sculptType;
[XmlIgnore] private byte[] _sculptData = Utils.EmptyBytes;
// Flexi
[XmlIgnore] private int _flexiSoftness;
[XmlIgnore] private float _flexiTension;
[XmlIgnore] private float _flexiDrag;
[XmlIgnore] private float _flexiGravity;
[XmlIgnore] private float _flexiWind;
[XmlIgnore] private float _flexiForceX;
[XmlIgnore] private float _flexiForceY;
[XmlIgnore] private float _flexiForceZ;
//Bright n sparkly
[XmlIgnore] private float _lightColorR;
[XmlIgnore] private float _lightColorG;
[XmlIgnore] private float _lightColorB;
[XmlIgnore] private float _lightColorA = 1.0f;
[XmlIgnore] private float _lightRadius;
[XmlIgnore] private float _lightCutoff;
[XmlIgnore] private float _lightFalloff;
[XmlIgnore] private float _lightIntensity = 1.0f;
[XmlIgnore] private bool _flexiEntry;
[XmlIgnore] private bool _lightEntry;
[XmlIgnore] private bool _sculptEntry;
public byte ProfileCurve
{
get { return (byte)((byte)HollowShape | (byte)ProfileShape); }
set
{
// Handle hollow shape component
byte hollowShapeByte = (byte)(value & 0xf0);
if (!Enum.IsDefined(typeof(HollowShape), hollowShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.",
hollowShapeByte);
this._hollowShape = HollowShape.Same;
}
else
{
this._hollowShape = (HollowShape)hollowShapeByte;
}
// Handle profile shape component
byte profileShapeByte = (byte)(value & 0xf);
if (!Enum.IsDefined(typeof(ProfileShape), profileShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.",
profileShapeByte);
this._profileShape = ProfileShape.Square;
}
else
{
this._profileShape = (ProfileShape)profileShapeByte;
}
}
}
public PrimitiveBaseShape()
{
PCode = (byte) PCodeEnum.Primitive;
ExtraParams = new byte[1];
m_textureEntry = DEFAULT_TEXTURE;
}
public PrimitiveBaseShape(bool noShape)
{
if (noShape)
return;
PCode = (byte)PCodeEnum.Primitive;
ExtraParams = new byte[1];
m_textureEntry = DEFAULT_TEXTURE;
}
public PrimitiveBaseShape(Primitive prim)
{
PCode = (byte)prim.PrimData.PCode;
ExtraParams = new byte[1];
State = prim.PrimData.State;
PathBegin = Primitive.PackBeginCut(prim.PrimData.PathBegin);
PathEnd = Primitive.PackEndCut(prim.PrimData.PathEnd);
PathScaleX = Primitive.PackPathScale(prim.PrimData.PathScaleX);
PathScaleY = Primitive.PackPathScale(prim.PrimData.PathScaleY);
PathShearX = (byte)Primitive.PackPathShear(prim.PrimData.PathShearX);
PathShearY = (byte)Primitive.PackPathShear(prim.PrimData.PathShearY);
PathSkew = Primitive.PackPathTwist(prim.PrimData.PathSkew);
ProfileBegin = Primitive.PackBeginCut(prim.PrimData.ProfileBegin);
ProfileEnd = Primitive.PackEndCut(prim.PrimData.ProfileEnd);
Scale = prim.Scale;
PathCurve = (byte)prim.PrimData.PathCurve;
ProfileCurve = (byte)prim.PrimData.ProfileCurve;
ProfileHollow = Primitive.PackProfileHollow(prim.PrimData.ProfileHollow);
PathRadiusOffset = Primitive.PackPathTwist(prim.PrimData.PathRadiusOffset);
PathRevolutions = Primitive.PackPathRevolutions(prim.PrimData.PathRevolutions);
PathTaperX = Primitive.PackPathTaper(prim.PrimData.PathTaperX);
PathTaperY = Primitive.PackPathTaper(prim.PrimData.PathTaperY);
PathTwist = Primitive.PackPathTwist(prim.PrimData.PathTwist);
PathTwistBegin = Primitive.PackPathTwist(prim.PrimData.PathTwistBegin);
m_textureEntry = prim.Textures.GetBytes();
SculptEntry = (prim.Sculpt.Type != OpenMetaverse.SculptType.None);
SculptData = prim.Sculpt.GetBytes();
SculptTexture = prim.Sculpt.SculptTexture;
SculptType = (byte)prim.Sculpt.Type;
}
[XmlIgnore]
public Primitive.TextureEntry Textures
{
get
{
//m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length);
try { return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length); }
catch { }
m_log.Warn("[SHAPE]: Failed to decode texture, length=" + ((m_textureEntry != null) ? m_textureEntry.Length : 0));
return new Primitive.TextureEntry(null);
}
set { m_textureEntry = value.GetBytes(); }
}
public byte[] TextureEntry
{
get { return m_textureEntry; }
set
{
if (value == null)
m_textureEntry = new byte[1];
else
m_textureEntry = value;
}
}
public static PrimitiveBaseShape Default
{
get
{
PrimitiveBaseShape boxShape = CreateBox();
boxShape.SetScale(0.5f);
return boxShape;
}
}
public static PrimitiveBaseShape Create()
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
return shape;
}
public static PrimitiveBaseShape CreateBox()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Straight;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateSphere()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.HalfCircle;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateCylinder()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public void SetScale(float side)
{
_scale = new Vector3(side, side, side);
}
public void SetHeigth(float heigth)
{
_scale.Z = heigth;
}
public void SetRadius(float radius)
{
_scale.X = _scale.Y = radius * 2f;
}
// TODO: void returns need to change of course
public virtual void GetMesh()
{
}
public PrimitiveBaseShape Copy()
{
return (PrimitiveBaseShape) MemberwiseClone();
}
public static PrimitiveBaseShape CreateCylinder(float radius, float heigth)
{
PrimitiveBaseShape shape = CreateCylinder();
shape.SetHeigth(heigth);
shape.SetRadius(radius);
return shape;
}
public void SetPathRange(Vector3 pathRange)
{
_pathBegin = Primitive.PackBeginCut(pathRange.X);
_pathEnd = Primitive.PackEndCut(pathRange.Y);
}
public void SetPathRange(float begin, float end)
{
_pathBegin = Primitive.PackBeginCut(begin);
_pathEnd = Primitive.PackEndCut(end);
}
public void SetSculptData(byte sculptType, UUID SculptTextureUUID)
{
_sculptType = sculptType;
_sculptTexture = SculptTextureUUID;
}
public void SetProfileRange(Vector3 profileRange)
{
_profileBegin = Primitive.PackBeginCut(profileRange.X);
_profileEnd = Primitive.PackEndCut(profileRange.Y);
}
public void SetProfileRange(float begin, float end)
{
_profileBegin = Primitive.PackBeginCut(begin);
_profileEnd = Primitive.PackEndCut(end);
}
public byte[] ExtraParams
{
get
{
return ExtraParamsToBytes();
}
set
{
ReadInExtraParamsBytes(value);
}
}
public ushort PathBegin {
get {
return _pathBegin;
}
set {
_pathBegin = value;
}
}
public byte PathCurve {
get {
return _pathCurve;
}
set {
_pathCurve = value;
}
}
public ushort PathEnd {
get {
return _pathEnd;
}
set {
_pathEnd = value;
}
}
public sbyte PathRadiusOffset {
get {
return _pathRadiusOffset;
}
set {
_pathRadiusOffset = value;
}
}
public byte PathRevolutions {
get {
return _pathRevolutions;
}
set {
_pathRevolutions = value;
}
}
public byte PathScaleX {
get {
return _pathScaleX;
}
set {
_pathScaleX = value;
}
}
public byte PathScaleY {
get {
return _pathScaleY;
}
set {
_pathScaleY = value;
}
}
public byte PathShearX {
get {
return _pathShearX;
}
set {
_pathShearX = value;
}
}
public byte PathShearY {
get {
return _pathShearY;
}
set {
_pathShearY = value;
}
}
public sbyte PathSkew {
get {
return _pathSkew;
}
set {
_pathSkew = value;
}
}
public sbyte PathTaperX {
get {
return _pathTaperX;
}
set {
_pathTaperX = value;
}
}
public sbyte PathTaperY {
get {
return _pathTaperY;
}
set {
_pathTaperY = value;
}
}
public sbyte PathTwist {
get {
return _pathTwist;
}
set {
_pathTwist = value;
}
}
public sbyte PathTwistBegin {
get {
return _pathTwistBegin;
}
set {
_pathTwistBegin = value;
}
}
public byte PCode {
get {
return _pCode;
}
set {
_pCode = value;
}
}
public ushort ProfileBegin {
get {
return _profileBegin;
}
set {
_profileBegin = value;
}
}
public ushort ProfileEnd {
get {
return _profileEnd;
}
set {
_profileEnd = value;
}
}
public ushort ProfileHollow {
get {
return _profileHollow;
}
set {
_profileHollow = value;
}
}
public Vector3 Scale {
get {
return _scale;
}
set {
_scale = value;
}
}
public byte State {
get {
return _state;
}
set {
_state = value;
}
}
public ProfileShape ProfileShape {
get {
return _profileShape;
}
set {
_profileShape = value;
}
}
public HollowShape HollowShape {
get {
return _hollowShape;
}
set {
_hollowShape = value;
}
}
public UUID SculptTexture {
get {
return _sculptTexture;
}
set {
_sculptTexture = value;
}
}
public byte SculptType {
get {
return _sculptType;
}
set {
_sculptType = value;
}
}
public byte[] SculptData {
get {
return _sculptData;
}
set {
_sculptData = value;
}
}
public int FlexiSoftness {
get {
return _flexiSoftness;
}
set {
_flexiSoftness = value;
}
}
public float FlexiTension {
get {
return _flexiTension;
}
set {
_flexiTension = value;
}
}
public float FlexiDrag {
get {
return _flexiDrag;
}
set {
_flexiDrag = value;
}
}
public float FlexiGravity {
get {
return _flexiGravity;
}
set {
_flexiGravity = value;
}
}
public float FlexiWind {
get {
return _flexiWind;
}
set {
_flexiWind = value;
}
}
public float FlexiForceX {
get {
return _flexiForceX;
}
set {
_flexiForceX = value;
}
}
public float FlexiForceY {
get {
return _flexiForceY;
}
set {
_flexiForceY = value;
}
}
public float FlexiForceZ {
get {
return _flexiForceZ;
}
set {
_flexiForceZ = value;
}
}
public float LightColorR {
get {
return _lightColorR;
}
set {
_lightColorR = value;
}
}
public float LightColorG {
get {
return _lightColorG;
}
set {
_lightColorG = value;
}
}
public float LightColorB {
get {
return _lightColorB;
}
set {
_lightColorB = value;
}
}
public float LightColorA {
get {
return _lightColorA;
}
set {
_lightColorA = value;
}
}
public float LightRadius {
get {
return _lightRadius;
}
set {
_lightRadius = value;
}
}
public float LightCutoff {
get {
return _lightCutoff;
}
set {
_lightCutoff = value;
}
}
public float LightFalloff {
get {
return _lightFalloff;
}
set {
_lightFalloff = value;
}
}
public float LightIntensity {
get {
return _lightIntensity;
}
set {
_lightIntensity = value;
}
}
public bool FlexiEntry {
get {
return _flexiEntry;
}
set {
_flexiEntry = value;
}
}
public bool LightEntry {
get {
return _lightEntry;
}
set {
_lightEntry = value;
}
}
public bool SculptEntry {
get {
return _sculptEntry;
}
set {
_sculptEntry = value;
}
}
public byte[] ExtraParamsToBytes()
{
ushort FlexiEP = 0x10;
ushort LightEP = 0x20;
ushort SculptEP = 0x30;
int i = 0;
uint TotalBytesLength = 1; // ExtraParamsNum
uint ExtraParamsNum = 0;
if (_flexiEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_lightEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_sculptEntry)
{
ExtraParamsNum++;
TotalBytesLength += 17;// data
TotalBytesLength += 2 + 4; // type
}
byte[] returnbytes = new byte[TotalBytesLength];
// uint paramlength = ExtraParamsNum;
// Stick in the number of parameters
returnbytes[i++] = (byte)ExtraParamsNum;
if (_flexiEntry)
{
byte[] FlexiData = GetFlexiBytes();
returnbytes[i++] = (byte)(FlexiEP % 256);
returnbytes[i++] = (byte)((FlexiEP >> 8) % 256);
returnbytes[i++] = (byte)(FlexiData.Length % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 8) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 16) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 24) % 256);
Array.Copy(FlexiData, 0, returnbytes, i, FlexiData.Length);
i += FlexiData.Length;
}
if (_lightEntry)
{
byte[] LightData = GetLightBytes();
returnbytes[i++] = (byte)(LightEP % 256);
returnbytes[i++] = (byte)((LightEP >> 8) % 256);
returnbytes[i++] = (byte)(LightData.Length % 256);
returnbytes[i++] = (byte)((LightData.Length >> 8) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 16) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 24) % 256);
Array.Copy(LightData, 0, returnbytes, i, LightData.Length);
i += LightData.Length;
}
if (_sculptEntry)
{
byte[] SculptData = GetSculptBytes();
returnbytes[i++] = (byte)(SculptEP % 256);
returnbytes[i++] = (byte)((SculptEP >> 8) % 256);
returnbytes[i++] = (byte)(SculptData.Length % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 8) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 16) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 24) % 256);
Array.Copy(SculptData, 0, returnbytes, i, SculptData.Length);
i += SculptData.Length;
}
if (!_flexiEntry && !_lightEntry && !_sculptEntry)
{
byte[] returnbyte = new byte[1];
returnbyte[0] = 0;
return returnbyte;
}
return returnbytes;
//m_log.Info("[EXTRAPARAMS]: Length = " + m_shape.ExtraParams.Length.ToString());
}
public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data)
{
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
switch (type)
{
case FlexiEP:
if (!inUse)
{
_flexiEntry = false;
return;
}
ReadFlexiData(data, 0);
break;
case LightEP:
if (!inUse)
{
_lightEntry = false;
return;
}
ReadLightData(data, 0);
break;
case SculptEP:
if (!inUse)
{
_sculptEntry = false;
return;
}
ReadSculptData(data, 0);
break;
}
}
public void ReadInExtraParamsBytes(byte[] data)
{
if (data == null || data.Length == 1)
return;
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
bool lGotFlexi = false;
bool lGotLight = false;
bool lGotSculpt = false;
int i = 0;
byte extraParamCount = 0;
if (data.Length > 0)
{
extraParamCount = data[i++];
}
for (int k = 0; k < extraParamCount; k++)
{
ushort epType = Utils.BytesToUInt16(data, i);
i += 2;
// uint paramLength = Helpers.BytesToUIntBig(data, i);
i += 4;
switch (epType)
{
case FlexiEP:
ReadFlexiData(data, i);
i += 16;
lGotFlexi = true;
break;
case LightEP:
ReadLightData(data, i);
i += 16;
lGotLight = true;
break;
case SculptEP:
ReadSculptData(data, i);
i += 17;
lGotSculpt = true;
break;
}
}
if (!lGotFlexi)
_flexiEntry = false;
if (!lGotLight)
_lightEntry = false;
if (!lGotSculpt)
_sculptEntry = false;
}
public void ReadSculptData(byte[] data, int pos)
{
byte[] SculptTextureUUID = new byte[16];
UUID SculptUUID = UUID.Zero;
byte SculptTypel = data[16+pos];
if (data.Length+pos >= 17)
{
_sculptEntry = true;
SculptTextureUUID = new byte[16];
SculptTypel = data[16 + pos];
Array.Copy(data, pos, SculptTextureUUID,0, 16);
SculptUUID = new UUID(SculptTextureUUID, 0);
}
else
{
_sculptEntry = false;
SculptUUID = UUID.Zero;
SculptTypel = 0x00;
}
if (_sculptEntry)
{
if (_sculptType != (byte)1 && _sculptType != (byte)2 && _sculptType != (byte)3 && _sculptType != (byte)4)
_sculptType = 4;
}
_sculptTexture = SculptUUID;
_sculptType = SculptTypel;
//m_log.Info("[SCULPT]:" + SculptUUID.ToString());
}
public byte[] GetSculptBytes()
{
byte[] data = new byte[17];
_sculptTexture.GetBytes().CopyTo(data, 0);
data[16] = (byte)_sculptType;
return data;
}
public void ReadFlexiData(byte[] data, int pos)
{
if (data.Length-pos >= 16)
{
_flexiEntry = true;
_flexiSoftness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
_flexiTension = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiDrag = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiGravity = (float)(data[pos++] / 10.0f) - 10.0f;
_flexiWind = (float)data[pos++] / 10.0f;
Vector3 lForce = new Vector3(data, pos);
_flexiForceX = lForce.X;
_flexiForceY = lForce.Y;
_flexiForceZ = lForce.Z;
}
else
{
_flexiEntry = false;
_flexiSoftness = 0;
_flexiTension = 0.0f;
_flexiDrag = 0.0f;
_flexiGravity = 0.0f;
_flexiWind = 0.0f;
_flexiForceX = 0f;
_flexiForceY = 0f;
_flexiForceZ = 0f;
}
}
public byte[] GetFlexiBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((_flexiSoftness & 2) << 6);
data[i + 1] = (byte)((_flexiSoftness & 1) << 7);
data[i++] |= (byte)((byte)(_flexiTension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(_flexiDrag * 10.01f) & 0x7F);
data[i++] = (byte)((_flexiGravity + 10.0f) * 10.01f);
data[i++] = (byte)(_flexiWind * 10.01f);
Vector3 lForce = new Vector3(_flexiForceX, _flexiForceY, _flexiForceZ);
lForce.GetBytes().CopyTo(data, i);
return data;
}
public void ReadLightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
_lightEntry = true;
Color4 lColor = new Color4(data, pos, false);
_lightIntensity = lColor.A;
_lightColorA = 1f;
_lightColorR = lColor.R;
_lightColorG = lColor.G;
_lightColorB = lColor.B;
_lightRadius = Utils.BytesToFloat(data, pos + 4);
_lightCutoff = Utils.BytesToFloat(data, pos + 8);
_lightFalloff = Utils.BytesToFloat(data, pos + 12);
}
else
{
_lightEntry = false;
_lightColorA = 1f;
_lightColorR = 0f;
_lightColorG = 0f;
_lightColorB = 0f;
_lightRadius = 0f;
_lightCutoff = 0f;
_lightFalloff = 0f;
_lightIntensity = 0f;
}
}
public byte[] GetLightBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
Color4 tmpColor = new Color4(_lightColorR,_lightColorG,_lightColorB,_lightIntensity);
tmpColor.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_lightRadius).CopyTo(data, 4);
Utils.FloatToBytes(_lightCutoff).CopyTo(data, 8);
Utils.FloatToBytes(_lightFalloff).CopyTo(data, 12);
return data;
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <returns></returns>
public Primitive ToOmvPrimitive()
{
// position and rotation defaults here since they are not available in PrimitiveBaseShape
return ToOmvPrimitive(new Vector3(0.0f, 0.0f, 0.0f),
new Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <param name="position"></param>
/// <param name="rotation"></param>
/// <returns></returns>
public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation)
{
OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive();
prim.Scale = this.Scale;
prim.Position = position;
prim.Rotation = rotation;
if (this.SculptEntry)
{
prim.Sculpt = new Primitive.SculptData();
prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType;
prim.Sculpt.SculptTexture = this.SculptTexture;
}
prim.PrimData.PathShearX = this.PathShearX < 128 ? (float)this.PathShearX * 0.01f : (float)(this.PathShearX - 256) * 0.01f;
prim.PrimData.PathShearY = this.PathShearY < 128 ? (float)this.PathShearY * 0.01f : (float)(this.PathShearY - 256) * 0.01f;
prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f;
prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f;
prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f;
prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f;
prim.PrimData.PathTaperX = this.PathTaperX * 0.01f;
prim.PrimData.PathTaperY = this.PathTaperY * 0.01f;
prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f;
prim.PrimData.PathTwist = this.PathTwist * 0.01f;
prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f;
prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f;
prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f;
prim.PrimData.profileCurve = this.ProfileCurve;
prim.PrimData.ProfileHole = (HoleType)this.HollowShape;
prim.PrimData.PathCurve = (PathCurve)this.PathCurve;
prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset;
prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions;
prim.PrimData.PathSkew = 0.01f * this.PathSkew;
prim.PrimData.PCode = OpenMetaverse.PCode.Prim;
prim.PrimData.State = 0;
if (this.FlexiEntry)
{
prim.Flexible = new Primitive.FlexibleData();
prim.Flexible.Drag = this.FlexiDrag;
prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ);
prim.Flexible.Gravity = this.FlexiGravity;
prim.Flexible.Softness = this.FlexiSoftness;
prim.Flexible.Tension = this.FlexiTension;
prim.Flexible.Wind = this.FlexiWind;
}
if (this.LightEntry)
{
prim.Light = new Primitive.LightData();
prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA);
prim.Light.Cutoff = this.LightCutoff;
prim.Light.Falloff = this.LightFalloff;
prim.Light.Intensity = this.LightIntensity;
prim.Light.Radius = this.LightRadius;
}
prim.Textures = this.Textures;
prim.Properties = new Primitive.ObjectProperties();
prim.Properties.Name = "Primitive";
prim.Properties.Description = "";
prim.Properties.CreatorID = UUID.Zero;
prim.Properties.GroupID = UUID.Zero;
prim.Properties.OwnerID = UUID.Zero;
prim.Properties.Permissions = new Permissions();
prim.Properties.SalePrice = 10;
prim.Properties.SaleType = new SaleType();
return prim;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Hydra.Framework.Conversions
{
//
// **********************************************************************
/// <summary>
/// Utility methods to work with floating point numerics (float, decimal, etc.)
/// </summary>
// **********************************************************************
//
public class ConvertFloat
{
#region Static Methods
//
// **********************************************************************
/// <summary>
/// Converts string to decimal. Returns defValue if conversion failed.
/// </summary>
/// <param name="s">string to parse as decimal</param>
/// <param name="defValue">value to return if conversion failed</param>
/// <returns>
/// parse value or default value if conversion failed
/// </returns>
// **********************************************************************
//
static public Decimal ParseDecimal_dotSeparator(string s, Decimal defValue)
{
if (ConvertUtils.NotEmpty(s))
{
Decimal result;
if (Decimal.TryParse(s.Trim(), NumberStyles.Number, GetConstantFormatProvider(), out result))
return result;
}
return defValue;
}
//
// **********************************************************************
/// <summary>
/// Converts string to decimal. Returns defValue if conversion failed.
/// </summary>
/// <param name="s">string to parse as decimal</param>
/// <param name="defValue">value to return if conversion failed</param>
/// <returns>
/// parse value or default value if conversion failed
/// </returns>
// **********************************************************************
//
static public Decimal ParseDecimal(string s, Decimal defValue)
{
if (ConvertUtils.NotEmpty(s))
{
Decimal result;
if (Decimal.TryParse(s.Trim(), out result))
return result;
}
return defValue;
}
//
// **********************************************************************
/// <summary>
/// Converts string to decimal. Returns defValue if conversion failed.
/// </summary>
/// <param name="o">object to parse as decimal</param>
/// <param name="defValue">value to return if conversion failed</param>
/// <returns>
/// parse value or default value if conversion failed
/// </returns>
// **********************************************************************
//
static public Decimal ParseDecimal(object o, Decimal defValue)
{
if (ConvertUtils.IsEmpty(o))
return defValue;
if (o is string)
return ParseDecimal((string)o, defValue);
try
{
return Convert.ToDecimal(o);
}
catch (Exception)
{
return defValue;
}
}
//
// **********************************************************************
/// <summary>
/// Converts string to float. Returns defValue if conversion failed.
/// </summary>
/// <param name="s">string to parse as float</param>
/// <param name="defValue">value to return if conversion failed</param>
/// <returns>
/// parse value or default value if conversion failed
/// </returns>
// **********************************************************************
//
static public float ParseFloat(string s, float defValue)
{
if (ConvertUtils.NotEmpty(s))
{
float result;
if (float.TryParse(s.Trim(), out result))
return result;
}
return defValue;
}
//
// **********************************************************************
/// <summary>
/// Converts string to float. Returns defValue if conversion failed.
/// </summary>
/// <param name="o">object to parse as float</param>
/// <param name="defValue">value to return if conversion failed</param>
/// <returns>
/// parse value or default value if conversion failed
/// </returns>
// **********************************************************************
//
static public float ParseFloat(object o, float defValue)
{
if (ConvertUtils.IsEmpty(o))
return defValue;
if (o is string)
return ParseFloat((string)o, defValue);
try
{
return Convert.ToSingle(o);
}
catch (Exception)
{
return defValue;
}
}
//
// **********************************************************************
/// <summary>
/// Converts string to double. Returns defValue if conversion failed.
/// </summary>
/// <param name="s">string to parse as double</param>
/// <param name="defValue">value to return if conversion failed</param>
/// <returns>
/// parse value or default value if conversion failed
/// </returns>
// **********************************************************************
//
static public double ParseDouble(string s, double defValue)
{
if (ConvertUtils.NotEmpty(s))
{
double result;
if (double.TryParse(s.Trim(), out result))
return result;
}
return defValue;
}
//
// **********************************************************************
/// <summary>
/// Converts string to double. Returns defValue if conversion failed.
/// </summary>
/// <param name="o">object to parse as double</param>
/// <param name="defValue">value to return if conversion failed</param>
/// <returns>
/// parse value or default value if conversion failed
/// </returns>
// **********************************************************************
//
static public double ParseDouble(object o, double defValue)
{
if (ConvertUtils.IsEmpty(o))
return defValue;
if (o is string)
return ParseDouble((string)o, defValue);
try
{
return Convert.ToDouble(o);
}
catch (Exception)
{
return defValue;
}
}
//
// **********************************************************************
/// <summary>
/// Return format provider for internal float constant convertation.
/// Provides '.' decimal separator and empty group separator.
/// </summary>
/// <returns>format provider</returns>
// **********************************************************************
//
static public IFormatProvider GetConstantFormatProvider()
{
IFormatProvider fp = (IFormatProvider)NumberFormatInfo.CurrentInfo.Clone();
((NumberFormatInfo)fp).NumberDecimalSeparator = ".";
((NumberFormatInfo)fp).NumberGroupSeparator = "";
return fp;
}
//
// **********************************************************************
/// <summary>
/// Parses float constant with the '.' decimal separator and empty group separator.
/// Raises exception if convertion falied.
/// </summary>
/// <param name="constant">constant string</param>
/// <returns>converted float value</returns>
// **********************************************************************
//
static public float ParseFloatConst(string constant)
{
return float.Parse(constant, GetConstantFormatProvider());
}
//
// **********************************************************************
/// <summary>
/// Parses decimal constant with the '.' decimal separator and empty group separator.
/// Raises exception if convertion falied.
/// </summary>
/// <param name="constant">constant string</param>
/// <returns>converted float value</returns>
// **********************************************************************
//
static public Decimal ParseDecimalConst(string constant)
{
return Decimal.Parse(constant, GetConstantFormatProvider());
}
//
// **********************************************************************
/// <summary>
/// Returns value converted to string with '.' decimal separator and empty group separator.
/// </summary>
/// <param name="value">value to convert</param>
/// <returns>string representation of the value</returns>
// **********************************************************************
//
static public string ToConst(float value)
{
return value.ToString(GetConstantFormatProvider());
}
//
// **********************************************************************
/// <summary>
/// Returns value converted to string with '.' decimal separator and empty group separator.
/// </summary>
/// <param name="value">value to convert</param>
/// <returns>string representation of the value</returns>
// **********************************************************************
//
static public string ToConst(double value)
{
return value.ToString(GetConstantFormatProvider());
}
//
// **********************************************************************
/// <summary>
/// Rounds the given value to the provided number of decimal digits.
/// Uses "normal" method (0.5 -> 1) instead of based on IEEE 754 standard.
/// </summary>
/// <param name="d">value to round</param>
/// <param name="decimals">number of decinal digits to remain</param>
/// <returns>
/// the given value rounded to the given number of decimal digits
/// </returns>
// **********************************************************************
//
static public decimal Round(decimal d, int decimals)
{
decimal mult = 1;
for (int i = decimals; i < 0; i++)
mult /= 10m;
for (int i = 0; i < decimals; i++)
mult *= 10m;
decimal value = Math.Abs(d * mult);
decimal floor = Convert.ToDecimal(Math.Floor(Convert.ToDouble(value)));
decimal ceiling = Convert.ToDecimal(Math.Ceiling(Convert.ToDouble(value)));
decimal result = (value - floor < ceiling - value ? floor : ceiling) / mult * Math.Sign(d);
return result;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.Experimental.VFX;
namespace UnityEditor.VFX
{
abstract class VFXExpressionNumericOperation : VFXExpression
{
protected VFXExpressionNumericOperation(VFXExpression[] parents)
: base(Flags.None, parents)
{
m_additionnalOperands = new int[] {};
}
static private object[] ToObjectArray(float input) { return new object[] { input }; }
static private object[] ToObjectArray(Vector2 input) { return new object[] { input.x, input.y }; }
static private object[] ToObjectArray(Vector3 input) { return new object[] { input.x, input.y, input.z }; }
static private object[] ToObjectArray(Vector4 input) { return new object[] { input.x, input.y, input.z, input.w }; }
static protected object[] ToObjectArray(VFXExpression input)
{
switch (input.valueType)
{
case VFXValueType.Float: return ToObjectArray(input.Get<float>());
case VFXValueType.Float2: return ToObjectArray(input.Get<Vector2>());
case VFXValueType.Float3: return ToObjectArray(input.Get<Vector3>());
case VFXValueType.Float4: return ToObjectArray(input.Get<Vector4>());
case VFXValueType.Int32: return new object[] { input.Get<int>() };
case VFXValueType.Uint32: return new object[] { input.Get<uint>() };
case VFXValueType.Boolean: return new object[] { input.Get<bool>() };
}
return null;
}
static protected VFXExpression ToVFXValue(object[] input, VFXValue.Mode mode)
{
if (input[0] is int)
{
if (input.Length != 1)
throw new InvalidOperationException("VFXExpressionMathOperation : Unexpected size of int");
return new VFXValue<int>((int)input[0], mode);
}
else if (input[0] is uint)
{
if (input.Length != 1)
throw new InvalidOperationException("VFXExpressionMathOperation : Unexpected size of uint");
return new VFXValue<uint>((uint)input[0], mode);
}
else if (input[0] is bool)
{
if (input.Length != 1)
throw new InvalidOperationException("VFXExpressionMathOperation : Unexpected size of bool");
return new VFXValue<bool>((bool)input[0], mode);
}
else if (input[0] is float)
{
if (input.OfType<float>().Count() != input.Length)
throw new InvalidOperationException("VFXExpressionMathOperation : Unexpected type of float among other float");
switch (input.Length)
{
case 1: return new VFXValue<float>((float)input[0], mode);
case 2: return new VFXValue<Vector2>(new Vector2((float)input[0], (float)input[1]), mode);
case 3: return new VFXValue<Vector3>(new Vector3((float)input[0], (float)input[1], (float)input[2]), mode);
case 4: return new VFXValue<Vector4>(new Vector4((float)input[0], (float)input[1], (float)input[2], (float)input[3]), mode);
}
}
return null;
}
static protected bool IsNumeric(VFXValueType type)
{
return IsFloatValueType(type) || IsUIntValueType(type) || IsIntValueType(type) || IsBoolValueType(type);
}
sealed public override VFXExpressionOperation operation { get { return m_Operation; } }
sealed protected override int[] additionnalOperands { get { return m_additionnalOperands; } }
protected override VFXExpression Reduce(VFXExpression[] reducedParents)
{
var newExpression = (VFXExpressionNumericOperation)base.Reduce(reducedParents);
newExpression.m_additionnalOperands = m_additionnalOperands.Select(o => o).ToArray();
newExpression.m_Operation = m_Operation;
return newExpression;
}
protected int[] m_additionnalOperands;
protected VFXExpressionOperation m_Operation;
}
abstract class VFXExpressionUnaryNumericOperation : VFXExpressionNumericOperation
{
protected VFXExpressionUnaryNumericOperation(VFXExpression parent, VFXExpressionOperation operation) : base(new VFXExpression[1] { parent })
{
if (!IsNumeric(parent.valueType))
{
throw new ArgumentException("Incorrect VFXExpressionUnaryMathOperation");
}
m_additionnalOperands = new int[] { (int)parent.valueType };
m_Operation = operation;
}
sealed protected override VFXExpression Evaluate(VFXExpression[] reducedParents)
{
var source = ToObjectArray(reducedParents[0]);
var result = new object[source.Length];
if (source[0] is float)
{
result = source.Select(o => (object)ProcessUnaryOperation((float)o)).ToArray();
}
else if (source[0] is int)
{
result = source.Select(o => (object)ProcessUnaryOperation((int)o)).ToArray();
}
else if (source[0] is uint)
{
result = source.Select(o => (object)ProcessUnaryOperation((uint)o)).ToArray();
}
else if (source[0] is bool)
{
result = source.Select(o => (object)ProcessUnaryOperation((bool)o)).ToArray();
}
else
{
throw new InvalidOperationException("Unexpected type in VFXExpressionUnaryMathOperation");
}
return ToVFXValue(result, VFXValue.Mode.Constant);
}
abstract protected float ProcessUnaryOperation(float input);
abstract protected int ProcessUnaryOperation(int input);
abstract protected uint ProcessUnaryOperation(uint input);
abstract protected bool ProcessUnaryOperation(bool input);
sealed public override string GetCodeString(string[] parents)
{
var valueType = this.parents.First().valueType;
valueType = IsFloatValueType(valueType) ? VFXValueType.Float : valueType;
return GetUnaryOperationCode(parents[0], valueType);
}
abstract protected string GetUnaryOperationCode(string x, VFXValueType type);
}
abstract class VFXExpressionBinaryNumericOperation : VFXExpressionNumericOperation
{
protected VFXExpressionBinaryNumericOperation(VFXExpression parentLeft, VFXExpression parentRight, VFXExpressionOperation operation)
: base(new VFXExpression[2] { parentLeft, parentRight })
{
if (!IsNumeric(parentLeft.valueType) || !IsNumeric(parentRight.valueType))
{
throw new ArgumentException("Incorrect VFXExpressionBinaryMathOperation (not numeric type)");
}
if (parentRight.valueType != parentLeft.valueType)
{
throw new ArgumentException("Incorrect VFXExpressionBinaryFloatOperation (incompatible numeric type)");
}
m_additionnalOperands = new int[] { (int)parentLeft.valueType };
m_Operation = operation;
}
sealed protected override VFXExpression Evaluate(VFXExpression[] reducedParents)
{
var parentLeft = reducedParents[0];
var parentRight = reducedParents[1];
var sourceLeft = ToObjectArray(parentLeft);
var sourceRight = ToObjectArray(parentRight);
var result = new object[sourceLeft.Length];
if (sourceLeft[0] is float)
{
for (int iChannel = 0; iChannel < sourceLeft.Length; ++iChannel)
{
result[iChannel] = ProcessBinaryOperation((float)sourceLeft[iChannel], (float)sourceRight[iChannel]);
}
}
else if (sourceLeft[0] is int)
{
for (int iChannel = 0; iChannel < sourceLeft.Length; ++iChannel)
{
result[iChannel] = ProcessBinaryOperation((int)sourceLeft[iChannel], (int)sourceRight[iChannel]);
}
}
else if (sourceLeft[0] is uint)
{
for (int iChannel = 0; iChannel < sourceLeft.Length; ++iChannel)
{
result[iChannel] = ProcessBinaryOperation((uint)sourceLeft[iChannel], (uint)sourceRight[iChannel]);
}
}
else if (sourceLeft[0] is bool)
{
for (int iChannel = 0; iChannel < sourceLeft.Length; ++iChannel)
{
result[iChannel] = ProcessBinaryOperation((bool)sourceLeft[iChannel], (bool)sourceRight[iChannel]);
}
}
else
{
throw new InvalidOperationException("Unexpected type in VFXExpressionUnaryMathOperation");
}
return ToVFXValue(result, VFXValue.Mode.Constant);
}
abstract protected float ProcessBinaryOperation(float x, float y);
abstract protected int ProcessBinaryOperation(int x, int y);
abstract protected uint ProcessBinaryOperation(uint x, uint y);
abstract protected bool ProcessBinaryOperation(bool x, bool y);
sealed public override string GetCodeString(string[] parents)
{
var valueType = this.parents.First().valueType;
valueType = IsFloatValueType(valueType) ? VFXValueType.Float : valueType;
return GetBinaryOperationCode(parents[0], parents[1], valueType);
}
abstract protected string GetBinaryOperationCode(string x, string y, VFXValueType type);
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
namespace Mono.Cecil {
public class ExportedType : IMetadataTokenProvider {
string @namespace;
string name;
uint attributes;
IMetadataScope scope;
ModuleDefinition module;
int identifier;
ExportedType declaring_type;
internal MetadataToken token;
public string Namespace {
get { return @namespace; }
set { @namespace = value; }
}
public string Name {
get { return name; }
set { name = value; }
}
public TypeAttributes Attributes {
get { return (TypeAttributes) attributes; }
set { attributes = (uint) value; }
}
public IMetadataScope Scope {
get {
if (declaring_type != null)
return declaring_type.Scope;
return scope;
}
}
public ExportedType DeclaringType {
get { return declaring_type; }
set { declaring_type = value; }
}
public MetadataToken MetadataToken {
get { return token; }
set { token = value; }
}
public int Identifier {
get { return identifier; }
set { identifier = value; }
}
#region TypeAttributes
public bool IsNotPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }
}
public bool IsNestedPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }
}
public bool IsNestedPrivate {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }
}
public bool IsNestedFamily {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }
}
public bool IsNestedAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }
}
public bool IsNestedFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }
}
public bool IsNestedFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }
}
public bool IsAutoLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }
}
public bool IsSequentialLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }
}
public bool IsExplicitLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }
}
public bool IsClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }
}
public bool IsInterface {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }
}
public bool IsAbstract {
get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); }
}
public bool IsSealed {
get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); }
}
public bool IsImport {
get { return attributes.GetAttributes ((uint) TypeAttributes.Import); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); }
}
public bool IsSerializable {
get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); }
}
public bool IsAnsiClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }
}
public bool IsUnicodeClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }
}
public bool IsAutoClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }
}
public bool IsBeforeFieldInit {
get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); }
}
public bool HasSecurity {
get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); }
}
#endregion
public bool IsForwarder {
get { return attributes.GetAttributes ((uint) TypeAttributes.Forwarder); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Forwarder, value); }
}
public string FullName {
get {
var fullname = string.IsNullOrEmpty (@namespace)
? name
: @namespace + '.' + name;
if (declaring_type != null)
return declaring_type.FullName + "/" + fullname;
return fullname;
}
}
public ExportedType (string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
{
this.@namespace = @namespace;
this.name = name;
this.scope = scope;
this.module = module;
}
public override string ToString ()
{
return FullName;
}
public TypeDefinition Resolve ()
{
return module.Resolve (CreateReference ());
}
internal TypeReference CreateReference ()
{
return new TypeReference (@namespace, name, module, scope) {
DeclaringType = declaring_type != null ? declaring_type.CreateReference () : null,
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Runtime.InteropServices;
// Taken from http://www.codeproject.com/Articles/23746/TreeView-with-Columns with minor tweaks
// and fixes for my purposes.
namespace TreelistView
{
public class VisualStyleItemBackground // can't find system provided visual style for this.
{
[StructLayout(LayoutKind.Sequential)]
public class RECT
{
public int left;
public int top;
public int right;
public int bottom;
public RECT()
{
}
public RECT(Rectangle r)
{
this.left = r.X;
this.top = r.Y;
this.right = r.Right;
this.bottom = r.Bottom;
}
}
[DllImport("uxtheme.dll", CharSet=CharSet.Auto)]
public static extern int DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int partId, int stateId, [In] RECT pRect, [In] RECT pClipRect);
[DllImport("uxtheme.dll", CharSet=CharSet.Auto)]
public static extern IntPtr OpenThemeData(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszClassList);
[DllImport("uxtheme.dll", CharSet=CharSet.Auto)]
public static extern int CloseThemeData(IntPtr hTheme);
//http://www.ookii.org/misc/vsstyle.h
//http://msdn2.microsoft.com/en-us/library/bb773210(VS.85).aspx
enum ITEMSTATES
{
LBPSI_HOT = 1,
LBPSI_HOTSELECTED = 2,
LBPSI_SELECTED = 3,
LBPSI_SELECTEDNOTFOCUS = 4,
};
enum LISTBOXPARTS
{
LBCP_BORDER_HSCROLL = 1,
LBCP_BORDER_HVSCROLL = 2,
LBCP_BORDER_NOSCROLL = 3,
LBCP_BORDER_VSCROLL = 4,
LBCP_ITEM = 5,
};
public enum Style
{
Normal,
Inactive, // when not focused
}
Style m_style;
public VisualStyleItemBackground(Style style)
{
m_style = style;
}
public void DrawBackground(Control owner, Graphics dc, Rectangle r, Color col)
{
/*
IntPtr themeHandle = OpenThemeData(owner.Handle, "Explorer");
if (themeHandle != IntPtr.Zero)
{
DrawThemeBackground(themeHandle, dc.GetHdc(), (int)LISTBOXPARTS.LBCP_ITEM, (int)ITEMSTATES.LBPSI_SELECTED, new RECT(r), new RECT(r));
dc.ReleaseHdc();
CloseThemeData(themeHandle);
return;
}
*/
Pen pen = new Pen(col);
GraphicsPath path = new GraphicsPath();
path.AddLine(r.Left + 2, r.Top, r.Right - 2, r.Top);
path.AddLine(r.Right, r.Top + 2, r.Right, r.Bottom - 2);
path.AddLine(r.Right - 2, r.Bottom, r.Left + 2, r.Bottom);
path.AddLine(r.Left, r.Bottom - 2, r.Left, r.Top + 2);
path.CloseFigure();
dc.DrawPath(pen, path);
//r.Inflate(-1, -1);
LinearGradientBrush brush = new LinearGradientBrush(r, Color.FromArgb(120, col), col, 90);
dc.FillRectangle(brush, r);
// for some reason in some cases the 'white' end of the gradient brush is drawn with the starting color
// therefore this redraw of the 'top' line of the rectangle
//dc.DrawLine(Pens.White, r.Left + 1, r.Top, r.Right - 1, r.Top);
pen.Dispose();
brush.Dispose();
path.Dispose();
}
}
public delegate string CellDataToString(TreeListColumn column, object data);
public class CellPainter
{
public static Rectangle AdjustRectangle(Rectangle r, Padding padding)
{
r.X += padding.Left;
r.Width -= padding.Left + padding.Right;
r.Y += padding.Top;
r.Height -= padding.Top + padding.Bottom;
return r;
}
protected TreeListView m_owner;
protected CellDataToString m_converter = null;
public CellDataToString CellDataConverter
{
get { return m_converter; }
set { m_converter = value; }
}
public CellPainter(TreeListView owner)
{
m_owner = owner;
}
public virtual void DrawSelectionBackground(Graphics dc, Rectangle nodeRect, Node node)
{
Point mousePoint = m_owner.PointToClient(Cursor.Position);
Node hoverNode = m_owner.CalcHitNode(mousePoint);
if (m_owner.NodesSelection.Contains(node) || m_owner.FocusedNode == node)
{
Color col = m_owner.Focused ? SystemColors.Highlight : SystemColors.Control;
if (!Application.RenderWithVisualStyles)
{
// have to fill the solid background only before the node is painted
dc.FillRectangle(SystemBrushes.FromSystemColor(col), nodeRect);
}
else
{
col = m_owner.Focused ? SystemColors.Highlight : Color.FromArgb(180, SystemColors.ControlDark);
// have to draw the transparent background after the node is painted
VisualStyleItemBackground.Style style = VisualStyleItemBackground.Style.Normal;
if (m_owner.Focused == false)
style = VisualStyleItemBackground.Style.Inactive;
VisualStyleItemBackground rendere = new VisualStyleItemBackground(style);
rendere.DrawBackground(m_owner, dc, nodeRect, col);
}
}
else if (hoverNode == node && m_owner.RowOptions.HoverHighlight)
{
Color col = SystemColors.ControlLight;
if (SystemInformation.HighContrast)
{
col = SystemColors.ButtonHighlight;
}
if (!Application.RenderWithVisualStyles)
{
// have to fill the solid background only before the node is painted
dc.FillRectangle(SystemBrushes.FromSystemColor(col), nodeRect);
}
else
{
// have to draw the transparent background after the node is painted
VisualStyleItemBackground.Style style = VisualStyleItemBackground.Style.Normal;
if (m_owner.Focused == false)
style = VisualStyleItemBackground.Style.Inactive;
VisualStyleItemBackground rendere = new VisualStyleItemBackground(style);
rendere.DrawBackground(m_owner, dc, nodeRect, col);
}
}
if (m_owner.Focused && (m_owner.FocusedNode == node))
{
nodeRect.Height += 1;
nodeRect.Inflate(-1,-1);
ControlPaint.DrawFocusRectangle(dc, nodeRect);
}
}
public virtual void PaintCellBackground(Graphics dc,
Rectangle cellRect,
Node node,
TreeListColumn column,
TreeList.TextFormatting format,
object data)
{
Color c = Color.Transparent;
Point mousePoint = m_owner.PointToClient(Cursor.Position);
Node hoverNode = m_owner.CalcHitNode(mousePoint);
if (format.BackColor != Color.Transparent)
c = format.BackColor;
if (!m_owner.NodesSelection.Contains(node) && m_owner.FocusedNode != node &&
!(hoverNode == node && m_owner.RowOptions.HoverHighlight) &&
node.DefaultBackColor != Color.Transparent)
c = node.DefaultBackColor;
if (node.BackColor != Color.Transparent && !m_owner.NodesSelection.Contains(node) && m_owner.SelectedNode != node)
c = node.BackColor;
if (column.Index < node.IndexedBackColor.Length && node.IndexedBackColor[column.Index] != Color.Transparent)
c = node.IndexedBackColor[column.Index];
if (c != Color.Transparent)
{
Rectangle r = cellRect;
r.X -= Math.Max(0, column.CalculatedRect.Width - cellRect.Width);
r.Width += Math.Max(0, column.CalculatedRect.Width - cellRect.Width);
SolidBrush brush = new SolidBrush(c);
dc.FillRectangle(brush, r);
brush.Dispose();
}
}
public virtual void PaintCellText(Graphics dc,
Rectangle cellRect,
Node node,
TreeListColumn column,
TreeList.TextFormatting format,
object data)
{
if (data != null)
{
cellRect = AdjustRectangle(cellRect, format.Padding);
//dc.DrawRectangle(Pens.Black, cellRect);
Color color = format.ForeColor;
if (node.ForeColor != Color.Transparent)
color = node.ForeColor;
if (m_owner.FocusedNode == node && Application.RenderWithVisualStyles == false && m_owner.Focused)
color = SystemColors.HighlightText;
TextFormatFlags flags= TextFormatFlags.EndEllipsis | format.GetFormattingFlags();
Font f = m_owner.Font;
Font disposefont = null;
if(node.Bold && node.Italic)
disposefont = f = new Font(f, FontStyle.Bold|FontStyle.Italic);
else if (node.Bold)
disposefont = f = new Font(f, FontStyle.Bold);
else if (node.Italic)
disposefont = f = new Font(f, FontStyle.Italic);
string datastring = "";
if(m_converter != null)
datastring = m_converter(column, data);
else
datastring = data.ToString();
TextRenderer.DrawText(dc, datastring, f, cellRect, color, flags);
Size sz = TextRenderer.MeasureText(dc, datastring, f, new Size(1000000, 10000), flags);
int treecolumn = node.TreeColumn;
if (treecolumn < 0)
treecolumn = node.OwnerView.TreeColumn;
if (column.Index == treecolumn)
node.ClippedText = (sz.Width > cellRect.Width || sz.Height > cellRect.Height);
if (disposefont != null) disposefont.Dispose();
}
}
public virtual void PaintCellPlusMinus(Graphics dc, Rectangle glyphRect, Node node, TreeListColumn column, TreeList.TextFormatting format)
{
if (!Application.RenderWithVisualStyles)
{
// find square rect first
int diff = glyphRect.Height-glyphRect.Width;
glyphRect.Y += diff/2;
glyphRect.Height -= diff;
// draw 8x8 box centred
while (glyphRect.Height > 8)
{
glyphRect.Height -= 2;
glyphRect.Y += 1;
glyphRect.X += 1;
}
// make a box
glyphRect.Width = glyphRect.Height;
// clear first
SolidBrush brush = new SolidBrush(format.BackColor);
if (format.BackColor == Color.Transparent)
brush = new SolidBrush(m_owner.BackColor);
dc.FillRectangle(brush, glyphRect);
brush.Dispose();
// draw outline
Pen p = new Pen(SystemColors.ControlDark);
dc.DrawRectangle(p, glyphRect);
p.Dispose();
p = new Pen(SystemColors.ControlText);
// reduce box for internal lines
glyphRect.X += 2; glyphRect.Y += 2;
glyphRect.Width -= 4; glyphRect.Height -= 4;
// draw horizontal line always
dc.DrawLine(p, glyphRect.X, glyphRect.Y + glyphRect.Height / 2, glyphRect.X + glyphRect.Width, glyphRect.Y + glyphRect.Height / 2);
// draw vertical line if this should be a +
if(!node.Expanded)
dc.DrawLine(p, glyphRect.X + glyphRect.Width / 2, glyphRect.Y, glyphRect.X + glyphRect.Width / 2, glyphRect.Y + glyphRect.Height);
p.Dispose();
return;
}
VisualStyleElement element = VisualStyleElement.TreeView.Glyph.Closed;
if (node.Expanded)
element = VisualStyleElement.TreeView.Glyph.Opened;
if (VisualStyleRenderer.IsElementDefined(element))
{
VisualStyleRenderer renderer = new VisualStyleRenderer(element);
renderer.DrawBackground(dc, glyphRect);
}
}
}
public class ColumnHeaderPainter
{
TreeListView m_owner;
public ColumnHeaderPainter(TreeListView owner)
{
m_owner = owner;
}
public static Rectangle AdjustRectangle(Rectangle r, Padding padding)
{
r.X += padding.Left;
r.Width -= padding.Left + padding.Right;
r.Y += padding.Top;
r.Height -= padding.Top + padding.Bottom;
return r;
}
public virtual void DrawHeaderFiller(Graphics dc, Rectangle r)
{
if (!Application.RenderWithVisualStyles)
{
ControlPaint.DrawButton(dc, r, ButtonState.Flat);
return;
}
VisualStyleElement element = VisualStyleElement.Header.Item.Normal;
if (VisualStyleRenderer.IsElementDefined(element))
{
VisualStyleRenderer renderer = new VisualStyleRenderer(element);
renderer.DrawBackground(dc, r);
}
}
public void DrawHeaderText(Graphics dc, Rectangle cellRect, TreeListColumn column, TreeList.TextFormatting format)
{
Color color = format.ForeColor;
TextFormatFlags flags = TextFormatFlags.EndEllipsis | format.GetFormattingFlags();
TextRenderer.DrawText(dc, column.Caption, column.Font, cellRect, color, flags);
}
public virtual void DrawHeader(Graphics dc, Rectangle cellRect, TreeListColumn column, TreeList.TextFormatting format, bool isHot, bool highlight)
{
Rectangle textRect = AdjustRectangle(cellRect, format.Padding);
if (!Application.RenderWithVisualStyles)
{
ControlPaint.DrawButton(dc, cellRect,
m_owner.ViewOptions.UserRearrangeableColumns && highlight ? ButtonState.Pushed : ButtonState.Flat);
DrawHeaderText(dc, textRect, column, format);
return;
}
VisualStyleElement element = VisualStyleElement.Header.Item.Normal;
if (isHot || highlight)
element = VisualStyleElement.Header.Item.Hot;
if (VisualStyleRenderer.IsElementDefined(element))
{
VisualStyleRenderer renderer = new VisualStyleRenderer(element);
renderer.DrawBackground(dc, cellRect);
if (format.BackColor != Color.Transparent)
{
SolidBrush brush = new SolidBrush(format.BackColor);
dc.FillRectangle(brush, cellRect);
brush.Dispose();
}
//dc.DrawRectangle(Pens.Black, cellRect);
DrawHeaderText(dc, textRect, column, format);
}
}
public virtual void DrawVerticalGridLines(TreeListColumnCollection columns, Graphics dc, Rectangle r, int hScrollOffset)
{
foreach (TreeListColumn col in columns.VisibleColumns)
{
int rightPos = col.CalculatedRect.Right - hScrollOffset;
if (rightPos < 0)
continue;
Pen p = new Pen(columns.Owner.GridLineColour);
dc.DrawLine(p, rightPos, r.Top, rightPos, r.Bottom);
p.Dispose();
}
}
}
public class RowPainter
{
public void DrawHeader(Graphics dc, Rectangle r, bool isHot)
{
if (!Application.RenderWithVisualStyles)
{
if (r.Width > 0 && r.Height > 0)
{
ControlPaint.DrawButton(dc, r, ButtonState.Flat);
}
return;
}
VisualStyleElement element = VisualStyleElement.Header.Item.Normal;
if (isHot)
element = VisualStyleElement.Header.Item.Hot;
if (VisualStyleRenderer.IsElementDefined(element))
{
VisualStyleRenderer renderer = new VisualStyleRenderer(element);
renderer.DrawBackground(dc, r);
}
}
public void DrawHorizontalGridLine(Graphics dc, Rectangle r, Color col)
{
Pen p = new Pen(col);
dc.DrawLine(p, r.Left, r.Bottom, r.Right, r.Bottom);
p.Dispose();
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
namespace DotSpatial.Data
{
/// <summary>
/// Hfa
/// </summary>
public static class Hfa
{
#region Methods
/// <summary>
/// Gets the bitcount of a single member of the specified data type.
/// </summary>
/// <param name="dataType">The data type to get the byte count of</param>
/// <returns>An integer that represents the bit count of the specified type</returns>
public static int GetBitCount(this HfaEpt dataType)
{
switch (dataType)
{
case HfaEpt.U1: return 1;
case HfaEpt.U2: return 2;
case HfaEpt.U4: return 4;
case HfaEpt.U8:
case HfaEpt.S8: return 8;
case HfaEpt.U16:
case HfaEpt.S16: return 16;
case HfaEpt.U32:
case HfaEpt.S32:
case HfaEpt.Single: return 32;
case HfaEpt.Double:
case HfaEpt.Char64: return 64;
case HfaEpt.Char128: return 128;
}
return 0;
}
/// <summary>
/// Reverses the byte order on Big-Endian systems like Unix to conform with the
/// HFA standard of little endian.
/// </summary>
/// <param name="value">The value that gets reversed.</param>
/// <returns>The reversed value.</returns>
public static byte[] LittleEndian(byte[] value)
{
if (!BitConverter.IsLittleEndian) Array.Reverse(value);
return value;
}
/// <summary>
/// Obtains the 4 byte equivalent for 32 bit Integer values
/// </summary>
/// <param name="value">The unsigned integer value to convert into bytes</param>
/// <returns>The bytes in LittleEndian standard, regardless of the system architecture</returns>
public static byte[] LittleEndian(int value)
{
byte[] bValue = BitConverter.GetBytes(value);
return LittleEndian(bValue);
}
/// <summary>
/// Obtains the 4 byte equivalent for 32bit floating point values
/// </summary>
/// <param name="value">The unsigned integer value to convert into bytes</param>
/// <returns>The bytes in LittleEndian standard, regardless of the system architecture</returns>
public static byte[] LittleEndian(float value)
{
byte[] bValue = BitConverter.GetBytes(value);
return LittleEndian(bValue);
}
/// <summary>
/// Obtains the 8 byte equivalent for 64 bit floating point values
/// </summary>
/// <param name="value">The unsigned integer value to convert into bytes</param>
/// <returns>The bytes in LittleEndian standard, regardless of the system architecture</returns>
public static byte[] LittleEndian(double value)
{
byte[] bValue = BitConverter.GetBytes(value);
return LittleEndian(bValue);
}
/// <summary>
/// Gets the 2 byte equivalent of a short in little endian format.
/// </summary>
/// <param name="value">The value to get the equivalent for.</param>
/// <returns>The 2 byte equivalent for the value.</returns>
public static byte[] LittleEndian(short value)
{
byte[] bValue = BitConverter.GetBytes(value);
return LittleEndian(bValue);
}
/// <summary>
/// Obtains the 4 byte equivalent for 32 bit Unsigned Integer values
/// </summary>
/// <param name="value">The unsigned integer value to convert into bytes</param>
/// <returns>The bytes in LittleEndian standard, regardless of the system architecture</returns>
public static byte[] LittleEndianAsUint32(long value)
{
byte[] bValue = BitConverter.GetBytes(Convert.ToUInt32(value));
return LittleEndian(bValue);
}
/// <summary>
/// Gets the 2 byte equivalent of an unsigned short in little endian format.
/// </summary>
/// <param name="value">The value to get the equivalent for.</param>
/// <returns>The 2 byte equivalent for the value.</returns>
public static byte[] LittleEndianAsUShort(int value)
{
byte[] bValue = BitConverter.GetBytes(Convert.ToUInt16(value));
return LittleEndian(bValue);
}
/// <summary>
/// Given the byte array, this reads four bytes and converts this to a 64 bit floating point value
/// This always uses little endian byte order.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The offset to start reading.</param>
/// <returns>The value</returns>
public static double ReadDouble(byte[] data, long offset)
{
byte[] vals = new byte[8];
Array.Copy(data, offset, vals, 0, 8);
return BitConverter.ToSingle(LittleEndian(vals), 0);
}
/// <summary>
/// Given the byte array, this reads four bytes and converts this to a 32 bit integer.
/// This always uses little endian byte order.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The offset to start reading.</param>
/// <returns>The read value.</returns>
public static short ReadInt16(byte[] data, long offset)
{
byte[] vals = new byte[4];
Array.Copy(data, offset, vals, 0, 4);
return BitConverter.ToInt16(LittleEndian(vals), 0);
}
/// <summary>
/// Given the byte array, this reads four bytes and converts this to a 32 bit integer.
/// This always uses little endian byte order.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The offset to start reading.</param>
/// <returns>The read value.</returns>
public static int ReadInt32(byte[] data, long offset)
{
byte[] vals = new byte[4];
Array.Copy(data, offset, vals, 0, 4);
return BitConverter.ToInt32(LittleEndian(vals), 0);
}
/// <summary>
/// Given the byte array, this reads four bytes and converts this to a 32 bit floating point value
/// This always uses little endian byte order.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The offset to start reading.</param>
/// <returns>The read value.</returns>
public static float ReadSingle(byte[] data, long offset)
{
byte[] vals = new byte[4];
Array.Copy(data, offset, vals, 0, 4);
return BitConverter.ToSingle(LittleEndian(vals), 0);
}
/// <summary>
/// Returns the type that was read.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The offset to start reading.</param>
/// <returns>The type.</returns>
public static HfaEpt ReadType(byte[] data, long offset)
{
byte[] vals = new byte[2];
Array.Copy(data, offset, vals, 0, 2);
return (HfaEpt)BitConverter.ToInt16(LittleEndian(vals), 0);
}
/// <summary>
/// Given the byte array, this reads four bytes and converts this to a 16 bit unsigned short integer.
/// This always uses little endian byte order.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The offset to start reading.</param>
/// <returns>A UInt16 value stored in an int because UInt16 is not CLS Compliant</returns>
public static int ReadUInt16(byte[] data, long offset)
{
byte[] vals = new byte[2];
Array.Copy(data, offset, vals, 0, 2);
return BitConverter.ToUInt16(LittleEndian(vals), 0);
}
/// <summary>
/// Given the byte array, this reads four bytes and converts this to a 32 bit unsigned integer.
/// This always uses little endian byte order.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The offset to start reading.</param>
/// <returns>A UInt32 value stored in a long because UInt32 is not CLS Compliant</returns>
public static long ReadUInt32(byte[] data, long offset)
{
byte[] vals = new byte[4];
Array.Copy(data, offset, vals, 0, 4);
return BitConverter.ToUInt32(LittleEndian(vals), 0);
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Linq;
using FluentAssertions;
using Microsoft.DotNet.ProjectModel.Resolution;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
using NuGet.Configuration;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.ProjectModel;
using NuGet.Versioning;
using Xunit;
namespace Microsoft.DotNet.ProjectModel.Tests
{
public class PackageDependencyProviderTests : TestBase
{
[Fact]
public void GetDescriptionShouldLeavePackageLibraryPathAlone()
{
// Arrange
var provider = new PackageDependencyProvider(
NuGetPathContext.Create("/foo/packages"),
new FrameworkReferenceResolver("/foo/references"));
var package = new LockFileLibrary();
package.Name = "Something";
package.Version = NuGetVersion.Parse("1.0.0");
package.Files.Add("lib/dotnet/_._");
package.Files.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");
package.Path = "SomePath";
var target = new LockFileTargetLibrary();
target.Name = "Something";
target.Version = package.Version;
target.RuntimeAssemblies.Add("lib/dotnet/_._");
target.CompileTimeAssemblies.Add("lib/dotnet/_._");
target.NativeLibraries.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");
// Act
var p = provider.GetDescription(NuGetFramework.Parse("netcoreapp1.0"), package, target);
// Assert
p.PackageLibrary.Path.Should().Be("SomePath");
}
[Fact]
public void GetDescriptionShouldGenerateHashFileName()
{
// Arrange
var provider = new PackageDependencyProvider(
NuGetPathContext.Create("/foo/packages"),
new FrameworkReferenceResolver("/foo/references"));
var package = new LockFileLibrary();
package.Name = "Something";
package.Version = NuGetVersion.Parse("1.0.0-Beta");
package.Files.Add("lib/dotnet/_._");
package.Files.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");
package.Path = "SomePath";
var target = new LockFileTargetLibrary();
target.Name = "Something";
target.Version = package.Version;
target.RuntimeAssemblies.Add("lib/dotnet/_._");
target.CompileTimeAssemblies.Add("lib/dotnet/_._");
target.NativeLibraries.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");
// Act
var p = provider.GetDescription(NuGetFramework.Parse("netcoreapp1.0"), package, target);
// Assert
p.PackageLibrary.Path.Should().Be("SomePath");
p.HashPath.Should().Be("something.1.0.0-beta.nupkg.sha512");
}
[Fact]
public void GetDescriptionShouldNotModifyTarget()
{
var provider = new PackageDependencyProvider(
NuGetPathContext.Create("/foo/packages"),
new FrameworkReferenceResolver("/foo/references"));
var package = new LockFileLibrary();
package.Name = "Something";
package.Version = NuGetVersion.Parse("1.0.0");
package.Files.Add("lib/dotnet/_._");
package.Files.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");
var target = new LockFileTargetLibrary();
target.Name = "Something";
target.Version = package.Version;
target.RuntimeAssemblies.Add("lib/dotnet/_._");
target.CompileTimeAssemblies.Add("lib/dotnet/_._");
target.NativeLibraries.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");
var p1 = provider.GetDescription(NuGetFramework.Parse("netcoreapp1.0"), package, target);
var p2 = provider.GetDescription(NuGetFramework.Parse("netcoreapp1.0"), package, target);
Assert.True(p1.Compatible);
Assert.True(p2.Compatible);
Assert.Empty(p1.CompileTimeAssemblies);
Assert.Empty(p1.RuntimeAssemblies);
Assert.Empty(p2.CompileTimeAssemblies);
Assert.Empty(p2.RuntimeAssemblies);
}
[Fact]
public void HasCompileTimePlaceholderChecksAllCompileTimeAssets()
{
var provider = new PackageDependencyProvider(
NuGetPathContext.Create("/foo/packages"),
new FrameworkReferenceResolver("/foo/references"));
var package = new LockFileLibrary();
package.Name = "Something";
package.Version = NuGetVersion.Parse("1.0.0");
package.Files.Add("lib/net46/_._");
package.Files.Add("lib/net46/Something.dll");
var target = new LockFileTargetLibrary();
target.Name = "Something";
target.Version = package.Version;
target.RuntimeAssemblies.Add("lib/net46/_._");
target.RuntimeAssemblies.Add("lib/net46/Something.dll");
target.CompileTimeAssemblies.Add("lib/net46/_._");
target.CompileTimeAssemblies.Add("lib/net46/Something.dll");
var p1 = provider.GetDescription(NuGetFramework.Parse("net46"), package, target);
Assert.False(p1.HasCompileTimePlaceholder);
Assert.Equal(1, p1.CompileTimeAssemblies.Count());
Assert.Equal(1, p1.RuntimeAssemblies.Count());
Assert.Equal("lib/net46/Something.dll", p1.CompileTimeAssemblies.First().Path);
Assert.Equal("lib/net46/Something.dll", p1.RuntimeAssemblies.First().Path);
}
[Fact]
public void HasCompileTimePlaceholderReturnsFalseIfEmpty()
{
var provider = new PackageDependencyProvider(
NuGetPathContext.Create("/foo/packages"),
new FrameworkReferenceResolver("/foo/references"));
var package = new LockFileLibrary();
package.Name = "Something";
package.Version = NuGetVersion.Parse("1.0.0");
var target = new LockFileTargetLibrary();
target.Name = "Something";
target.Version = package.Version;
var p1 = provider.GetDescription(NuGetFramework.Parse("net46"), package, target);
Assert.False(p1.HasCompileTimePlaceholder);
Assert.Equal(0, p1.CompileTimeAssemblies.Count());
Assert.Equal(0, p1.RuntimeAssemblies.Count());
}
[Theory]
[InlineData("TestMscorlibReference", true)]
[InlineData("TestMscorlibReference", false)]
[InlineData("TestMicrosoftCSharpReference", true)]
[InlineData("TestMicrosoftCSharpReference", false)]
[InlineData("TestSystemReference", true)]
[InlineData("TestSystemReference", false)]
[InlineData("TestSystemCoreReference", true)]
[InlineData("TestSystemCoreReference", false)]
public void TestDuplicateDefaultDesktopReferences(string sampleName, bool withLockFile)
{
var instance = TestAssetsManager.CreateTestInstance(sampleName);
if (withLockFile)
{
instance = instance.WithLockFiles();
}
var context = new ProjectContextBuilder().WithProjectDirectory(instance.TestRoot)
.WithTargetFramework("net451")
.Build();
Assert.Equal(4, context.RootProject.Dependencies.Count());
}
[Fact]
public void NoDuplicateReferencesWhenFrameworkMissing()
{
var instance = TestAssetsManager.CreateTestInstance("TestMicrosoftCSharpReferenceMissingFramework")
.WithLockFiles();
var context = new ProjectContextBuilder().WithProjectDirectory(instance.TestRoot)
.WithTargetFramework("net99")
.Build();
// Will fail with dupes if any
context.LibraryManager.GetLibraries().ToDictionary(l => l.Identity.Name, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void NetCore50ShouldNotResolveFrameworkAssemblies()
{
var instance = TestAssetsManager.CreateTestInstance("TestMicrosoftCSharpReferenceMissingFramework")
.WithLockFiles();
var context = new ProjectContextBuilder().WithProjectDirectory(instance.TestRoot)
.WithTargetFramework("netcore50")
.Build();
var diagnostics = context.LibraryManager.GetAllDiagnostics();
Assert.False(diagnostics.Any(d => d.ErrorCode == ErrorCodes.DOTNET1011));
}
[Fact]
public void NoDuplicatesWithProjectAndReferenceAssemblyWithSameName()
{
var instance = TestAssetsManager.CreateTestInstance("DuplicatedReferenceAssembly")
.WithLockFiles();
var context = new ProjectContextBuilder().WithProjectDirectory(Path.Combine(instance.TestRoot, "TestApp"))
.WithTargetFramework("net461")
.Build();
// Will fail with dupes if any
context.LibraryManager.GetLibraries().ToDictionary(l => l.Identity.Name, StringComparer.OrdinalIgnoreCase);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
abstract class CodeFunctionNode : AbstractMaterialNode
, IGeneratesBodyCode
, IGeneratesFunction
, IMayRequireNormal
, IMayRequireTangent
, IMayRequireBitangent
, IMayRequireMeshUV
, IMayRequireScreenPosition
, IMayRequireViewDirection
, IMayRequirePosition
, IMayRequireVertexColor
{
[NonSerialized]
private List<SlotAttribute> m_Slots = new List<SlotAttribute>();
public override bool hasPreview
{
get { return true; }
}
protected CodeFunctionNode()
{
UpdateNodeAfterDeserialization();
}
protected struct Boolean
{}
protected struct Vector1
{}
protected struct Texture2D
{}
protected struct Texture2DArray
{}
protected struct Texture3D
{}
protected struct SamplerState
{}
protected struct Gradient
{}
protected struct DynamicDimensionVector
{}
protected struct ColorRGBA
{}
protected struct ColorRGB
{}
protected struct Matrix3x3
{}
protected struct Matrix2x2
{}
protected struct DynamicDimensionMatrix
{}
protected enum Binding
{
None,
ObjectSpaceNormal,
ObjectSpaceTangent,
ObjectSpaceBitangent,
ObjectSpacePosition,
ViewSpaceNormal,
ViewSpaceTangent,
ViewSpaceBitangent,
ViewSpacePosition,
WorldSpaceNormal,
WorldSpaceTangent,
WorldSpaceBitangent,
WorldSpacePosition,
TangentSpaceNormal,
TangentSpaceTangent,
TangentSpaceBitangent,
TangentSpacePosition,
MeshUV0,
MeshUV1,
MeshUV2,
MeshUV3,
ScreenPosition,
ObjectSpaceViewDirection,
ViewSpaceViewDirection,
WorldSpaceViewDirection,
TangentSpaceViewDirection,
VertexColor,
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
protected class SlotAttribute : Attribute
{
public int slotId { get; private set; }
public Binding binding { get; private set; }
public bool hidden { get; private set; }
public Vector4? defaultValue { get; private set; }
public ShaderStageCapability stageCapability { get; private set; }
public SlotAttribute(int mSlotId, Binding mImplicitBinding, ShaderStageCapability mStageCapability = ShaderStageCapability.All)
{
slotId = mSlotId;
binding = mImplicitBinding;
defaultValue = null;
stageCapability = mStageCapability;
}
public SlotAttribute(int mSlotId, Binding mImplicitBinding, bool mHidden, ShaderStageCapability mStageCapability = ShaderStageCapability.All)
{
slotId = mSlotId;
binding = mImplicitBinding;
hidden = mHidden;
defaultValue = null;
stageCapability = mStageCapability;
}
public SlotAttribute(int mSlotId, Binding mImplicitBinding, float defaultX, float defaultY, float defaultZ, float defaultW, ShaderStageCapability mStageCapability = ShaderStageCapability.All)
{
slotId = mSlotId;
binding = mImplicitBinding;
defaultValue = new Vector4(defaultX, defaultY, defaultZ, defaultW);
stageCapability = mStageCapability;
}
}
protected abstract MethodInfo GetFunctionToConvert();
private static SlotValueType ConvertTypeToSlotValueType(ParameterInfo p)
{
Type t = p.ParameterType;
if (p.ParameterType.IsByRef)
t = p.ParameterType.GetElementType();
if (t == typeof(Boolean))
{
return SlotValueType.Boolean;
}
if (t == typeof(Vector1))
{
return SlotValueType.Vector1;
}
if (t == typeof(Vector2))
{
return SlotValueType.Vector2;
}
if (t == typeof(Vector3))
{
return SlotValueType.Vector3;
}
if (t == typeof(Vector4))
{
return SlotValueType.Vector4;
}
if (t == typeof(Color))
{
return SlotValueType.Vector4;
}
if (t == typeof(ColorRGBA))
{
return SlotValueType.Vector4;
}
if (t == typeof(ColorRGB))
{
return SlotValueType.Vector3;
}
if (t == typeof(Texture2D))
{
return SlotValueType.Texture2D;
}
if (t == typeof(Texture2DArray))
{
return SlotValueType.Texture2DArray;
}
if (t == typeof(Texture3D))
{
return SlotValueType.Texture3D;
}
if (t == typeof(Cubemap))
{
return SlotValueType.Cubemap;
}
if (t == typeof(Gradient))
{
return SlotValueType.Gradient;
}
if (t == typeof(SamplerState))
{
return SlotValueType.SamplerState;
}
if (t == typeof(DynamicDimensionVector))
{
return SlotValueType.DynamicVector;
}
if (t == typeof(Matrix4x4))
{
return SlotValueType.Matrix4;
}
if (t == typeof(Matrix3x3))
{
return SlotValueType.Matrix3;
}
if (t == typeof(Matrix2x2))
{
return SlotValueType.Matrix2;
}
if (t == typeof(DynamicDimensionMatrix))
{
return SlotValueType.DynamicMatrix;
}
throw new ArgumentException("Unsupported type " + t);
}
public sealed override void UpdateNodeAfterDeserialization()
{
var method = GetFunctionToConvert();
if (method == null)
throw new ArgumentException("Mapped method is null on node" + this);
if (method.ReturnType != typeof(string))
throw new ArgumentException("Mapped function should return string");
// validate no duplicates
var slotAtributes = method.GetParameters().Select(GetSlotAttribute).ToList();
if (slotAtributes.Any(x => x == null))
throw new ArgumentException("Missing SlotAttribute on " + method.Name);
if (slotAtributes.GroupBy(x => x.slotId).Any(x => x.Count() > 1))
throw new ArgumentException("Duplicate SlotAttribute on " + method.Name);
List<MaterialSlot> slots = new List<MaterialSlot>();
foreach (var par in method.GetParameters())
{
var attribute = GetSlotAttribute(par);
var name = GraphUtil.ConvertCamelCase(par.Name, true);
MaterialSlot s;
if (attribute.binding == Binding.None && !par.IsOut && par.ParameterType == typeof(Color))
s = new ColorRGBAMaterialSlot(attribute.slotId, name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, stageCapability: attribute.stageCapability, hidden: attribute.hidden);
else if (attribute.binding == Binding.None && !par.IsOut && par.ParameterType == typeof(ColorRGBA))
s = new ColorRGBAMaterialSlot(attribute.slotId, name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, stageCapability: attribute.stageCapability, hidden: attribute.hidden);
else if (attribute.binding == Binding.None && !par.IsOut && par.ParameterType == typeof(ColorRGB))
s = new ColorRGBMaterialSlot(attribute.slotId, name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, ColorMode.Default, stageCapability: attribute.stageCapability, hidden: attribute.hidden);
else if (attribute.binding == Binding.None || par.IsOut)
s = MaterialSlot.CreateMaterialSlot(
ConvertTypeToSlotValueType(par),
attribute.slotId,
name,
par.Name,
par.IsOut ? SlotType.Output : SlotType.Input,
attribute.defaultValue ?? Vector4.zero,
shaderStageCapability: attribute.stageCapability,
hidden: attribute.hidden);
else
s = CreateBoundSlot(attribute.binding, attribute.slotId, name, par.Name, attribute.stageCapability, attribute.hidden);
slots.Add(s);
m_Slots.Add(attribute);
}
foreach (var slot in slots)
{
AddSlot(slot);
}
RemoveSlotsNameNotMatching(slots.Select(x => x.id));
}
private static MaterialSlot CreateBoundSlot(Binding attributeBinding, int slotId, string displayName, string shaderOutputName, ShaderStageCapability shaderStageCapability, bool hidden)
{
switch (attributeBinding)
{
case Binding.ObjectSpaceNormal:
return new NormalMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Object, shaderStageCapability);
case Binding.ObjectSpaceTangent:
return new TangentMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Object, shaderStageCapability);
case Binding.ObjectSpaceBitangent:
return new BitangentMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Object, shaderStageCapability);
case Binding.ObjectSpacePosition:
return new PositionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Object, shaderStageCapability);
case Binding.ViewSpaceNormal:
return new NormalMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.View, shaderStageCapability);
case Binding.ViewSpaceTangent:
return new TangentMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.View, shaderStageCapability);
case Binding.ViewSpaceBitangent:
return new BitangentMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.View, shaderStageCapability);
case Binding.ViewSpacePosition:
return new PositionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.View, shaderStageCapability);
case Binding.WorldSpaceNormal:
return new NormalMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.World, shaderStageCapability);
case Binding.WorldSpaceTangent:
return new TangentMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.World, shaderStageCapability);
case Binding.WorldSpaceBitangent:
return new BitangentMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.World, shaderStageCapability);
case Binding.WorldSpacePosition:
return new PositionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.World, shaderStageCapability);
case Binding.TangentSpaceNormal:
return new NormalMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Tangent, shaderStageCapability);
case Binding.TangentSpaceTangent:
return new TangentMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Tangent, shaderStageCapability);
case Binding.TangentSpaceBitangent:
return new BitangentMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Tangent, shaderStageCapability);
case Binding.TangentSpacePosition:
return new PositionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Tangent, shaderStageCapability);
case Binding.MeshUV0:
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV0, shaderStageCapability);
case Binding.MeshUV1:
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV1, shaderStageCapability);
case Binding.MeshUV2:
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV2, shaderStageCapability);
case Binding.MeshUV3:
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV3, shaderStageCapability);
case Binding.ScreenPosition:
return new ScreenPositionMaterialSlot(slotId, displayName, shaderOutputName, ScreenSpaceType.Default, shaderStageCapability);
case Binding.ObjectSpaceViewDirection:
return new ViewDirectionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Object, shaderStageCapability);
case Binding.ViewSpaceViewDirection:
return new ViewDirectionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.View, shaderStageCapability);
case Binding.WorldSpaceViewDirection:
return new ViewDirectionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.World, shaderStageCapability);
case Binding.TangentSpaceViewDirection:
return new ViewDirectionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Tangent, shaderStageCapability);
case Binding.VertexColor:
return new VertexColorMaterialSlot(slotId, displayName, shaderOutputName, shaderStageCapability);
default:
throw new ArgumentOutOfRangeException("attributeBinding", attributeBinding, null);
}
}
public void GenerateNodeCode(ShaderGenerator visitor, GraphContext graphContext, GenerationMode generationMode)
{
s_TempSlots.Clear();
GetOutputSlots(s_TempSlots);
foreach (var outSlot in s_TempSlots)
{
visitor.AddShaderChunk(GetParamTypeName(outSlot) + " " + GetVariableNameForSlot(outSlot.id) + ";", true);
}
string call = GetFunctionName() + "(";
bool first = true;
s_TempSlots.Clear();
GetSlots(s_TempSlots);
s_TempSlots.Sort((slot1, slot2) => slot1.id.CompareTo(slot2.id));
foreach (var slot in s_TempSlots)
{
if (!first)
{
call += ", ";
}
first = false;
if (slot.isInputSlot)
call += GetSlotValue(slot.id, generationMode);
else
call += GetVariableNameForSlot(slot.id);
}
call += ");";
visitor.AddShaderChunk(call, true);
}
private string GetParamTypeName(MaterialSlot slot)
{
return NodeUtils.ConvertConcreteSlotValueTypeToString(precision, slot.concreteValueType);
}
private string GetFunctionName()
{
var function = GetFunctionToConvert();
return function.Name + "_" + (function.IsStatic ? string.Empty : GuidEncoder.Encode(guid) + "_") + precision
+ (this.GetSlots<DynamicVectorMaterialSlot>().Select(s => NodeUtils.GetSlotDimension(s.concreteValueType)).FirstOrDefault() ?? "")
+ (this.GetSlots<DynamicMatrixMaterialSlot>().Select(s => NodeUtils.GetSlotDimension(s.concreteValueType)).FirstOrDefault() ?? "");
}
private string GetFunctionHeader()
{
string header = "void " + GetFunctionName() + "(";
s_TempSlots.Clear();
GetSlots(s_TempSlots);
s_TempSlots.Sort((slot1, slot2) => slot1.id.CompareTo(slot2.id));
var first = true;
foreach (var slot in s_TempSlots)
{
if (!first)
header += ", ";
first = false;
if (slot.isOutputSlot)
header += "out ";
header += GetParamTypeName(slot) + " " + slot.shaderOutputName;
}
header += ")";
return header;
}
private static object GetDefault(Type type)
{
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
private string GetFunctionBody(MethodInfo info)
{
var args = new List<object>();
foreach (var param in info.GetParameters())
args.Add(GetDefault(param.ParameterType));
var result = info.Invoke(this, args.ToArray()) as string;
if (string.IsNullOrEmpty(result))
return string.Empty;
result = result.Replace("{precision}", precision.ToString());
s_TempSlots.Clear();
GetSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
{
var toReplace = string.Format("{{slot{0}dimension}}", slot.id);
var replacement = NodeUtils.GetSlotDimension(slot.concreteValueType);
result = result.Replace(toReplace, replacement);
}
return result;
}
public virtual void GenerateNodeFunction(FunctionRegistry registry, GraphContext graphContext, GenerationMode generationMode)
{
registry.ProvideFunction(GetFunctionName(), s =>
{
s.AppendLine(GetFunctionHeader());
var functionBody = GetFunctionBody(GetFunctionToConvert());
var lines = functionBody.Trim('\r', '\n', '\t', ' ');
s.AppendLines(lines);
});
}
private static SlotAttribute GetSlotAttribute([NotNull] ParameterInfo info)
{
var attrs = info.GetCustomAttributes(typeof(SlotAttribute), false).OfType<SlotAttribute>().ToList();
return attrs.FirstOrDefault();
}
public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability)
{
var binding = NeededCoordinateSpace.None;
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
binding |= slot.RequiresNormal();
return binding;
}
public NeededCoordinateSpace RequiresViewDirection(ShaderStageCapability stageCapability)
{
var binding = NeededCoordinateSpace.None;
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
binding |= slot.RequiresViewDirection();
return binding;
}
public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability)
{
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
var binding = NeededCoordinateSpace.None;
foreach (var slot in s_TempSlots)
binding |= slot.RequiresPosition();
return binding;
}
public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability)
{
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
var binding = NeededCoordinateSpace.None;
foreach (var slot in s_TempSlots)
binding |= slot.RequiresTangent();
return binding;
}
public NeededCoordinateSpace RequiresBitangent(ShaderStageCapability stageCapability)
{
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
var binding = NeededCoordinateSpace.None;
foreach (var slot in s_TempSlots)
binding |= slot.RequiresBitangent();
return binding;
}
public bool RequiresMeshUV(UVChannel channel, ShaderStageCapability stageCapability)
{
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
{
if (slot.RequiresMeshUV(channel))
return true;
}
return false;
}
public bool RequiresScreenPosition(ShaderStageCapability stageCapability)
{
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
{
if (slot.RequiresScreenPosition())
return true;
}
return false;
}
public bool RequiresVertexColor(ShaderStageCapability stageCapability)
{
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
{
if (slot.RequiresVertexColor())
return true;
}
return 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.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml.Xsl.XsltOld.Debugger;
internal class DbgData
{
private VariableAction[] _variables;
public XPathNavigator StyleSheet { get; }
public DbgData(Compiler compiler)
{
DbgCompiler dbgCompiler = (DbgCompiler)compiler;
StyleSheet = dbgCompiler.Input.Navigator.Clone();
_variables = dbgCompiler.LocalVariables;
dbgCompiler.Debugger.OnInstructionCompile(this.StyleSheet);
}
internal void ReplaceVariables(VariableAction[] vars) { _variables = vars; }
// static Empty:
private static readonly DbgData s_nullDbgData = new DbgData();
private DbgData()
{
StyleSheet = null;
_variables = Array.Empty<VariableAction>();
}
public static DbgData Empty { get { return s_nullDbgData; } }
}
internal class DbgCompiler : Compiler
{
private readonly IXsltDebugger _debugger;
public DbgCompiler(IXsltDebugger debugger)
{
_debugger = debugger;
}
public override IXsltDebugger Debugger { get { return _debugger; } }
// Variables
//
// In XsltDebugger we have to know variables that are visible from each action.
// We keepping two different sets of wariables because global and local variables have different rules of visibility.
// Globals: All global variables are visible avryware (uncalucaled will have null value),
// Duplicated globals from different stilesheets are replaced (by import presidence)
// Locals: Visible only in scope and after it was defined.
// No duplicates posible.
private readonly ArrayList _globalVars = new ArrayList();
private readonly ArrayList _localVars = new ArrayList();
private VariableAction[] _globalVarsCache, _localVarsCache;
public virtual VariableAction[] GlobalVariables
{
get
{
Debug.Assert(this.Debugger != null);
if (_globalVarsCache == null)
{
_globalVarsCache = (VariableAction[])_globalVars.ToArray(typeof(VariableAction));
}
return _globalVarsCache;
}
}
public virtual VariableAction[] LocalVariables
{
get
{
Debug.Assert(this.Debugger != null);
if (_localVarsCache == null)
{
_localVarsCache = (VariableAction[])_localVars.ToArray(typeof(VariableAction));
}
return _localVarsCache;
}
}
private void DefineVariable(VariableAction variable)
{
Debug.Assert(this.Debugger != null);
if (variable.IsGlobal)
{
for (int i = 0; i < _globalVars.Count; i++)
{
VariableAction oldVar = (VariableAction)_globalVars[i];
if (oldVar.Name == variable.Name)
{ // Duplicate var definition
if (variable.Stylesheetid < oldVar.Stylesheetid)
{
Debug.Assert(variable.VarKey != -1, "Variable was already placed and it should replace prev var.");
_globalVars[i] = variable;
_globalVarsCache = null;
}
return;
}
}
_globalVars.Add(variable);
_globalVarsCache = null;
}
else
{
// local variables never conflict
_localVars.Add(variable);
_localVarsCache = null;
}
}
private void UnDefineVariables(int count)
{
Debug.Assert(0 <= count, "This scope can't have more variables than we have in total");
Debug.Assert(count <= _localVars.Count, "This scope can't have more variables than we have in total");
if (count != 0)
{
_localVars.RemoveRange(_localVars.Count - count, count);
_localVarsCache = null;
}
}
internal override void PopScope()
{
this.UnDefineVariables(this.ScopeManager.CurrentScope.GetVeriablesCount());
base.PopScope();
}
// ---------------- Actions: ---------------
public override ApplyImportsAction CreateApplyImportsAction()
{
ApplyImportsAction action = new ApplyImportsActionDbg();
action.Compile(this);
return action;
}
public override ApplyTemplatesAction CreateApplyTemplatesAction()
{
ApplyTemplatesAction action = new ApplyTemplatesActionDbg();
action.Compile(this);
return action;
}
public override AttributeAction CreateAttributeAction()
{
AttributeAction action = new AttributeActionDbg();
action.Compile(this);
return action;
}
public override AttributeSetAction CreateAttributeSetAction()
{
AttributeSetAction action = new AttributeSetActionDbg();
action.Compile(this);
return action;
}
public override CallTemplateAction CreateCallTemplateAction()
{
CallTemplateAction action = new CallTemplateActionDbg();
action.Compile(this);
return action;
}
public override ChooseAction CreateChooseAction()
{//!!! don't need to be here
ChooseAction action = new ChooseAction();
action.Compile(this);
return action;
}
public override CommentAction CreateCommentAction()
{
CommentAction action = new CommentActionDbg();
action.Compile(this);
return action;
}
public override CopyAction CreateCopyAction()
{
CopyAction action = new CopyActionDbg();
action.Compile(this);
return action;
}
public override CopyOfAction CreateCopyOfAction()
{
CopyOfAction action = new CopyOfActionDbg();
action.Compile(this);
return action;
}
public override ElementAction CreateElementAction()
{
ElementAction action = new ElementActionDbg();
action.Compile(this);
return action;
}
public override ForEachAction CreateForEachAction()
{
ForEachAction action = new ForEachActionDbg();
action.Compile(this);
return action;
}
public override IfAction CreateIfAction(IfAction.ConditionType type)
{
IfAction action = new IfActionDbg(type);
action.Compile(this);
return action;
}
public override MessageAction CreateMessageAction()
{
MessageAction action = new MessageActionDbg();
action.Compile(this);
return action;
}
public override NewInstructionAction CreateNewInstructionAction()
{
NewInstructionAction action = new NewInstructionActionDbg();
action.Compile(this);
return action;
}
public override NumberAction CreateNumberAction()
{
NumberAction action = new NumberActionDbg();
action.Compile(this);
return action;
}
public override ProcessingInstructionAction CreateProcessingInstructionAction()
{
ProcessingInstructionAction action = new ProcessingInstructionActionDbg();
action.Compile(this);
return action;
}
public override void CreateRootAction()
{
this.RootAction = new RootActionDbg();
this.RootAction.Compile(this);
}
public override SortAction CreateSortAction()
{
SortAction action = new SortActionDbg();
action.Compile(this);
return action;
}
public override TemplateAction CreateTemplateAction()
{
TemplateAction action = new TemplateActionDbg();
action.Compile(this);
return action;
}
public override TemplateAction CreateSingleTemplateAction()
{
TemplateAction action = new TemplateActionDbg();
action.CompileSingle(this);
return action;
}
public override TextAction CreateTextAction()
{
TextAction action = new TextActionDbg();
action.Compile(this);
return action;
}
public override UseAttributeSetsAction CreateUseAttributeSetsAction()
{
UseAttributeSetsAction action = new UseAttributeSetsActionDbg();
action.Compile(this);
return action;
}
public override ValueOfAction CreateValueOfAction()
{
ValueOfAction action = new ValueOfActionDbg();
action.Compile(this);
return action;
}
public override VariableAction CreateVariableAction(VariableType type)
{
VariableAction action = new VariableActionDbg(type);
action.Compile(this);
return action;
}
public override WithParamAction CreateWithParamAction()
{
WithParamAction action = new WithParamActionDbg();
action.Compile(this);
return action;
}
// ---------------- Events: ---------------
public override BeginEvent CreateBeginEvent()
{
return new BeginEventDbg(this);
}
public override TextEvent CreateTextEvent()
{
return new TextEventDbg(this);
}
// Debugger enabled implemetation of most compiled actions
private class ApplyImportsActionDbg : ApplyImportsAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class ApplyTemplatesActionDbg : ApplyTemplatesAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class AttributeActionDbg : AttributeAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class AttributeSetActionDbg : AttributeSetAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class CallTemplateActionDbg : CallTemplateAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class CommentActionDbg : CommentAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class CopyActionDbg : CopyAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class CopyOfActionDbg : CopyOfAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class ElementActionDbg : ElementAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class ForEachActionDbg : ForEachAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.PushDebuggerStack();
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
if (frame.State == Finished)
{
processor.PopDebuggerStack();
}
}
}
private class IfActionDbg : IfAction
{
internal IfActionDbg(ConditionType type) : base(type) { }
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class MessageActionDbg : MessageAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class NewInstructionActionDbg : NewInstructionAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class NumberActionDbg : NumberAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class ProcessingInstructionActionDbg : ProcessingInstructionAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class RootActionDbg : RootAction
{
private DbgData _dbgData;
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
internal override void Compile(Compiler compiler)
{
_dbgData = new DbgData(compiler);
base.Compile(compiler);
Debug.Assert(compiler.Debugger != null);
string builtIn = compiler.Debugger.GetBuiltInTemplatesUri();
if (builtIn != null && builtIn.Length != 0)
{
compiler.AllowBuiltInMode = true;
builtInSheet = compiler.RootAction.CompileImport(compiler, compiler.ResolveUri(builtIn), int.MaxValue);
compiler.AllowBuiltInMode = false;
}
_dbgData.ReplaceVariables(((DbgCompiler)compiler).GlobalVariables);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.PushDebuggerStack();
processor.OnInstructionExecute();
processor.PushDebuggerStack();
}
base.Execute(processor, frame);
if (frame.State == Finished)
{
processor.PopDebuggerStack();
processor.PopDebuggerStack();
}
}
}
private class SortActionDbg : SortAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class TemplateActionDbg : TemplateAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.PushDebuggerStack();
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
if (frame.State == Finished)
{
processor.PopDebuggerStack();
}
}
}
private class TextActionDbg : TextAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class UseAttributeSetsActionDbg : UseAttributeSetsAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class ValueOfActionDbg : ValueOfAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class VariableActionDbg : VariableAction
{
internal VariableActionDbg(VariableType type) : base(type) { }
private DbgData _dbgData;
internal override void Compile(Compiler compiler)
{
_dbgData = new DbgData(compiler);
base.Compile(compiler);
((DbgCompiler)compiler).DefineVariable(this);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
private class WithParamActionDbg : WithParamAction
{
internal override void Compile(Compiler compiler)
{
base.Compile(compiler);
}
internal override void Execute(Processor processor, ActionFrame frame)
{
if (frame.State == Initialized)
{
processor.OnInstructionExecute();
}
base.Execute(processor, frame);
}
}
// ---------------- Events: ---------------
private class BeginEventDbg : BeginEvent
{
private readonly DbgData _dbgData;
internal override DbgData DbgData { get { return _dbgData; } }
public BeginEventDbg(Compiler compiler) : base(compiler)
{
_dbgData = new DbgData(compiler);
}
public override bool Output(Processor processor, ActionFrame frame)
{
this.OnInstructionExecute(processor);
return base.Output(processor, frame);
}
}
private class TextEventDbg : TextEvent
{
private readonly DbgData _dbgData;
internal override DbgData DbgData { get { return _dbgData; } }
public TextEventDbg(Compiler compiler) : base(compiler)
{
_dbgData = new DbgData(compiler);
}
public override bool Output(Processor processor, ActionFrame frame)
{
this.OnInstructionExecute(processor);
return base.Output(processor, frame);
}
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Lucene.Net.Index
{
using System;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Lucene.Net.Util.BytesRef;
using CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton;
/// <summary>
/// Exposes flex API, merged from flex API of
/// sub-segments.
///
/// @lucene.experimental
/// </summary>
public sealed class MultiTerms : Terms
{
private readonly Terms[] Subs;
private readonly ReaderSlice[] SubSlices;
private readonly IComparer<BytesRef> TermComp;
private readonly bool HasFreqs_Renamed;
private readonly bool HasOffsets_Renamed;
private readonly bool HasPositions_Renamed;
private readonly bool HasPayloads_Renamed;
/// <summary>
/// Sole constructor.
/// </summary>
/// <param name="subs"> The <seealso cref="Terms"/> instances of all sub-readers. </param>
/// <param name="subSlices"> A parallel array (matching {@code
/// subs}) describing the sub-reader slices. </param>
public MultiTerms(Terms[] subs, ReaderSlice[] subSlices)
{
this.Subs = subs;
this.SubSlices = subSlices;
IComparer<BytesRef> _termComp = null;
Debug.Assert(subs.Length > 0, "inefficient: don't use MultiTerms over one sub");
bool _hasFreqs = true;
bool _hasOffsets = true;
bool _hasPositions = true;
bool _hasPayloads = false;
for (int i = 0; i < subs.Length; i++)
{
if (_termComp == null)
{
_termComp = subs[i].Comparator;
}
else
{
// We cannot merge sub-readers that have
// different TermComps
IComparer<BytesRef> subTermComp = subs[i].Comparator;
if (subTermComp != null && !subTermComp.Equals(_termComp))
{
throw new InvalidOperationException("sub-readers have different BytesRef.Comparators; cannot merge");
}
}
_hasFreqs &= subs[i].HasFreqs();
_hasOffsets &= subs[i].HasOffsets();
_hasPositions &= subs[i].HasPositions();
_hasPayloads |= subs[i].HasPayloads();
}
TermComp = _termComp;
HasFreqs_Renamed = _hasFreqs;
HasOffsets_Renamed = _hasOffsets;
HasPositions_Renamed = _hasPositions;
HasPayloads_Renamed = HasPositions_Renamed && _hasPayloads; // if all subs have pos, and at least one has payloads.
}
public override TermsEnum Intersect(CompiledAutomaton compiled, BytesRef startTerm)
{
IList<MultiTermsEnum.TermsEnumIndex> termsEnums = new List<MultiTermsEnum.TermsEnumIndex>();
for (int i = 0; i < Subs.Length; i++)
{
TermsEnum termsEnum = Subs[i].Intersect(compiled, startTerm);
if (termsEnum != null)
{
termsEnums.Add(new MultiTermsEnum.TermsEnumIndex(termsEnum, i));
}
}
if (termsEnums.Count > 0)
{
return (new MultiTermsEnum(SubSlices)).Reset(termsEnums.ToArray(/*MultiTermsEnum.TermsEnumIndex.EMPTY_ARRAY*/));
}
else
{
return TermsEnum.EMPTY;
}
}
public override TermsEnum Iterator(TermsEnum reuse)
{
IList<MultiTermsEnum.TermsEnumIndex> termsEnums = new List<MultiTermsEnum.TermsEnumIndex>();
for (int i = 0; i < Subs.Length; i++)
{
TermsEnum termsEnum = Subs[i].Iterator(null);
if (termsEnum != null)
{
termsEnums.Add(new MultiTermsEnum.TermsEnumIndex(termsEnum, i));
}
}
if (termsEnums.Count > 0)
{
return (new MultiTermsEnum(SubSlices)).Reset(termsEnums.ToArray(/*MultiTermsEnum.TermsEnumIndex.EMPTY_ARRAY*/));
}
else
{
return TermsEnum.EMPTY;
}
}
public override long Size()
{
return -1;
}
public override long SumTotalTermFreq
{
get
{
long sum = 0;
foreach (Terms terms in Subs)
{
long v = terms.SumTotalTermFreq;
if (v == -1)
{
return -1;
}
sum += v;
}
return sum;
}
}
public override long SumDocFreq
{
get
{
long sum = 0;
foreach (Terms terms in Subs)
{
long v = terms.SumDocFreq;
if (v == -1)
{
return -1;
}
sum += v;
}
return sum;
}
}
public override int DocCount
{
get
{
int sum = 0;
foreach (Terms terms in Subs)
{
int v = terms.DocCount;
if (v == -1)
{
return -1;
}
sum += v;
}
return sum;
}
}
public override IComparer<BytesRef> Comparator
{
get
{
return TermComp;
}
}
public override bool HasFreqs()
{
return HasFreqs_Renamed;
}
public override bool HasOffsets()
{
return HasOffsets_Renamed;
}
public override bool HasPositions()
{
return HasPositions_Renamed;
}
public override bool HasPayloads()
{
return HasPayloads_Renamed;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression2;
using System.Text;
namespace ETLStackBrowse
{
[Serializable]
public class ByteWindow
{
public static Encoder en = System.Text.ASCIIEncoding.ASCII.GetEncoder();
public static Decoder de = System.Text.ASCIIEncoding.ASCII.GetDecoder();
public byte[] buffer; // buffer where the data actually lives.
public int[] fields; // start positions of all fields in the line
public int fieldsLen; // Number of valid entries in 'fields'
public int ib; // pointer into 'buffer' at start of string.
public int len; // length of string
public ByteWindow()
{
buffer = null;
fields = null;
ib = 0;
len = 0;
}
public ByteWindow(string s)
{
buffer = ByteWindow.MakeBytes(s);
fields = null;
ib = 0;
len = buffer.Length;
}
public ByteWindow(byte[] bytes)
{
buffer = bytes;
fields = null;
ib = 0;
len = buffer.Length;
}
public ByteWindow(ByteWindow b)
{
buffer = b.buffer;
fields = b.fields;
ib = b.ib;
len = b.len;
}
public ByteWindow(ByteWindow b, int fld)
{
buffer = b.buffer;
fields = b.fields;
ib = b.ib;
len = b.len;
Field(fld);
}
public ByteWindow Assign(ByteWindow b)
{
buffer = b.buffer;
fields = b.fields;
ib = b.ib;
len = b.len;
return this;
}
public ByteWindow Assign(ByteWindow b, int fld)
{
buffer = b.buffer;
fields = b.fields;
ib = fields[fld];
len = fields[fld + 1] - ib - 1;
return this;
}
public ByteWindow Assign(byte[] b)
{
buffer = b;
fields = null;
ib = 0;
len = b.Length;
return this;
}
public ByteWindow Assign(String s)
{
return Assign(MakeBytes(s));
}
public ByteWindow Field(int fld)
{
ib = fields[fld];
len = fields[fld + 1] - ib - 1;
return this;
}
public ByteWindow Truncate(byte b)
{
for (int i = 0; i < len; i++)
{
if (buffer[ib + i] == b)
{
len = i;
return this;
}
}
return this;
}
public long GetLong(int fld)
{
byte[] buffer = this.buffer;
int ib = fields[fld];
while (buffer[ib] == (byte)' ')
{
ib++;
}
long t = 0;
if (buffer[ib] == '0' && buffer[ib + 1] == 'x')
{
ib += 2;
for (; ; )
{
if (buffer[ib] >= '0' && buffer[ib] <= '9')
{
t *= 16;
t += (uint)(buffer[ib] - '0');
ib++;
continue;
}
if (buffer[ib] >= 'a' && buffer[ib] <= 'f')
{
t *= 16;
t += (uint)(buffer[ib] - 'a' + 10);
ib++;
continue;
}
return t;
}
}
while (buffer[ib] >= '0' && buffer[ib] <= '9')
{
t *= 10;
t += buffer[ib] - '0';
ib++;
}
return t;
}
public long GetLong()
{
byte[] buffer = this.buffer;
int ib = this.ib;
int i = 0;
while (buffer[ib + i] == (byte)' ')
{
i++;
}
long t = 0;
if (i + 2 < len && buffer[ib + i] == '0' && buffer[ib + i + 1] == 'x')
{
i += 2;
for (; ; )
{
if (buffer[ib + i] >= '0' && buffer[ib + i] <= '9')
{
t *= 16;
t += (uint)(buffer[ib] - '0');
ib++;
continue;
}
if (buffer[ib + i] >= 'a' && buffer[ib + i] <= 'f')
{
t *= 16;
t += (uint)(buffer[ib + i] - 'a' + 10);
ib++;
continue;
}
return t;
}
}
for (; i < len; i++)
{
byte b = buffer[ib + i];
if (b >= '0' && b <= '9')
{
t *= 10;
t += b - '0';
}
else if (b == ',')
{
continue;
}
else
{
break;
}
}
return t;
}
public ulong GetHex(int fld)
{
byte[] buffer = this.buffer;
int ib = fields[fld];
while (buffer[ib] == (byte)' ')
{
ib++;
}
if (buffer[ib] == '0' && buffer[ib + 1] == 'x')
{
ib += 2;
}
ulong t = 0;
for (; ; )
{
if (buffer[ib] >= '0' && buffer[ib] <= '9')
{
t *= 16;
t += (uint)(buffer[ib] - '0');
ib++;
continue;
}
if (buffer[ib] >= 'a' && buffer[ib] <= 'f')
{
t *= 16;
t += (uint)(buffer[ib] - 'a' + 10);
ib++;
continue;
}
break;
}
return t;
}
public int GetInt(int fld)
{
byte[] buffer = this.buffer;
int ib = fields[fld];
while (buffer[ib] == (byte)' ')
{
ib++;
}
int t = 0;
while (buffer[ib] >= '0' && buffer[ib] <= '9')
{
t *= 10;
t += buffer[ib] - '0';
ib++;
}
return t;
}
public int GetInt()
{
byte[] buffer = this.buffer;
int ib = this.ib;
while (buffer[ib] == (byte)' ')
{
ib++;
}
int t = 0;
while (buffer[ib] >= '0' && buffer[ib] <= '9')
{
t *= 10;
t += buffer[ib] - '0';
ib++;
}
return t;
}
public ByteWindow Trim()
{
while (len > 0 && buffer[ib] == ' ')
{
ib++;
len--;
}
while (len > 0 && buffer[ib + len - 1] == ' ')
{
len--;
}
return this;
}
public static char[] chars = new char[10240];
public string GetString()
{
int cch = de.GetChars(buffer, ib, len, chars, 0);
return new String(chars, 0, cch);
}
public static string MakeString(byte[] bytes)
{
int cch = de.GetChars(bytes, 0, bytes.Length, chars, 0);
return new String(chars, 0, cch);
}
public static byte[] MakeBytes(String s)
{
char[] ca = s.ToCharArray();
int byteCount = en.GetByteCount(ca, 0, ca.Length, true);
byte[] bytes = new byte[byteCount];
en.GetBytes(ca, 0, ca.Length, bytes, 0, true);
return bytes;
}
public static int CompareBytes(byte[] b1, byte[] b2, bool caseInsensitive)
{
int i = 0;
for (i = 0; i < b1.Length; i++)
{
if (i == b2.Length)
{
return 1;
}
byte c1 = b1[i];
byte c2 = b2[i];
if (caseInsensitive)
{
if ('a' <= c1 && c1 <= 'z')
{
c1 -= ('a' - 'A');
}
if ('a' <= c2 && c2 <= 'z')
{
c2 -= ('a' - 'A');
}
}
if (c1 < c2)
{
return -1;
}
if (c1 > c2)
{
return 1;
}
}
if (i < b2.Length)
{
return -1;
}
return 0;
}
public bool Contains(byte[] substr)
{
if (substr.Length == 0)
{
return true;
}
if (substr.Length > len)
{
return false;
}
for (int i = 0; i < len; i++)
{
int j = 0;
for (; j < substr.Length; j++)
{
if (buffer[i + ib + j] != substr[j])
{
break;
}
}
if (j == substr.Length)
{
return true;
}
}
return false;
}
public bool StartsWith(byte[] prefix)
{
if (prefix.Length > len)
{
return false;
}
for (int i = prefix.Length - 1; i >= 0; i--)
{
if (buffer[i + ib] != prefix[i])
{
return false;
}
}
return true;
}
public byte[] Clone()
{
byte[] bytes = new byte[len];
for (int i = 0; i < len; i++)
{
bytes[i] = buffer[ib + i];
}
return bytes;
}
public int Compare(ByteWindow t)
{
int i = 0;
for (i = 0; i < len; i++)
{
if (i == t.len)
{
return 1;
}
if (buffer[ib + i] < t.buffer[t.ib + i])
{
return -1;
}
if (buffer[ib + i] > t.buffer[t.ib + i])
{
return 1;
}
}
if (i < t.len)
{
return -1;
}
return 0;
}
/// <summary>
/// Useful in debugging. Not intended for normal use
/// </summary>
public override string ToString()
{
return GetString();
}
/// <summary>
/// Useful in debugging. Not intended for normal use
/// </summary>
public string Dump
{
get
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
ByteWindow b = this;
for (int i = 0; i < fieldsLen && i < fields.Length - 1; i++)
{
b.Field(i);
if (b.len < 0)
{
sb.Append("ERROR_FIELD");
break;
}
sb.Append(i).Append("='").Append(b.GetString()).Append("' ");
}
sb.Append(')');
return sb.ToString();
}
}
}
public class BigStream
{
private BackgroundReader bgReader = null;
private const int cbBufferSize = 1 << 16; // 64k
private FileStream src;
private int cb;
private int ib = 0;
private byte[] stm_buffer = new byte[cbBufferSize];
private short[] stm_offsets = new short[cbBufferSize / 2];
private int stm_c_offsets = 0;
private int stm_i_offset = 0;
private int[] fields = new int[100];
private System.Threading.Thread bgThread = null;
~BigStream()
{
Close();
}
public BigStream(string filename)
{
src = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
if (filename.EndsWith(".csvz"))
{
InitArchiveSettings();
}
bgReader = new BackgroundReader(src, offsets);
bgThread = new System.Threading.Thread(() =>
{
bgReader.DoWork();
});
bgThread.Start();
bgReader.Seek(0);
cb = ReadBuffer(stm_buffer, 0, stm_buffer.Length);
ib = 0;
}
public long Position
{
get
{
return pos;
}
set
{
bgReader.Seek(value);
pos = value;
cb = ReadBuffer(stm_buffer, 0, stm_buffer.Length);
ib = 0;
posNext = pos;
}
}
private List<long> offsets = new List<long>();
private int ReadBuffer(byte[] buffer, int ib, int len)
{
var b = bgReader.ReadBlock();
// for the gzip case, the main thread should do the line breaking
if (offsets.Count != 0)
{
LineBreaker.ComputeLineAndFieldOffsets(b);
}
int cb = b.cb;
posNext = b.position;
if (b.cb > 0)
{
Array.Copy(b.buffer, 0, buffer, ib, b.cb);
Array.Copy(b.offsets, 0, stm_offsets, 0, b.cFields);
stm_c_offsets = b.cFields;
stm_i_offset = 0;
}
bgReader.Free(b);
return cb;
}
private void InitArchiveSettings()
{
var stmlen = src.Length;
var r0 = MakeReader(src, stmlen - 8, 8);
var pos = r0.ReadInt64();
var r1 = MakeReader(src, pos, (int)(stmlen - pos));
var c = r1.ReadInt32();
for (int i = 0; i < c; i++)
{
var offset = r1.ReadInt64();
offsets.Add(offset);
}
}
private BinaryReader MakeReader(FileStream stm, long offset, int count)
{
var b = new byte[count];
stm.Seek(offset, SeekOrigin.Begin);
int c = stm.Read(b, 0, count);
var m = new MemoryStream(b, 0, c);
return new BinaryReader(m);
}
private long pos = 0;
private long posNext = 0;
public bool ReadLine(ByteWindow b)
{
pos = posNext;
for (; ; )
{
int fld = 0;
while (stm_i_offset < stm_c_offsets)
{
ib = stm_offsets[stm_i_offset];
if (ib >= 0)
{
if (fld < fields.Length)
{
fields[fld++] = ib;
}
stm_i_offset++;
}
else
{
ib = -ib;
b.ib = fields[0];
b.len = (ib - b.ib);
b.fields = fields;
b.buffer = stm_buffer;
b.fieldsLen = fld;
// note the fields offset array goes one past the number of fields so that length can always be computed
// for a legal field by taking the offset of field[n+1] minus field[n]
// include just one terminator character, either the /r or the /n
if (ib > 0 && stm_buffer[ib - 1] == '\r')
{
if (fld < fields.Length)
{
fields[fld++] = ib; // use the /r if there is one
}
}
else
{
if (fld < fields.Length)
{
fields[fld++] = ib + 1; // else use the /n
}
b.len++;
}
stm_i_offset++;
posNext += b.len + 1;
return true;
}
}
int cb = ReadBuffer(stm_buffer, 0, stm_buffer.Length);
if (cb == 0)
{
b.fields = null;
b.buffer = null;
b.ib = 0;
b.len = 0;
b.fieldsLen = 0;
return false;
}
}
}
// For debugging only gets 256 characters at a particular position.
private string ToString(int pos)
{
int cch = ByteWindow.de.GetChars(stm_buffer, pos, Math.Min(256, stm_buffer.Length - pos), ByteWindow.chars, 0);
return new String(ByteWindow.chars, 0, cch);
}
internal void Close()
{
if (bgReader != null)
{
bgReader.Exit();
}
bgReader = null;
if (src != null)
{
src.Close();
}
src = null;
}
}
internal class BackgroundReader
{
private const int buffersize = 32000;
private FileStream src = null;
private List<long> offsets = null;
public BackgroundReader(FileStream src, List<long> offsets)
{
this.src = src;
this.offsets = offsets;
}
public class Block
{
public long position;
public int cb;
public int cFields;
public short[] offsets = new short[buffersize / 2];
public byte[] buffer = new byte[buffersize];
}
private enum CmdCode
{
Seek,
Stop,
Free,
Exit
}
private class Cmd
{
public CmdCode code;
public long position;
public Block block;
}
private LinkedList<Cmd> cmds = new LinkedList<Cmd>();
private LinkedList<Block> blocksReady = new LinkedList<Block>();
private LinkedList<Block> blocksFree = new LinkedList<Block>();
private System.Threading.Semaphore semaphoreToBg = new System.Threading.Semaphore(0, 10000);
private System.Threading.Semaphore semaphoreFromBg = new System.Threading.Semaphore(0, 10000);
private const int blocks_readahead = 16;
private byte[] bufferScratch = new byte[buffersize];
private int cbScratch = 0;
private long currentSegmentOffset = 0;
private int currentSegment = 0;
public void DoWork()
{
for (int i = 0; i < blocks_readahead; i++)
{
blocksFree.AddLast(new Block());
}
bool fReading = false;
GZipStream gstm = null;
for (; ; )
{
semaphoreToBg.WaitOne();
Cmd cmd = null;
lock (cmds)
{
cmd = cmds.First.Value;
cmds.RemoveFirst();
}
switch (cmd.code)
{
case CmdCode.Exit:
if (gstm != null)
{
gstm.Close();
}
return;
case CmdCode.Free:
blocksFree.AddLast(cmd.block);
break;
case CmdCode.Seek:
if (offsets.Count == 0)
{
src.Seek(cmd.position, SeekOrigin.Begin);
currentSegment = 0;
currentSegmentOffset = cmd.position;
cbScratch = 0;
}
else
{
int seg = (int)(cmd.position >> 32);
int offset = (int)(cmd.position & 0xffffffff);
if (gstm != null)
{
gstm.Close();
gstm = null;
}
currentSegment = (int)seg;
src.Seek(offsets[currentSegment], SeekOrigin.Begin);
currentSegmentOffset = offset;
cbScratch = 0;
gstm = new GZipStream(src, CompressionMode.Decompress, true);
while (offset > 0)
{
int cb = Math.Min(offset, bufferScratch.Length);
cb = gstm.Read(bufferScratch, 0, cb);
offset -= cb;
}
}
fReading = true;
break;
case CmdCode.Stop:
fReading = false;
break;
}
if (!fReading)
{
continue;
}
if (offsets.Count == 0)
{
// this is not an archive
while (blocksFree.Count > 0)
{
Block b = blocksFree.First.Value;
blocksFree.RemoveFirst();
int cbBuffer = 0;
int cbRead = 0;
if (cbScratch > 0)
{
Array.Copy(bufferScratch, b.buffer, cbScratch);
cbBuffer = cbScratch;
cbScratch = 0;
}
cbRead = src.Read(b.buffer, cbBuffer, b.buffer.Length - cbBuffer);
cbBuffer += cbRead;
ProcessAndTransfer(b, cbBuffer);
if (cbRead == 0)
{
fReading = false;
break;
}
}
}
else
{
// this is an archive...
while (blocksFree.Count > 0)
{
Block b = blocksFree.First.Value;
blocksFree.RemoveFirst();
if (gstm == null)
{
ProcessAndTransfer(b, 0);
fReading = false;
break;
}
int cbBuffer = 0;
int cbRead = 0;
if (cbScratch > 0)
{
Array.Copy(bufferScratch, b.buffer, cbScratch);
cbBuffer = cbScratch;
cbScratch = 0;
}
while (cbBuffer < b.buffer.Length)
{
cbRead = gstm.Read(b.buffer, cbBuffer, b.buffer.Length - cbBuffer);
cbBuffer += cbRead;
if (cbBuffer == b.buffer.Length)
{
break;
}
if (cbRead == 0)
{
break;
}
}
if (cbBuffer > 0)
{
ProcessAndTransfer(b, cbBuffer);
}
else
{
// put it back, since we didn't use it
blocksFree.AddFirst(b);
}
if (cbRead != 0)
{
continue;
}
currentSegment++;
currentSegmentOffset = 0;
if (currentSegment < offsets.Count)
{
src.Seek(offsets[currentSegment], SeekOrigin.Begin);
gstm.Recycle();
}
else
{
gstm.Close();
gstm = null;
}
}
}
}
}
private long seekPosition = -1;
public void Seek(long position)
{
var cmd = new Cmd();
cmd.code = CmdCode.Seek;
cmd.position = position;
seekPosition = position;
lock (cmds)
{
cmds.AddLast(cmd);
}
semaphoreToBg.Release();
}
public void Stop()
{
var cmd = new Cmd();
cmd.code = CmdCode.Stop;
lock (cmds)
{
cmds.AddLast(cmd);
}
semaphoreToBg.Release();
}
public void Exit()
{
var cmd = new Cmd();
cmd.code = CmdCode.Exit;
lock (cmds)
{
cmds.AddLast(cmd);
}
semaphoreToBg.Release();
}
public void Free(Block b)
{
var cmd = new Cmd();
cmd.code = CmdCode.Free;
cmd.block = b;
lock (cmds)
{
cmds.AddLast(cmd);
}
semaphoreToBg.Release();
}
private long lengthStatistic;
private long countStatistic;
public Block ReadBlock()
{
for (; ; )
{
Block b;
semaphoreFromBg.WaitOne();
lock (blocksReady)
{
b = blocksReady.First.Value;
blocksReady.RemoveFirst();
}
if (seekPosition == -1)
{
countStatistic++;
lengthStatistic += blocksReady.Count;
return b;
}
if (b.position != seekPosition)
{
Free(b);
continue;
}
countStatistic++;
lengthStatistic += blocksReady.Count;
seekPosition = -1;
return b;
}
}
private void ProcessAndTransfer(Block b, int cbBuffer)
{
if (cbBuffer > 0)
{
byte[] buffer = b.buffer;
int ibLastNewline = cbBuffer - 1;
while (buffer[ibLastNewline] != '\n' && ibLastNewline > 0)
{
ibLastNewline--;
}
int ibCopy = ibLastNewline + 1;
int ib = 0;
while (ibCopy < cbBuffer)
{
bufferScratch[ib++] = buffer[ibCopy++];
}
cbScratch = ib;
b.position = (((long)currentSegment) << 32) + currentSegmentOffset;
b.cb = ibLastNewline + 1;
currentSegmentOffset += b.cb;
// for the non-gzip case, the background thread should do the line breaking
if (offsets.Count == 0)
{
LineBreaker.ComputeLineAndFieldOffsets(b);
}
}
else
{
b.position = -1;
b.cb = 0;
b.offsets[0] = 0;
}
lock (blocksReady)
{
blocksReady.AddLast(b);
}
semaphoreFromBg.Release(1);
}
}
internal static class LineBreaker
{
public static void ComputeLineAndFieldOffsets(BackgroundReader.Block b)
{
int cb = b.cb;
int fld = 0;
int ib = 0;
byte[] buffer = b.buffer;
short[] fields = b.offsets;
fields[fld++] = (short)ib;
// there must still be a newline or we wouldn't be here
while (ib < cb)
{
switch ((char)buffer[ib])
{
case ',':
fields[fld++] = (short)(ib + 1);
ib++;
break;
case '\n':
fields[fld++] = (short)-ib;
fields[fld++] = (short)(ib + 1);
ib++;
break;
case '!':
case '"':
// If we see a ! assume it is the ! in Image!Function
// Since Function can itself contain commas (C++ templates, for example)
// we need to parse it more carefully
ib = ParseCarefully(buffer, ib);
break;
default:
ib++;
break;
}
}
b.cFields = fld;
}
// On entry, buffer[ib] points to the ! in Image!Function
// Need to parse through Function, matching angle brackets and parentheses as we go,
// until we reach the end. The point is that the undecordated
// function name may contain a comma and we don't want to be fooled into thinking
// it's a field delimiter.
// Returns true if there is more to go on this line. false if '\n' was reached.
private static int ParseCarefully(byte[] buffer, int ib)
{
// This is pretty naive. No attempt made to pair up brackets.
int nOpenAngleBrackets = 0;
int nOpenParentheses = 0;
bool bInQuote = (buffer[ib] == '"');
for (++ib; ; ++ib)
{
switch ((char)buffer[ib])
{
case '\n':
return ib;
case '"': // Quotes don't nest for XPERF (no way to escape them)
if (bInQuote)
{
ib++;
return ib;
}
break;
case '<':
nOpenAngleBrackets++;
break;
case '>':
nOpenAngleBrackets--;
break;
case '(':
nOpenParentheses++;
break;
case ')':
nOpenParentheses--;
break;
case ',':
case ' ':
if (nOpenParentheses == 0 && nOpenAngleBrackets == 0 && !bInQuote)
{
return ib;
}
break;
}
}
}
}
}
| |
#region Using Directives
using System;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Services;
using System.IO;
using Microsoft.Practices.Common;
using System.ComponentModel.Design;
using Microsoft.Practices.RecipeFramework.VisualStudio.Templates;
using System.Collections.Generic;
using EnvDTE;
using Microsoft.Practices.RecipeFramework.Library.Templates.Actions;
using System.Text.RegularExpressions;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.Common.Services;
using System.Xml;
using EnvDTE80;
using Microsoft.Win32;
using System.Collections;
using Microsoft.Practices.RecipeFramework.VisualStudio;
using Microsoft.VisualStudio;
using System.Globalization;
using System.Security.Permissions;
using System.Windows.Forms;
#endregion
namespace SPALM.SPSF.Library.Actions
{
[ServiceDependency(typeof(DTE)), ServiceDependency(typeof(ITypeResolutionService))]
public class ExtendedUnfoldTemplateActionBase : ConfigurableAction
{
// Fields
private string destFolder;
private string itemName;
private object newItem;
private string path = string.Empty;
private object root;
private string template;
// Methods
private void AddItemTemplate(Project rootproject)
{
DTE service = (DTE)this.GetService(typeof(DTE));
string str2 = DteHelper.BuildPath(rootproject);
if (!string.IsNullOrEmpty(this.Path))
{
str2 = System.IO.Path.Combine(str2, this.Path);
}
ProjectItem item = DteHelper.FindItemByPath(service.Solution, str2);
if (item != null)
{
this.NewItem = item.ProjectItems.AddFromTemplate(this.Template, this.ItemName);
}
else
{
Project project = DteHelper.FindProjectByPath(service.Solution, str2);
if (project == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, "InsertionPointException", new object[] { str2 }));
}
project.ProjectItems.AddFromTemplate(this.Template, this.ItemName);
}
}
private void AddProjectTemplate(Project project)
{
try
{
IRecipeManagerService provider = (IRecipeManagerService)this.GetService(typeof(IRecipeManagerService));
GuidancePackage p = provider.GetPackage("SharePointSoftwareFactory.Base");
GuidancePackage p2 = provider.EnablePackage("SharePointSoftwareFactory.Base");
}
catch (Exception)
{
}
DTE service = (DTE)this.GetService(typeof(DTE));
SolutionFolder folder = null;
if (project == null)
{
if (string.IsNullOrEmpty(this.Path))
{
//char[] invalidedChars = System.IO.Path.GetInvalidPathChars();
//foreach (char c in invalidedChars)
//{
// if (this.Template.IndexOf(c) > 0)
// {
// }
// if (this.DestinationFolder.IndexOf(c) > 0)
// {
// }
//}
this.NewItem = service.Solution.AddFromTemplate(this.Template, this.DestinationFolder, this.ItemName, false);
}
else
{
folder = (SolutionFolder)DteHelper.FindProjectByPath(service.Solution, this.Path).Object;
this.NewItem = folder.AddFromTemplate(this.Template, this.DestinationFolder, this.ItemName);
}
}
else
{
//sometimes in the solutionfolder a project already exists but is not part of the project
//so we delete the folder if it already exists
if (Directory.Exists(this.DestinationFolder))
{
if (MessageBox.Show("Directory '" + this.DestinationFolder + "' already exists in the solution. Delete directory? If you choose 'No' the directory will be renamed to '" + this.DestinationFolder + "_Backup'", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Directory.Delete(this.DestinationFolder, true);
}
else
{
string backupDirectoryName = this.DestinationFolder + "_Backup";
int count = 1;
while (Directory.Exists(backupDirectoryName))
{
backupDirectoryName = this.DestinationFolder + "_Backup" + count.ToString();
count++;
}
Directory.Move(this.DestinationFolder, backupDirectoryName);
}
}
folder = (SolutionFolder)project.Object;
this.NewItem = folder.AddFromTemplate(this.Template, this.DestinationFolder, this.ItemName);
}
if (this.newItem == null)
{
ProjectItems projectItems;
if (folder != null)
{
projectItems = folder.Parent.ProjectItems;
}
else
{
projectItems = service.Solution.Projects as ProjectItems;
}
if (projectItems != null)
{
foreach (ProjectItem item in projectItems)
{
if (item.Name.Contains(this.ItemName))
{
this.NewItem = item.Object as Project;
break;
}
}
}
else
{
this.NewItem = FindProjectByName(service, this.ItemName, false);
}
}
}
public Project FindProject(_DTE vs, Predicate<Project> match)
{
Guard.ArgumentNotNull(vs, "vs");
Guard.ArgumentNotNull(match, "match");
foreach (Project project in vs.Solution.Projects)
{
if (match(project))
{
return project;
}
Project project2 = FindProjectInternal(project.ProjectItems, match);
if (project2 != null)
{
return project2;
}
}
return null;
}
private Project FindProjectInternal(ProjectItems items, Predicate<Project> match)
{
if (items != null)
{
foreach (ProjectItem item in items)
{
Project project = item.SubProject ?? (item.Object as Project);
if (project != null)
{
if (match(project))
{
return project;
}
project = FindProjectInternal(project.ProjectItems, match);
if (project != null)
{
return project;
}
}
}
}
return null;
}
public Project FindProjectByName(DTE dte, string name, bool isWeb)
{
Predicate<Project> match = null;
if (!isWeb)
{
if (match == null)
{
match = delegate(Project internalProject)
{
return internalProject.Name == name;
};
}
return FindProject(dte, match);
}
foreach (Project project2 in dte.Solution.Projects)
{
if (project2.Name.Contains(name))
{
return project2;
}
if (project2.ProjectItems != null)
{
Project project3 = FindProjectByName(project2.ProjectItems, name);
if (project3 != null)
{
return project3;
}
}
}
return null;
}
private Project FindProjectByName(ProjectItems items, string name)
{
foreach (ProjectItem item in items)
{
if ((item.Object is Project) && ((Project)item.Object).Name.Contains(name))
{
return (item.Object as Project);
}
if (item.ProjectItems != null)
{
Project project = FindProjectByName(item.ProjectItems, name);
if (project != null)
{
return project;
}
}
}
return null;
}
public override void Execute()
{
DTE service = (DTE)this.GetService(typeof(DTE));
Project project = FindProjectByName(service, this.ItemName, false);
if (project != null)
{
this.NewItem = project;
}
else
{
if (string.IsNullOrEmpty(this.DestinationFolder))
{
this.DestinationFolder = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(service.Solution.FileName), this.ItemName);
if (Directory.Exists(this.DestinationFolder))
{
Directory.Delete(this.DestinationFolder, true);
}
}
this.InternalExecute();
}
}
private void InternalExecute()
{
if ((this.Root == null) || (this.Root is Solution))
{
this.AddProjectTemplate(null);
}
else if ((this.Root is Project) && (((Project)this.Root).Object is SolutionFolder))
{
this.AddProjectTemplate((Project)this.Root);
}
else if (this.Root is SolutionFolder)
{
this.AddProjectTemplate(((SolutionFolder)this.Root).Parent);
}
else if (this.Root is Project)
{
this.AddItemTemplate((Project)this.Root);
}
}
public override void Undo()
{
}
// Properties
[Input]
public string DestinationFolder
{
get
{
return this.destFolder;
}
set
{
this.destFolder = value;
}
}
[Input(Required = true)]
public string ItemName
{
get
{
return this.itemName;
}
set
{
this.itemName = value;
}
}
[Output]
public object NewItem
{
get
{
return this.newItem;
}
set
{
this.newItem = value;
}
}
[Output]
public string CreatedProjectID
{
get
{
if(newItem is Project)
{
return Helpers.GetProjectGuid(newItem as Project);
}
else if(newItem is ProjectItem)
{
return Helpers.GetProjectGuid((newItem as ProjectItem).ContainingProject);
}
return "";
}
}
[Input]
public string Path
{
get
{
return this.path;
}
set
{
this.path = value;
}
}
[Input]
public object Root
{
get
{
return this.root;
}
set
{
this.root = value;
}
}
[Input(Required = true)]
public string Template
{
get
{
if (!File.Exists(this.template))
{
TypeResolutionService service = (TypeResolutionService)this.GetService(typeof(ITypeResolutionService));
if (service != null)
{
this.template = new FileInfo(System.IO.Path.Combine(System.IO.Path.Combine(service.BasePath, @"Templates\"), this.template)).FullName;
}
}
return this.template;
}
set
{
this.template = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Netfox.Framework.Models;
using Netfox.Framework.Models.PmLib.SupportedTypes;
using PacketParser;
using PacketParser.Packets;
using ProtocolIdentification;
namespace Spid
{
internal class SessionAndProtocolModelExtractorFlow
{
private readonly Queue<KeyValuePair<ISession, ProtocolModel>> _completedProtocolModelsQueue; //30*256*(8+8)=~120kB per item
private readonly SortedList<String, ProtocolModel> _protocolModels;
private readonly Configuration config;
private readonly Queue<Frame> frameQueue; //~1kB per item
private Task _backgroundFileLoader, _backgroundFrameToSessionAdder;
private L4Conversation _conversation;
private Type _packetBaseType;
private SessionHandler _sessionHandler;
private AutoResetEvent fillInQueueAutoResetEvent = new AutoResetEvent(false);
public SessionAndProtocolModelExtractorFlow(SortedList<String, ProtocolModel> protocolModels, Configuration config)
{
this.config = config;
this._protocolModels = protocolModels;
this.frameQueue = new Queue<Frame>(); //(this._frameQueueMaxSize);
this._completedProtocolModelsQueue = new Queue<KeyValuePair<ISession, ProtocolModel>>();
this._backgroundFileLoader = new Task(this.backgroundFileLoader_DoWork);
this._backgroundFrameToSessionAdder = new Task(this.backgroundFrameToSessionAdder_DoWork);
}
public String RunRecognition(L4Conversation conversation)
{
this._conversation = conversation;
if(!this.SetPacketBaseType()) { return null; }
this._completedProtocolModelsQueue.Clear();
this.frameQueue.Clear();
this._sessionHandler = new SessionHandler(this.config.MaxSimultaneousSessions, this.config); //1000 parallel sessions is a good value
this._sessionHandler.SessionProtocolModelCompleted += this.sessionHandler_SessionProtocolModelCompleted;
this._backgroundFileLoader = new Task(this.backgroundFileLoader_DoWork);
this._backgroundFrameToSessionAdder = new Task(this.backgroundFrameToSessionAdder_DoWork);
this._backgroundFileLoader.Start();
this._backgroundFrameToSessionAdder.Start();
this._backgroundFileLoader.Wait();
this._backgroundFrameToSessionAdder.Wait();
var sessions = this._sessionHandler.GetSessionsWithoutCompletedProtocolModels();
// Debug.Assert(sessions.Count() == 1);
var protocols =
sessions.Select(session => this.GetBestProtocolMatch(session.ApplicationProtocolModel, this._protocolModels)).Where(protocol => protocol != null).ToList();
protocols.AddRange(
this._completedProtocolModelsQueue.Select(session => session.Value != null? this.GetBestProtocolMatch(session.Value, this._protocolModels) : null)
.Where(protocol => protocol != null));
if(protocols.Any())
{
if(protocols.Count != 1)
{
Debug.Write("Recognized more conversations tags> ");
foreach(var proto in protocols) { Debug.Write(proto + " "); }
Debug.WriteLine("");
}
return protocols.First().ToString();
}
return null;
}
private void backgroundFileLoader_DoWork()
{
//LoadingProcess lp=(LoadingProcess)e.Argument;
var nFramesReceived = 0;
foreach(var frame in this._conversation.Frames.OrderBy(f => f.FrameIndex))
{
//var millisecondsToSleep = 1;
//while (frameQueue.Count >= _frameQueueMaxSize)
//{
// Thread.Sleep(millisecondsToSleep);
// millisecondsToSleep = Math.Min(2 * millisecondsToSleep, 5000);
//}
lock(this.frameQueue) { this.frameQueue.Enqueue(new Frame(frame.TimeStamp, frame.L2Data(), this._packetBaseType, ++nFramesReceived, false)); }
this.fillInQueueAutoResetEvent.Set();
}
//Thread.Sleep(100);
////this.backgroundFileLoaderCompleted=true;
}
private void backgroundFrameToSessionAdder_DoWork()
{
//var bufferUsage=0;
//var millisecondsToSleep=1;
while(!this._backgroundFileLoader.IsCompleted || this.frameQueue.Count > 0)
{
// if(frameQueue.Count>0 && _completedProtocolModelsQueue.Count<_completedProtocolModelsQueueMaxSize) {
// millisecondsToSleep=1;
// Frame frame;
// lock(frameQueue) {
// frame=frameQueue.Dequeue();
// }
// ISession session;
// if(_sessionHandler.TryGetSession(frame, out session)) {
// session.AddFrame(frame);
// }
// }
// else {
// Thread.Sleep(millisecondsToSleep);
// millisecondsToSleep=Math.Min(2*millisecondsToSleep, 5000);
// }
if(this.frameQueue.Count > 0)
{
Frame frame;
lock(this.frameQueue) { frame = this.frameQueue.Dequeue(); }
ISession session;
if(this._sessionHandler.TryGetSession(frame, out session)) { session.AddFrame(frame); }
}
else
{
this.fillInQueueAutoResetEvent.WaitOne(100);
}
}
}
private ProtocolModel GetBestProtocolMatch(ProtocolModel observationModel, SortedList<String, ProtocolModel> protocolModels)
{
ProtocolModel bestProtocolMatch = null;
var bestProtocolMatchDivergence = this.config.DivergenceThreshold; //the highest allowed distance for a valid protocol model match
foreach(var protocolModel in this._protocolModels.Values)
{
var divergence = observationModel.GetAverageKullbackLeiblerDivergenceFrom(protocolModel);
if(divergence < bestProtocolMatchDivergence)
{
bestProtocolMatch = protocolModel;
bestProtocolMatchDivergence = divergence;
}
}
//TODO I have no idea why this is not working...
//var _protocolModelsDivergences = new double[_protocolModels.Values.Count];
//var _protocolModelsResulting = new ProtocolModel[_protocolModels.Values.Count];
//Parallel.ForEach(_protocolModels.Values, (i, state, index) =>
//{
// _protocolModelsDivergences[index] = observationModel.GetAverageKullbackLeiblerDivergenceFrom(i);
// _protocolModelsResulting[index] = i;
//});
//for (int index = 0; index < _protocolModelsDivergences.Length; index++)
//{
// double divergence = _protocolModelsDivergences[index];
// if (bestProtocolMatchDivergence > divergence)
// {
// bestProtocolMatchDivergence = divergence;
// bestProtocolMatch = _protocolModelsResulting[index];
// }
//}
return bestProtocolMatch;
}
private void sessionHandler_SessionProtocolModelCompleted(ISession session, ProtocolModel protocolModel)
{
//this.completedProtocolModels.Add(session, protocolModel);
lock(this._completedProtocolModelsQueue) { this._completedProtocolModelsQueue.Enqueue(new KeyValuePair<ISession, ProtocolModel>(session, protocolModel)); }
}
private Boolean SetPacketBaseType()
{
this._packetBaseType = null;
//TODO other types mapping
switch(this._conversation.Frames.First()?.PmLinkType)
{
case PmLinkType.Ethernet:
this._packetBaseType = typeof(Ethernet2Packet);
break;
case PmLinkType.Raw:
this._packetBaseType = typeof(IPv4Packet);
break;
case PmLinkType.Ieee80211:
this._packetBaseType = typeof(IEEE_802_11Packet);
break;
default:
return false;
}
return true;
}
private delegate void EmptyDelegateCallback();
}
}
| |
/*
* Environment.cs - Implementation of the "System.Environment" class.
*
* Copyright (C) 2001, 2002, 2003 Southern Storm Software, Pty Ltd.
*
* 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
*/
namespace System
{
using System.Security;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Platform;
public sealed class Environment
{
// Internal state.
private static String newLine;
private static int exitCode = 0;
// This class cannot be instantiated.
private Environment() {}
// Initialize the environment state.
static Environment()
{
// Get the newline string.
try
{
newLine = SysCharInfo.GetNewLine();
}
catch(NotImplementedException)
{
// The runtime engine does not have "SysCharInfo".
newLine = "\n";
}
}
// Get the platform-specific newline string.
public static String NewLine
{
get
{
return newLine;
}
}
// Exit from the current process.
public static void Exit(int exitCode)
{
TaskMethods.Exit(exitCode);
}
// Get or set the process exit code.
public static int ExitCode
{
get
{
return exitCode;
}
set
{
if(exitCode != value)
{
exitCode = value;
TaskMethods.SetExitCode(value);
}
}
}
// Determine if application shutdown has started.
public static bool HasShutdownStarted
{
get
{
return false;
}
}
// Get the stack trace for the current context.
public static String StackTrace
{
get
{
return (new StackTrace(1)).ToString();
}
}
// Get the version of the runtime engine.
public static Version Version
{
get
{
return new Version(InfoMethods.GetRuntimeVersion());
}
}
// Get the command line arguments.
public static String[] GetCommandLineArgs()
{
String[] args = TaskMethods.GetCommandLineArgs();
if(args != null)
{
return args;
}
else
{
throw new NotSupportedException
(_("Exception_NoCmdLine"));
}
}
// Get the command line as a single string.
public static String CommandLine
{
get
{
String[] args = GetCommandLineArgs();
return String.Join(" ", args);
}
}
// Get the number of milliseconds since the last reboot.
public static int TickCount
{
get
{
return TimeMethods.GetUpTime();
}
}
// Get a particular environment variable.
public static String GetEnvironmentVariable(String variable)
{
if(variable == null)
{
throw new ArgumentNullException("variable");
}
return TaskMethods.GetEnvironmentVariable(variable);
}
// Get a dictionary that allows access to the set of
// environment variables for the current task.
public static IDictionary GetEnvironmentVariables()
{
return new EnvironmentDictionary();
}
#if !ECMA_COMPAT
// Get the "System" directory.
public static String SystemDirectory
{
get
{
String dir = DirMethods.GetSystemDirectory();
if(dir != null)
{
return dir;
}
else
{
throw new NotSupportedException
(_("Exception_NoSystemDir"));
}
}
}
// Get or set the current working directory.
public static String CurrentDirectory
{
get
{
return Directory.GetCurrentDirectory();
}
set
{
Directory.SetCurrentDirectory(value);
}
}
// Get the NetBIOS machine name.
public static String MachineName
{
get
{
return InfoMethods.GetNetBIOSMachineName();
}
}
// Get the operating system version.
public static OperatingSystem OSVersion
{
get
{
return new OperatingSystem
(InfoMethods.GetPlatformID(),
new Version(5, 1, 2600, 0));
}
}
// Get the domain name for this machine.
public static String UserDomainName
{
get
{
return InfoMethods.GetUserDomainName();
}
}
// Determine if we are in interactive mode.
public static bool UserInteractive
{
get
{
return InfoMethods.IsUserInteractive();
}
}
// Get the name of the current user.
public static String UserName
{
get
{
return InfoMethods.GetUserName();
}
}
// Get the size of the working set.
public static long WorkingSet
{
get
{
return InfoMethods.GetWorkingSet();
}
}
#if CONFIG_FRAMEWORK_1_2
// Get the number of processors in this machine.
public static int ProcessorCount
{
get
{
return InfoMethods.GetProcessorCount();
}
}
#endif // CONFIG_FRAMEWORK_1_2
// Expand environment variable references in a string.
public static String ExpandEnvironmentVariables(String name)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
if(name.IndexOf('%') != -1)
{
return name;
}
StringBuilder builder = new StringBuilder();
int posn = 0;
int index;
String tag, value;
while(posn < name.Length)
{
index = name.IndexOf('%', posn);
if(index == -1)
{
builder.Append(name, posn, name.Length - posn);
break;
}
if(index > posn)
{
builder.Append(name, posn, index - posn);
posn = index;
index = name.IndexOf('%', posn + 1);
if(index == -1)
{
builder.Append(name, posn, name.Length - posn);
break;
}
tag = name.Substring(posn + 1, index - posn - 1);
value = GetEnvironmentVariable(tag);
if(value != null)
{
builder.Append(value);
}
else
{
builder.Append(name, posn, index + 1 - posn);
}
posn = index + 1;
}
}
return builder.ToString();
}
// Special folder names.
public enum SpecialFolder
{
Desktop = 0x00,
Programs = 0x02,
Personal = 0x05,
Favorites = 0x06,
Startup = 0x07,
Recent = 0x08,
SendTo = 0x09,
StartMenu = 0x0b,
MyMusic = 0x0d,
DesktopDirectory = 0x10,
MyComputer = 0x11,
Templates = 0x15,
ApplicationData = 0x1a,
LocalApplicationData = 0x1c,
InternetCache = 0x20,
Cookies = 0x21,
History = 0x22,
CommonApplicationData = 0x23,
System = 0x25,
ProgramFiles = 0x26,
MyPictures = 0x27,
CommonProgramFiles = 0x2b
}; // enum SpecialFolder
// Import the Win32 SHGetFolderPathA function from "shell32.dll"
[DllImport("shell32.dll", CallingConvention=CallingConvention.Winapi)]
[MethodImpl(MethodImplOptions.PreserveSig)]
extern private static Int32 SHGetFolderPathA
(IntPtr hwndOwner, int nFolder, IntPtr hToken,
uint dwFlags, IntPtr path);
// Get a path to a specific system folder.
public static String GetFolderPath(SpecialFolder folder)
{
// We can use the operating system under Win32.
if(InfoMethods.GetPlatformID() != PlatformID.Unix)
{
// Allocate a buffer to hold the result path.
IntPtr buffer = Marshal.AllocHGlobal(260 /*MAX_PATH*/ + 1);
// Call "SHGetFolderPath" to retrieve the path.
try
{
SHGetFolderPathA(IntPtr.Zero, (int)folder,
IntPtr.Zero, 0, buffer);
String value = Marshal.PtrToStringAnsi(buffer);
if(value != null && value.Length != 0)
{
Marshal.FreeHGlobal(buffer);
return value;
}
}
catch(Exception)
{
// We weren't able to find the function in the DLL.
}
Marshal.FreeHGlobal(buffer);
}
// Special handling for some of the cases.
String dir = null;
switch(folder)
{
case SpecialFolder.System:
{
dir = DirMethods.GetSystemDirectory();
}
break;
case SpecialFolder.ApplicationData:
{
dir = InfoMethods.GetUserStorageDir() +
Path.DirectorySeparatorChar +
"ApplicationData";
}
break;
case SpecialFolder.LocalApplicationData:
{
dir = InfoMethods.GetUserStorageDir() +
Path.DirectorySeparatorChar +
"LocalApplicationData";
}
break;
case SpecialFolder.CommonApplicationData:
{
dir = InfoMethods.GetUserStorageDir() +
Path.DirectorySeparatorChar +
"CommonApplicationData";
}
break;
}
if(dir != null && dir.Length > 0)
{
return dir;
}
// The empty string indicates that the value is not present.
return String.Empty;
}
// Get a list of logical drives on the system.
public static String[] GetLogicalDrives()
{
return DirMethods.GetLogicalDrives();
}
#endif // !ECMA_COMPAT
// Private class that implements a dictionary for environment variables.
private sealed class EnvironmentDictionary : IDictionary
{
public EnvironmentDictionary()
{
// Nothing to do here.
}
// Add an object to this dictionary.
public void Add(Object key, Object value)
{
throw new NotSupportedException(_("NotSupp_ReadOnly"));
}
// Clear this dictionary.
public void Clear()
{
throw new NotSupportedException(_("NotSupp_ReadOnly"));
}
// Determine if this dictionary contains a specific key.
public bool Contains(Object key)
{
String keyName = key.ToString();
if(keyName != null)
{
return (TaskMethods.GetEnvironmentVariable(keyName)
!= null);
}
else
{
throw new ArgumentNullException("key");
}
}
// Copy the contents of this dictionary to an array.
public void CopyTo(Array array, int index)
{
int count;
if(array == null)
{
throw new ArgumentNullException("array");
}
if(index < 0)
{
throw new ArgumentOutOfRangeException
("index", _("ArgRange_Array"));
}
if(array.Rank != 1)
{
throw new ArgumentException(_("Arg_RankMustBe1"));
}
count = TaskMethods.GetEnvironmentCount();
if(index >= array.Length ||
count > (array.Length - index))
{
throw new ArgumentException
(_("Arg_InvalidArrayIndex"));
}
int posn;
for(posn = 0; posn < count; ++posn)
{
array.SetValue(new DictionaryEntry
(TaskMethods.GetEnvironmentKey(posn),
TaskMethods.GetEnvironmentValue(posn)),
index + posn);
}
}
// Enumerate all values in this dictionary.
IEnumerator IEnumerable.GetEnumerator()
{
return new EnvironmentEnumerator();
}
public IDictionaryEnumerator GetEnumerator()
{
return new EnvironmentEnumerator();
}
// Remove a value from this dictionary.
public void Remove(Object key)
{
throw new NotSupportedException(_("NotSupp_ReadOnly"));
}
// Count the number of items in this dictionary.
public int Count
{
get
{
return TaskMethods.GetEnvironmentCount();
}
}
// Determine if this dictionary has a fixed size.
public bool IsFixedSize
{
get
{
return true;
}
}
// Determine if this dictionary is read-only.
public bool IsReadOnly
{
get
{
return true;
}
}
// Determine if this dictionary is synchronized.
public bool IsSynchronized
{
get
{
return false;
}
}
// Get the synchronization root for this dictionary.
public Object SyncRoot
{
get
{
return this;
}
}
// Get a particular object from this dictionary.
public Object this[Object key]
{
get
{
String keyName = key.ToString();
if(keyName != null)
{
return TaskMethods.GetEnvironmentVariable(keyName);
}
else
{
throw new ArgumentNullException("key");
}
}
set
{
throw new NotSupportedException(_("NotSupp_ReadOnly"));
}
}
// Get a list of all keys in this dictionary.
public ICollection Keys
{
get
{
int count = TaskMethods.GetEnvironmentCount();
String[] keys = new String [count];
int posn;
for(posn = 0; posn < count; ++posn)
{
keys[posn] = TaskMethods.GetEnvironmentKey(posn);
}
return keys;
}
}
// Get a list of all values in this dictionary.
public ICollection Values
{
get
{
int count = TaskMethods.GetEnvironmentCount();
String[] values = new String [count];
int posn;
for(posn = 0; posn < count; ++posn)
{
values[posn] =
TaskMethods.GetEnvironmentValue(posn);
}
return values;
}
}
};
// Private class for enumerating over the contents of the environment.
private sealed class EnvironmentEnumerator : IDictionaryEnumerator
{
private int posn;
private int count;
// Constructor.
public EnvironmentEnumerator()
{
posn = -1;
count = TaskMethods.GetEnvironmentCount();
}
// Move to the next item in sequence.
public bool MoveNext()
{
++posn;
return (posn < count);
}
// Reset the enumerator.
public void Reset()
{
posn = -1;
}
// Get the current enumerator value.
public Object Current
{
get
{
return Entry;
}
}
// Get the current dictionary entry value.
public DictionaryEntry Entry
{
get
{
if(posn >= 0 && posn < count)
{
return new DictionaryEntry
(TaskMethods.GetEnvironmentKey(posn),
TaskMethods.GetEnvironmentValue(posn));
}
else
{
throw new InvalidOperationException
(_("Invalid_BadEnumeratorPosition"));
}
}
}
// Get the key associated with the current enumerator value.
public Object Key
{
get
{
if(posn >= 0 && posn < count)
{
return TaskMethods.GetEnvironmentKey(posn);
}
else
{
throw new InvalidOperationException
(_("Invalid_BadEnumeratorPosition"));
}
}
}
// Get the value associated with the current enumerator value.
public Object Value
{
get
{
if(posn >= 0 && posn < count)
{
return TaskMethods.GetEnvironmentValue(posn);
}
else
{
throw new InvalidOperationException
(_("Invalid_BadEnumeratorPosition"));
}
}
}
};
}; // class Environment
}; // namespace System
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.38.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Digital Asset Links API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/digital-asset-links/'>Digital Asset Links API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20190205 (1496)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/digital-asset-links/'>
* https://developers.google.com/digital-asset-links/</a>
* <tr><th>Discovery Name<td>digitalassetlinks
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Digital Asset Links API can be found at
* <a href='https://developers.google.com/digital-asset-links/'>https://developers.google.com/digital-asset-links/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Digitalassetlinks.v1
{
/// <summary>The Digitalassetlinks Service.</summary>
public class DigitalassetlinksService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public DigitalassetlinksService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public DigitalassetlinksService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
assetlinks = new AssetlinksResource(this);
statements = new StatementsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "digitalassetlinks"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://digitalassetlinks.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://digitalassetlinks.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
private readonly AssetlinksResource assetlinks;
/// <summary>Gets the Assetlinks resource.</summary>
public virtual AssetlinksResource Assetlinks
{
get { return assetlinks; }
}
private readonly StatementsResource statements;
/// <summary>Gets the Statements resource.</summary>
public virtual StatementsResource Statements
{
get { return statements; }
}
}
///<summary>A base abstract class for Digitalassetlinks requests.</summary>
public abstract class DigitalassetlinksBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new DigitalassetlinksBaseServiceRequest instance.</summary>
protected DigitalassetlinksBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Digitalassetlinks parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "assetlinks" collection of methods.</summary>
public class AssetlinksResource
{
private const string Resource = "assetlinks";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public AssetlinksResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Determines whether the specified (directional) relationship exists between the specified source and
/// target assets.
///
/// The relation describes the intent of the link between the two assets as claimed by the source asset. An
/// example for such relationships is the delegation of privileges or permissions.
///
/// This command is most often used by infrastructure systems to check preconditions for an action. For
/// example, a client may want to know if it is OK to send a web URL to a particular mobile app instead. The
/// client can check for the relevant asset link from the website to the mobile app to decide if the operation
/// should be allowed.
///
/// A note about security: if you specify a secure asset as the source, such as an HTTPS website or an Android
/// app, the API will ensure that any statements used to generate the response have been made in a secure way by
/// the owner of that asset. Conversely, if the source asset is an insecure HTTP website (that is, the URL
/// starts with `http://` instead of `https://`), the API cannot verify its statements securely, and it is not
/// possible to ensure that the website's statements have not been altered by a third party. For more
/// information, see the [Digital Asset Links technical design
/// specification](https://github.com/google/digitalassetlinks/blob/master/well-known/details.md).</summary>
public virtual CheckRequest Check()
{
return new CheckRequest(service);
}
/// <summary>Determines whether the specified (directional) relationship exists between the specified source and
/// target assets.
///
/// The relation describes the intent of the link between the two assets as claimed by the source asset. An
/// example for such relationships is the delegation of privileges or permissions.
///
/// This command is most often used by infrastructure systems to check preconditions for an action. For
/// example, a client may want to know if it is OK to send a web URL to a particular mobile app instead. The
/// client can check for the relevant asset link from the website to the mobile app to decide if the operation
/// should be allowed.
///
/// A note about security: if you specify a secure asset as the source, such as an HTTPS website or an Android
/// app, the API will ensure that any statements used to generate the response have been made in a secure way by
/// the owner of that asset. Conversely, if the source asset is an insecure HTTP website (that is, the URL
/// starts with `http://` instead of `https://`), the API cannot verify its statements securely, and it is not
/// possible to ensure that the website's statements have not been altered by a third party. For more
/// information, see the [Digital Asset Links technical design
/// specification](https://github.com/google/digitalassetlinks/blob/master/well-known/details.md).</summary>
public class CheckRequest : DigitalassetlinksBaseServiceRequest<Google.Apis.Digitalassetlinks.v1.Data.CheckResponse>
{
/// <summary>Constructs a new Check request.</summary>
public CheckRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The uppercase SHA-265 fingerprint of the certificate. From the PEM certificate, it can be
/// acquired like this:
///
/// $ keytool -printcert -file $CERTFILE | grep SHA256: SHA256:
/// 14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83: \ 42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5
///
/// or like this:
///
/// $ openssl x509 -in $CERTFILE -noout -fingerprint -sha256 SHA256
/// Fingerprint=14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64: \
/// 16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5
///
/// In this example, the contents of this field would be `14:6D:E9:83:C5:73:
/// 06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF: 44:E5`.
///
/// If these tools are not available to you, you can convert the PEM certificate into the DER format,
/// compute the SHA-256 hash of that string and represent the result as a hexstring (that is, uppercase
/// hexadecimal representations of each octet, separated by colons).</summary>
[Google.Apis.Util.RequestParameterAttribute("target.androidApp.certificate.sha256Fingerprint", Google.Apis.Util.RequestParameterType.Query)]
public virtual string TargetAndroidAppCertificateSha256Fingerprint { get; set; }
/// <summary>Web assets are identified by a URL that contains only the scheme, hostname and port parts. The
/// format is
///
/// http[s]://[:]
///
/// Hostnames must be fully qualified: they must end in a single period ("`.`").
///
/// Only the schemes "http" and "https" are currently allowed.
///
/// Port numbers are given as a decimal number, and they must be omitted if the standard port numbers are
/// used: 80 for http and 443 for https.
///
/// We call this limited URL the "site". All URLs that share the same scheme, hostname and port are
/// considered to be a part of the site and thus belong to the web asset.
///
/// Example: the asset with the site `https://www.google.com` contains all these URLs:
///
/// * `https://www.google.com/` * `https://www.google.com:443/` * `https://www.google.com/foo` *
/// `https://www.google.com/foo?bar` * `https://www.google.com/foo#bar` *
/// `https://user@password:www.google.com/`
///
/// But it does not contain these URLs:
///
/// * `http://www.google.com/` (wrong scheme) * `https://google.com/` (hostname does not
/// match) * `https://www.google.com:444/` (port does not match) REQUIRED</summary>
[Google.Apis.Util.RequestParameterAttribute("source.web.site", Google.Apis.Util.RequestParameterType.Query)]
public virtual string SourceWebSite { get; set; }
/// <summary>Android App assets are naturally identified by their Java package name. For example, the Google
/// Maps app uses the package name `com.google.android.apps.maps`. REQUIRED</summary>
[Google.Apis.Util.RequestParameterAttribute("source.androidApp.packageName", Google.Apis.Util.RequestParameterType.Query)]
public virtual string SourceAndroidAppPackageName { get; set; }
/// <summary>Android App assets are naturally identified by their Java package name. For example, the Google
/// Maps app uses the package name `com.google.android.apps.maps`. REQUIRED</summary>
[Google.Apis.Util.RequestParameterAttribute("target.androidApp.packageName", Google.Apis.Util.RequestParameterType.Query)]
public virtual string TargetAndroidAppPackageName { get; set; }
/// <summary>The uppercase SHA-265 fingerprint of the certificate. From the PEM certificate, it can be
/// acquired like this:
///
/// $ keytool -printcert -file $CERTFILE | grep SHA256: SHA256:
/// 14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83: \ 42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5
///
/// or like this:
///
/// $ openssl x509 -in $CERTFILE -noout -fingerprint -sha256 SHA256
/// Fingerprint=14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64: \
/// 16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5
///
/// In this example, the contents of this field would be `14:6D:E9:83:C5:73:
/// 06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF: 44:E5`.
///
/// If these tools are not available to you, you can convert the PEM certificate into the DER format,
/// compute the SHA-256 hash of that string and represent the result as a hexstring (that is, uppercase
/// hexadecimal representations of each octet, separated by colons).</summary>
[Google.Apis.Util.RequestParameterAttribute("source.androidApp.certificate.sha256Fingerprint", Google.Apis.Util.RequestParameterType.Query)]
public virtual string SourceAndroidAppCertificateSha256Fingerprint { get; set; }
/// <summary>Query string for the relation.
///
/// We identify relations with strings of the format `/`, where `` must be one of a set of pre-defined
/// purpose categories, and `` is a free-form lowercase alphanumeric string that describes the specific use
/// case of the statement.
///
/// Refer to [our API documentation](/digital-asset-links/v1/relation-strings) for the current list of
/// supported relations.
///
/// For a query to match an asset link, both the query's and the asset link's relation strings must match
/// exactly.
///
/// Example: A query with relation `delegate_permission/common.handle_all_urls` matches an asset link with
/// relation `delegate_permission/common.handle_all_urls`.</summary>
[Google.Apis.Util.RequestParameterAttribute("relation", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Relation { get; set; }
/// <summary>Web assets are identified by a URL that contains only the scheme, hostname and port parts. The
/// format is
///
/// http[s]://[:]
///
/// Hostnames must be fully qualified: they must end in a single period ("`.`").
///
/// Only the schemes "http" and "https" are currently allowed.
///
/// Port numbers are given as a decimal number, and they must be omitted if the standard port numbers are
/// used: 80 for http and 443 for https.
///
/// We call this limited URL the "site". All URLs that share the same scheme, hostname and port are
/// considered to be a part of the site and thus belong to the web asset.
///
/// Example: the asset with the site `https://www.google.com` contains all these URLs:
///
/// * `https://www.google.com/` * `https://www.google.com:443/` * `https://www.google.com/foo` *
/// `https://www.google.com/foo?bar` * `https://www.google.com/foo#bar` *
/// `https://user@password:www.google.com/`
///
/// But it does not contain these URLs:
///
/// * `http://www.google.com/` (wrong scheme) * `https://google.com/` (hostname does not
/// match) * `https://www.google.com:444/` (port does not match) REQUIRED</summary>
[Google.Apis.Util.RequestParameterAttribute("target.web.site", Google.Apis.Util.RequestParameterType.Query)]
public virtual string TargetWebSite { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "check"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/assetlinks:check"; }
}
/// <summary>Initializes Check parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"target.androidApp.certificate.sha256Fingerprint", new Google.Apis.Discovery.Parameter
{
Name = "target.androidApp.certificate.sha256Fingerprint",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"source.web.site", new Google.Apis.Discovery.Parameter
{
Name = "source.web.site",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"source.androidApp.packageName", new Google.Apis.Discovery.Parameter
{
Name = "source.androidApp.packageName",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"target.androidApp.packageName", new Google.Apis.Discovery.Parameter
{
Name = "target.androidApp.packageName",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"source.androidApp.certificate.sha256Fingerprint", new Google.Apis.Discovery.Parameter
{
Name = "source.androidApp.certificate.sha256Fingerprint",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"relation", new Google.Apis.Discovery.Parameter
{
Name = "relation",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"target.web.site", new Google.Apis.Discovery.Parameter
{
Name = "target.web.site",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "statements" collection of methods.</summary>
public class StatementsResource
{
private const string Resource = "statements";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public StatementsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves a list of all statements from a given source that match the specified target and
/// statement string.
///
/// The API guarantees that all statements with secure source assets, such as HTTPS websites or Android apps,
/// have been made in a secure way by the owner of those assets, as described in the [Digital Asset Links
/// technical design specification](https://github.com/google/digitalassetlinks/blob/master/well-
/// known/details.md). Specifically, you should consider that for insecure websites (that is, where the URL
/// starts with `http://` instead of `https://`), this guarantee cannot be made.
///
/// The `List` command is most useful in cases where the API client wants to know all the ways in which two
/// assets are related, or enumerate all the relationships from a particular source asset. Example: a feature
/// that helps users navigate to related items. When a mobile app is running on a device, the feature would
/// make it easy to navigate to the corresponding web site or Google+ profile.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Retrieves a list of all statements from a given source that match the specified target and
/// statement string.
///
/// The API guarantees that all statements with secure source assets, such as HTTPS websites or Android apps,
/// have been made in a secure way by the owner of those assets, as described in the [Digital Asset Links
/// technical design specification](https://github.com/google/digitalassetlinks/blob/master/well-
/// known/details.md). Specifically, you should consider that for insecure websites (that is, where the URL
/// starts with `http://` instead of `https://`), this guarantee cannot be made.
///
/// The `List` command is most useful in cases where the API client wants to know all the ways in which two
/// assets are related, or enumerate all the relationships from a particular source asset. Example: a feature
/// that helps users navigate to related items. When a mobile app is running on a device, the feature would
/// make it easy to navigate to the corresponding web site or Google+ profile.</summary>
public class ListRequest : DigitalassetlinksBaseServiceRequest<Google.Apis.Digitalassetlinks.v1.Data.ListResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The uppercase SHA-265 fingerprint of the certificate. From the PEM certificate, it can be
/// acquired like this:
///
/// $ keytool -printcert -file $CERTFILE | grep SHA256: SHA256:
/// 14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83: \ 42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5
///
/// or like this:
///
/// $ openssl x509 -in $CERTFILE -noout -fingerprint -sha256 SHA256
/// Fingerprint=14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64: \
/// 16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5
///
/// In this example, the contents of this field would be `14:6D:E9:83:C5:73:
/// 06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF: 44:E5`.
///
/// If these tools are not available to you, you can convert the PEM certificate into the DER format,
/// compute the SHA-256 hash of that string and represent the result as a hexstring (that is, uppercase
/// hexadecimal representations of each octet, separated by colons).</summary>
[Google.Apis.Util.RequestParameterAttribute("source.androidApp.certificate.sha256Fingerprint", Google.Apis.Util.RequestParameterType.Query)]
public virtual string SourceAndroidAppCertificateSha256Fingerprint { get; set; }
/// <summary>Use only associations that match the specified relation.
///
/// See the [`Statement`](#Statement) message for a detailed definition of relation strings.
///
/// For a query to match a statement, one of the following must be true:
///
/// * both the query's and the statement's relation strings match exactly, or * the query's relation
/// string is empty or missing.
///
/// Example: A query with relation `delegate_permission/common.handle_all_urls` matches an asset link with
/// relation `delegate_permission/common.handle_all_urls`.</summary>
[Google.Apis.Util.RequestParameterAttribute("relation", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Relation { get; set; }
/// <summary>Web assets are identified by a URL that contains only the scheme, hostname and port parts. The
/// format is
///
/// http[s]://[:]
///
/// Hostnames must be fully qualified: they must end in a single period ("`.`").
///
/// Only the schemes "http" and "https" are currently allowed.
///
/// Port numbers are given as a decimal number, and they must be omitted if the standard port numbers are
/// used: 80 for http and 443 for https.
///
/// We call this limited URL the "site". All URLs that share the same scheme, hostname and port are
/// considered to be a part of the site and thus belong to the web asset.
///
/// Example: the asset with the site `https://www.google.com` contains all these URLs:
///
/// * `https://www.google.com/` * `https://www.google.com:443/` * `https://www.google.com/foo` *
/// `https://www.google.com/foo?bar` * `https://www.google.com/foo#bar` *
/// `https://user@password:www.google.com/`
///
/// But it does not contain these URLs:
///
/// * `http://www.google.com/` (wrong scheme) * `https://google.com/` (hostname does not
/// match) * `https://www.google.com:444/` (port does not match) REQUIRED</summary>
[Google.Apis.Util.RequestParameterAttribute("source.web.site", Google.Apis.Util.RequestParameterType.Query)]
public virtual string SourceWebSite { get; set; }
/// <summary>Android App assets are naturally identified by their Java package name. For example, the Google
/// Maps app uses the package name `com.google.android.apps.maps`. REQUIRED</summary>
[Google.Apis.Util.RequestParameterAttribute("source.androidApp.packageName", Google.Apis.Util.RequestParameterType.Query)]
public virtual string SourceAndroidAppPackageName { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/statements:list"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"source.androidApp.certificate.sha256Fingerprint", new Google.Apis.Discovery.Parameter
{
Name = "source.androidApp.certificate.sha256Fingerprint",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"relation", new Google.Apis.Discovery.Parameter
{
Name = "relation",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"source.web.site", new Google.Apis.Discovery.Parameter
{
Name = "source.web.site",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"source.androidApp.packageName", new Google.Apis.Discovery.Parameter
{
Name = "source.androidApp.packageName",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Digitalassetlinks.v1.Data
{
/// <summary>Describes an android app asset.</summary>
public class AndroidAppAsset : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Because there is no global enforcement of package name uniqueness, we also require a signing
/// certificate, which in combination with the package name uniquely identifies an app.
///
/// Some apps' signing keys are rotated, so they may be signed by different keys over time. We treat these as
/// distinct assets, since we use (package name, cert) as the unique ID. This should not normally pose any
/// problems as both versions of the app will make the same or similar statements. Other assets making
/// statements about the app will have to be updated when a key is rotated, however.
///
/// (Note that the syntaxes for publishing and querying for statements contain syntactic sugar to easily let you
/// specify apps that are known by multiple certificates.) REQUIRED</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificate")]
public virtual CertificateInfo Certificate { get; set; }
/// <summary>Android App assets are naturally identified by their Java package name. For example, the Google
/// Maps app uses the package name `com.google.android.apps.maps`. REQUIRED</summary>
[Newtonsoft.Json.JsonPropertyAttribute("packageName")]
public virtual string PackageName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Uniquely identifies an asset.
///
/// A digital asset is an identifiable and addressable online entity that typically provides some service or
/// content. Examples of assets are websites, Android apps, Twitter feeds, and Plus Pages.</summary>
public class Asset : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Set if this is an Android App asset.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("androidApp")]
public virtual AndroidAppAsset AndroidApp { get; set; }
/// <summary>Set if this is a web asset.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("web")]
public virtual WebAsset Web { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes an X509 certificate.</summary>
public class CertificateInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The uppercase SHA-265 fingerprint of the certificate. From the PEM certificate, it can be acquired
/// like this:
///
/// $ keytool -printcert -file $CERTFILE | grep SHA256: SHA256:
/// 14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83: \ 42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5
///
/// or like this:
///
/// $ openssl x509 -in $CERTFILE -noout -fingerprint -sha256 SHA256
/// Fingerprint=14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64: \
/// 16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5
///
/// In this example, the contents of this field would be `14:6D:E9:83:C5:73:
/// 06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF: 44:E5`.
///
/// If these tools are not available to you, you can convert the PEM certificate into the DER format, compute
/// the SHA-256 hash of that string and represent the result as a hexstring (that is, uppercase hexadecimal
/// representations of each octet, separated by colons).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sha256Fingerprint")]
public virtual string Sha256Fingerprint { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for the CheckAssetLinks call.</summary>
public class CheckResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Human-readable message containing information intended to help end users understand, reproduce and
/// debug the result.
///
/// The message will be in English and we are currently not planning to offer any translations.
///
/// Please note that no guarantees are made about the contents or format of this string. Any aspect of it may
/// be subject to change without notice. You should not attempt to programmatically parse this data. For
/// programmatic access, use the error_code field below.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("debugString")]
public virtual string DebugString { get; set; }
/// <summary>Error codes that describe the result of the Check operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorCode")]
public virtual System.Collections.Generic.IList<string> ErrorCode { get; set; }
/// <summary>Set to true if the assets specified in the request are linked by the relation specified in the
/// request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("linked")]
public virtual System.Nullable<bool> Linked { get; set; }
/// <summary>From serving time, how much longer the response should be considered valid barring further updates.
/// REQUIRED</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxAge")]
public virtual object MaxAge { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for the List call.</summary>
public class ListResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Human-readable message containing information intended to help end users understand, reproduce and
/// debug the result.
///
/// The message will be in English and we are currently not planning to offer any translations.
///
/// Please note that no guarantees are made about the contents or format of this string. Any aspect of it may
/// be subject to change without notice. You should not attempt to programmatically parse this data. For
/// programmatic access, use the error_code field below.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("debugString")]
public virtual string DebugString { get; set; }
/// <summary>Error codes that describe the result of the List operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorCode")]
public virtual System.Collections.Generic.IList<string> ErrorCode { get; set; }
/// <summary>From serving time, how much longer the response should be considered valid barring further updates.
/// REQUIRED</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxAge")]
public virtual object MaxAge { get; set; }
/// <summary>A list of all the matching statements that have been found.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("statements")]
public virtual System.Collections.Generic.IList<Statement> Statements { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes a reliable statement that has been made about the relationship between a source asset and a
/// target asset.
///
/// Statements are always made by the source asset, either directly or by delegating to a statement list that is
/// stored elsewhere.
///
/// For more detailed definitions of statements and assets, please refer to our [API documentation landing page
/// ](/digital-asset-links/v1/getting-started).</summary>
public class Statement : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The relation identifies the use of the statement as intended by the source asset's owner (that is,
/// the person or entity who issued the statement). Every complete statement has a relation.
///
/// We identify relations with strings of the format `/`, where `` must be one of a set of pre-defined purpose
/// categories, and `` is a free-form lowercase alphanumeric string that describes the specific use case of the
/// statement.
///
/// Refer to [our API documentation](/digital-asset-links/v1/relation-strings) for the current list of supported
/// relations.
///
/// Example: `delegate_permission/common.handle_all_urls` REQUIRED</summary>
[Newtonsoft.Json.JsonPropertyAttribute("relation")]
public virtual string Relation { get; set; }
/// <summary>Every statement has a source asset. REQUIRED</summary>
[Newtonsoft.Json.JsonPropertyAttribute("source")]
public virtual Asset Source { get; set; }
/// <summary>Every statement has a target asset. REQUIRED</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual Asset Target { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes a web asset.</summary>
public class WebAsset : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Web assets are identified by a URL that contains only the scheme, hostname and port parts. The
/// format is
///
/// http[s]://[:]
///
/// Hostnames must be fully qualified: they must end in a single period ("`.`").
///
/// Only the schemes "http" and "https" are currently allowed.
///
/// Port numbers are given as a decimal number, and they must be omitted if the standard port numbers are used:
/// 80 for http and 443 for https.
///
/// We call this limited URL the "site". All URLs that share the same scheme, hostname and port are considered
/// to be a part of the site and thus belong to the web asset.
///
/// Example: the asset with the site `https://www.google.com` contains all these URLs:
///
/// * `https://www.google.com/` * `https://www.google.com:443/` * `https://www.google.com/foo` *
/// `https://www.google.com/foo?bar` * `https://www.google.com/foo#bar` *
/// `https://user@password:www.google.com/`
///
/// But it does not contain these URLs:
///
/// * `http://www.google.com/` (wrong scheme) * `https://google.com/` (hostname does not
/// match) * `https://www.google.com:444/` (port does not match) REQUIRED</summary>
[Newtonsoft.Json.JsonPropertyAttribute("site")]
public virtual string Site { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
//
// ChangePhotoPathController.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2008-2009 Novell, Inc.
// Copyright (C) 2008-2009 Stephane Delcroix
//
// 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.
//
//
// ChangePhotoPath.IChangePhotoPathController.cs: The logic to change the photo path in photos.db
//
// Author:
// Bengt Thuree (bengt@thuree.com)
//
// Copyright (C) 2007
//
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.Specialized;
using FSpot;
using FSpot.Core;
using FSpot.Database;
using FSpot.Utils;
using Hyena;
using FSpot.Settings;
/*
Need to
1) Find old base path, assuming starting /YYYY/MM/DD so look for /YY (/19 or /20)
2) Confirm old base path and display new base path
3) For each Photo, check each version, and change every instance of old base path to new path
Consider!!!
photo_store.Commit(photo) is using db.ExecuteNonQuery, which is not waiting for the command to finish. On my test set of 20.000 photos,
it took SQLite another 1 hour or so to commit all rows after this extension had finished its execution.
Consider 2!!!
A bit of mixture between URI and path. Old and New base path are in String path. Rest in URI.
*/
namespace FSpot.Tools.ChangePhotoPath
{
public enum ProcessResult {
Ok, Cancelled, Error, SamePath, NoPhotosFound, Processing
}
public class ChangePathController
{
PhotoStore photo_store = FSpot.App.Instance.Database.Photos;
List<uint> photo_id_array;
List<uint> version_id_array;
StringCollection old_path_array, new_path_array;
int total_photos;
string orig_base_path;
private const string BASE2000 = "/20";
private const string BASE1900 = "/19";
private const string BASE1800 = "/18";
private IChangePhotoPathGui gui_controller;
private bool user_cancelled;
public bool UserCancelled {
get {return user_cancelled;}
set {user_cancelled = value;}
}
public ChangePathController (IChangePhotoPathGui gui)
{
gui_controller = gui;
total_photos = photo_store.TotalPhotos;
orig_base_path = EnsureEndsWithOneDirectorySeparator (FindOrigBasePath()); // NOT URI
string new_base_path = EnsureEndsWithOneDirectorySeparator (FSpotConfiguration.PhotoUri.LocalPath); // NOT URI
gui_controller.DisplayDefaultPaths (orig_base_path, new_base_path);
user_cancelled = false;
}
private string EnsureEndsWithOneDirectorySeparator (string tmp_str)
{
if ( (tmp_str == null) || (tmp_str.Length == 0) )
return string.Format ("{0}", Path.DirectorySeparatorChar);
while (tmp_str.EndsWith(string.Format ("{0}", Path.DirectorySeparatorChar)))
tmp_str = tmp_str.Remove (tmp_str.Length-1, 1);
return string.Format ("{0}{1}", tmp_str, Path.DirectorySeparatorChar);
}
// Should always return TRUE, since path always ends with "/"
public bool CanWeRun ()
{
return (orig_base_path != null);
}
private string IsThisPhotoOnOrigBasePath (string check_this_path)
{
int i;
i = check_this_path.IndexOf(BASE2000);
if (i > 0)
return (check_this_path.Substring(0, i));
i = check_this_path.IndexOf(BASE1900);
if (i > 0)
return (check_this_path.Substring(0, i));
i = check_this_path.IndexOf(BASE1800);
if (i > 0)
return (check_this_path.Substring(0, i));
return null;
}
private string FindOrigBasePath()
{
string res_path = null;
foreach ( IPhoto photo in photo_store.Query ( "SELECT * FROM photos " ) ) {
string tmp_path = (photo as Photo).DefaultVersion.Uri.AbsolutePath;
res_path = IsThisPhotoOnOrigBasePath (tmp_path);
if (res_path != null)
break;
}
return res_path;
}
private void InitializeArrays()
{
photo_id_array = new List<uint> ();
version_id_array = new List<uint> ();
old_path_array = new StringCollection();
new_path_array = new StringCollection();
}
private void AddVersionToArrays ( uint photo_id, uint version_id, string old_path, string new_path)
{
photo_id_array.Add (photo_id);
version_id_array.Add (version_id);
old_path_array.Add (old_path);
new_path_array.Add (new_path);
}
private string CreateNewPath (string old_base, string new_base, PhotoVersion version)
{
return string.Format ("{0}{1}", new_base, version.Uri.AbsolutePath.Substring(old_base.Length));
}
private bool ChangeThisVersionUri (PhotoVersion version, string old_base, string new_base)
{
// Change to path from URI, since easier to compare with old_base which is not in URI format.
string tmp_path = System.IO.Path.GetDirectoryName (version.Uri.AbsolutePath);
return ( tmp_path.StartsWith (old_base) );
}
private void SearchVersionUriToChange (Photo photo, string old_base, string new_base)
{
foreach (uint version_id in photo.VersionIds) {
PhotoVersion version = photo.GetVersion (version_id) as PhotoVersion;
if ( ChangeThisVersionUri (version, old_base, new_base) )
AddVersionToArrays ( photo.Id,
version_id,
version.Uri.AbsolutePath,
CreateNewPath (old_base, new_base, version));
// else
// System.Console.WriteLine ("L : {0}", version.Uri.AbsolutePath);
}
}
public bool SearchUrisToChange (string old_base, string new_base)
{
int count = 0;
foreach ( IPhoto ibrows in photo_store.Query ( "SELECT * FROM photos " ) ) {
count++;
if (gui_controller.UpdateProgressBar ("Scanning through database", "Checking photo", total_photos))
return false;
SearchVersionUriToChange ((ibrows as Photo), old_base, new_base);
}
return true;
}
public bool StillOnSamePhotoId (int old_index, int current_index, List<uint> array)
{
try {
return (array[old_index] == array[current_index]);
} catch {
return true; // return true if out of index.
}
}
public void UpdateThisUri (int index, string path, ref Photo photo)
{
if (photo == null)
photo = photo_store.Get (photo_id_array[index]);
PhotoVersion version = photo.GetVersion ( (uint) version_id_array[index]) as PhotoVersion;
version.BaseUri = new SafeUri ( path ).GetBaseUri ();
version.Filename = new SafeUri ( path ).GetFilename ();
photo.Changes.UriChanged = true;
photo.Changes.ChangeVersion ( (uint) version_id_array[index] );
}
// FIXME: Refactor, try to use one common method....
public void RevertAllUris (int last_index)
{
gui_controller.remove_progress_dialog();
Photo photo = null;
for (int k = last_index; k >= 0; k--) {
if (gui_controller.UpdateProgressBar ("Reverting changes to database", "Reverting photo", last_index))
{} // do nothing, ignore trying to abort the revert...
if ( (photo != null) && !StillOnSamePhotoId (k+1, k, photo_id_array) ) {
photo_store.Commit (photo);
photo = null;
}
UpdateThisUri (k, old_path_array[k], ref photo);
Log.DebugFormat ("R : {0} - {1}", k, old_path_array[k]);
}
if (photo != null)
photo_store.Commit (photo);
Log.Debug ("Changing path failed due to above error. Have reverted any modification that took place.");
}
public ProcessResult ChangeAllUris ( ref int last_index)
{
gui_controller.remove_progress_dialog();
Photo photo = null;
last_index = 0;
try {
photo = null;
for (last_index = 0; last_index < photo_id_array.Count; last_index++) {
if (gui_controller.UpdateProgressBar ("Changing photos base path", "Changing photo", photo_id_array.Count)) {
Log.Debug("User aborted the change of paths...");
return ProcessResult.Cancelled;
}
if ( (photo != null) && !StillOnSamePhotoId (last_index-1, last_index, photo_id_array) ) {
photo_store.Commit (photo);
photo = null;
}
UpdateThisUri (last_index, new_path_array[last_index], ref photo);
Log.DebugFormat ("U : {0} - {1}", last_index, new_path_array[last_index]);
// DEBUG ONLY
// Cause an TEST exception on 6'th URI to be changed.
// float apa = last_index / (last_index-6);
}
if (photo != null)
photo_store.Commit (photo);
} catch (Exception e) {
Log.Exception(e);
return ProcessResult.Error;
}
return ProcessResult.Ok;
}
public ProcessResult ProcessArrays()
{
int last_index = 0;
ProcessResult tmp_res;
tmp_res = ChangeAllUris(ref last_index);
if (!(tmp_res == ProcessResult.Ok))
RevertAllUris(last_index);
return tmp_res;
}
/*
public void CheckIfUpdated (int test_index, StringCollection path_array)
{
Photo photo = photo_store.Get ( (uint) photo_id_array[test_index]) as Photo;
PhotoVersion version = photo.GetVersion ( (uint) version_id_array[test_index]) as PhotoVersion;
if (version.Uri.AbsolutePath.ToString() == path_array[ test_index ])
Log.DebugFormat ("Test URI ({0}) matches --- Should be finished", test_index);
else
Log.DebugFormat ("Test URI ({0}) DO NOT match --- Should NOT BE finished", test_index);
}
*/
/*
Check paths are different
If (Scan all photos) // user might cancel
If (Check there are photos on old path)
ChangePathsOnPhotos
*/
public bool NewOldPathSame (ref string newpath, ref string oldpath)
{
string p1 = EnsureEndsWithOneDirectorySeparator(newpath);
string p2 = EnsureEndsWithOneDirectorySeparator(oldpath);
return (p1 == p2);
}
public ProcessResult ChangePathOnPhotos (string old_base, string new_base)
{
ProcessResult tmp_res = ProcessResult.Processing;
InitializeArrays();
if (NewOldPathSame (ref new_base, ref old_base))
tmp_res = ProcessResult.SamePath;
if ( (tmp_res == ProcessResult.Processing) && (!SearchUrisToChange (old_base, new_base)) )
tmp_res = ProcessResult.Cancelled;
if ( (tmp_res == ProcessResult.Processing) && (photo_id_array.Count == 0) )
tmp_res = ProcessResult.NoPhotosFound;
if (tmp_res == ProcessResult.Processing)
tmp_res = ProcessArrays();
// if (res)
// CheckIfUpdated (photo_id_array.Count-1, new_path_array);
// else
// CheckIfUpdated (0, old_path_array);
return tmp_res;
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Data.Odbc
{
public sealed partial class OdbcCommand : System.Data.Common.DbCommand, System.ICloneable
{
public OdbcCommand() { }
public OdbcCommand(string cmdText) { }
public OdbcCommand(string cmdText, System.Data.Odbc.OdbcConnection connection) { }
public OdbcCommand(string cmdText, System.Data.Odbc.OdbcConnection connection, System.Data.Odbc.OdbcTransaction transaction) { }
public override string CommandText { get { throw null; } set { } }
public override int CommandTimeout { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(System.Data.CommandType.Text)]
public override System.Data.CommandType CommandType { get { throw null; } set { } }
public new System.Data.Odbc.OdbcConnection Connection { get { throw null; } set { } }
protected override System.Data.Common.DbConnection DbConnection { get { throw null; } set { } }
protected override System.Data.Common.DbParameterCollection DbParameterCollection { get { throw null; } }
protected override System.Data.Common.DbTransaction DbTransaction { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DefaultValueAttribute(true)]
[System.ComponentModel.DesignOnlyAttribute(true)]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool DesignTimeVisible { get { throw null; } set { } }
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
public new System.Data.Odbc.OdbcParameterCollection Parameters { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new System.Data.Odbc.OdbcTransaction Transaction { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(System.Data.UpdateRowSource.Both)]
public override System.Data.UpdateRowSource UpdatedRowSource { get { throw null; } set { } }
public override void Cancel() { }
protected override System.Data.Common.DbParameter CreateDbParameter() { throw null; }
public new System.Data.Odbc.OdbcParameter CreateParameter() { throw null; }
protected override void Dispose(bool disposing) { }
protected override System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior) { throw null; }
public override int ExecuteNonQuery() { throw null; }
public new System.Data.Odbc.OdbcDataReader ExecuteReader() { throw null; }
public new System.Data.Odbc.OdbcDataReader ExecuteReader(System.Data.CommandBehavior behavior) { throw null; }
public override object ExecuteScalar() { throw null; }
public override void Prepare() { }
public void ResetCommandTimeout() { }
object System.ICloneable.Clone() { throw null; }
}
public sealed partial class OdbcCommandBuilder : System.Data.Common.DbCommandBuilder
{
public OdbcCommandBuilder() { }
public OdbcCommandBuilder(System.Data.Odbc.OdbcDataAdapter adapter) { }
public new System.Data.Odbc.OdbcDataAdapter DataAdapter { get { throw null; } set { } }
protected override void ApplyParameterInfo(System.Data.Common.DbParameter parameter, System.Data.DataRow datarow, System.Data.StatementType statementType, bool whereClause) { }
public static void DeriveParameters(System.Data.Odbc.OdbcCommand command) { }
public new System.Data.Odbc.OdbcCommand GetDeleteCommand() { throw null; }
public new System.Data.Odbc.OdbcCommand GetDeleteCommand(bool useColumnsForParameterNames) { throw null; }
public new System.Data.Odbc.OdbcCommand GetInsertCommand() { throw null; }
public new System.Data.Odbc.OdbcCommand GetInsertCommand(bool useColumnsForParameterNames) { throw null; }
protected override string GetParameterName(int parameterOrdinal) { throw null; }
protected override string GetParameterName(string parameterName) { throw null; }
protected override string GetParameterPlaceholder(int parameterOrdinal) { throw null; }
public new System.Data.Odbc.OdbcCommand GetUpdateCommand() { throw null; }
public new System.Data.Odbc.OdbcCommand GetUpdateCommand(bool useColumnsForParameterNames) { throw null; }
public override string QuoteIdentifier(string unquotedIdentifier) { throw null; }
public string QuoteIdentifier(string unquotedIdentifier, System.Data.Odbc.OdbcConnection connection) { throw null; }
protected override void SetRowUpdatingHandler(System.Data.Common.DbDataAdapter adapter) { }
public override string UnquoteIdentifier(string quotedIdentifier) { throw null; }
public string UnquoteIdentifier(string quotedIdentifier, System.Data.Odbc.OdbcConnection connection) { throw null; }
}
public sealed partial class OdbcConnection : System.Data.Common.DbConnection, System.ICloneable
{
public OdbcConnection() { }
public OdbcConnection(string connectionString) { }
public override string ConnectionString { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(15)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new int ConnectionTimeout { get { throw null; } set { } }
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public override string Database { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public override string DataSource { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public string Driver { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public override string ServerVersion { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public override System.Data.ConnectionState State { get { throw null; } }
public event System.Data.Odbc.OdbcInfoMessageEventHandler InfoMessage { add { } remove { } }
protected override System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { throw null; }
public new System.Data.Odbc.OdbcTransaction BeginTransaction() { throw null; }
public new System.Data.Odbc.OdbcTransaction BeginTransaction(System.Data.IsolationLevel isolevel) { throw null; }
public override void ChangeDatabase(string value) { }
public override void Close() { }
public new System.Data.Odbc.OdbcCommand CreateCommand() { throw null; }
protected override System.Data.Common.DbCommand CreateDbCommand() { throw null; }
protected override void Dispose(bool disposing) { }
public override void Open() { }
public static void ReleaseObjectPool() { }
object System.ICloneable.Clone() { throw null; }
}
public sealed partial class OdbcConnectionStringBuilder : System.Data.Common.DbConnectionStringBuilder
{
public OdbcConnectionStringBuilder() { }
public OdbcConnectionStringBuilder(string connectionString) { }
[System.ComponentModel.DisplayNameAttribute("Driver")]
public string Driver { get { throw null; } set { } }
[System.ComponentModel.DisplayNameAttribute("Dsn")]
public string Dsn { get { throw null; } set { } }
public override object this[string keyword] { get { throw null; } set { } }
public override System.Collections.ICollection Keys { get { throw null; } }
public override void Clear() { }
public override bool ContainsKey(string keyword) { throw null; }
public override bool Remove(string keyword) { throw null; }
public override bool TryGetValue(string keyword, out object value) { throw null; }
}
public sealed partial class OdbcDataAdapter : System.Data.Common.DbDataAdapter, System.Data.IDataAdapter, System.Data.IDbDataAdapter, System.ICloneable
{
public OdbcDataAdapter() { }
public OdbcDataAdapter(System.Data.Odbc.OdbcCommand selectCommand) { }
public OdbcDataAdapter(string selectCommandText, System.Data.Odbc.OdbcConnection selectConnection) { }
public OdbcDataAdapter(string selectCommandText, string selectConnectionString) { }
public new System.Data.Odbc.OdbcCommand DeleteCommand { get { throw null; } set { } }
public new System.Data.Odbc.OdbcCommand InsertCommand { get { throw null; } set { } }
public new System.Data.Odbc.OdbcCommand SelectCommand { get { throw null; } set { } }
System.Data.IDbCommand System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } }
System.Data.IDbCommand System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } }
System.Data.IDbCommand System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } }
System.Data.IDbCommand System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } }
public new System.Data.Odbc.OdbcCommand UpdateCommand { get { throw null; } set { } }
public event System.Data.Odbc.OdbcRowUpdatedEventHandler RowUpdated { add { } remove { } }
public event System.Data.Odbc.OdbcRowUpdatingEventHandler RowUpdating { add { } remove { } }
protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; }
protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; }
protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value) { }
protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value) { }
object System.ICloneable.Clone() { throw null; }
}
public sealed partial class OdbcDataReader : System.Data.Common.DbDataReader
{
internal OdbcDataReader() { }
public override int Depth { get { throw null; } }
public override int FieldCount { get { throw null; } }
public override bool HasRows { get { throw null; } }
public override bool IsClosed { get { throw null; } }
public override object this[int i] { get { throw null; } }
public override object this[string value] { get { throw null; } }
public override int RecordsAffected { get { throw null; } }
public override void Close() { }
protected override void Dispose(bool disposing) { }
public override bool GetBoolean(int i) { throw null; }
public override byte GetByte(int i) { throw null; }
public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw null; }
public override char GetChar(int i) { throw null; }
public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) { throw null; }
public override string GetDataTypeName(int i) { throw null; }
public System.DateTime GetDate(int i) { throw null; }
public override System.DateTime GetDateTime(int i) { throw null; }
public override decimal GetDecimal(int i) { throw null; }
public override double GetDouble(int i) { throw null; }
public override System.Collections.IEnumerator GetEnumerator() { throw null; }
public override System.Type GetFieldType(int i) { throw null; }
public override float GetFloat(int i) { throw null; }
public override System.Guid GetGuid(int i) { throw null; }
public override short GetInt16(int i) { throw null; }
public override int GetInt32(int i) { throw null; }
public override long GetInt64(int i) { throw null; }
public override string GetName(int i) { throw null; }
public override int GetOrdinal(string value) { throw null; }
public override System.Data.DataTable GetSchemaTable() { throw null; }
public override string GetString(int i) { throw null; }
public System.TimeSpan GetTime(int i) { throw null; }
public override object GetValue(int i) { throw null; }
public override int GetValues(object[] values) { throw null; }
public override bool IsDBNull(int i) { throw null; }
public override bool NextResult() { throw null; }
public override bool Read() { throw null; }
}
public sealed partial class OdbcError
{
internal OdbcError() { }
public string Message { get { throw null; } }
public int NativeError { get { throw null; } }
public string Source { get { throw null; } }
public string SQLState { get { throw null; } }
public override string ToString() { throw null; }
}
public sealed partial class OdbcErrorCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal OdbcErrorCollection() { }
public int Count { get { throw null; } }
public System.Data.Odbc.OdbcError this[int i] { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int i) { }
public void CopyTo(System.Data.Odbc.OdbcError[] array, int i) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
}
public sealed partial class OdbcException : System.Data.Common.DbException
{
internal OdbcException() { }
public System.Data.Odbc.OdbcErrorCollection Errors { get { throw null; } }
public override string Source { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { }
}
public sealed partial class OdbcFactory : System.Data.Common.DbProviderFactory
{
internal OdbcFactory() { }
public static readonly System.Data.Odbc.OdbcFactory Instance;
public override System.Data.Common.DbCommand CreateCommand() { throw null; }
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder() { throw null; }
public override System.Data.Common.DbConnection CreateConnection() { throw null; }
public override System.Data.Common.DbConnectionStringBuilder CreateConnectionStringBuilder() { throw null; }
public override System.Data.Common.DbDataAdapter CreateDataAdapter() { throw null; }
public override System.Data.Common.DbParameter CreateParameter() { throw null; }
}
public sealed partial class OdbcInfoMessageEventArgs : System.EventArgs
{
internal OdbcInfoMessageEventArgs() { }
public System.Data.Odbc.OdbcErrorCollection Errors { get { throw null; } }
public string Message { get { throw null; } }
public override string ToString() { throw null; }
}
public delegate void OdbcInfoMessageEventHandler(object sender, System.Data.Odbc.OdbcInfoMessageEventArgs e);
public static partial class OdbcMetaDataCollectionNames
{
public static readonly string Columns;
public static readonly string Indexes;
public static readonly string ProcedureColumns;
public static readonly string ProcedureParameters;
public static readonly string Procedures;
public static readonly string Tables;
public static readonly string Views;
}
public static partial class OdbcMetaDataColumnNames
{
public static readonly string BooleanFalseLiteral;
public static readonly string BooleanTrueLiteral;
public static readonly string SQLType;
}
public sealed partial class OdbcParameter : System.Data.Common.DbParameter, System.Data.IDataParameter, System.Data.IDbDataParameter, System.ICloneable
{
public OdbcParameter() { }
public OdbcParameter(string name, System.Data.Odbc.OdbcType type) { }
public OdbcParameter(string name, System.Data.Odbc.OdbcType type, int size) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public OdbcParameter(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, System.Data.ParameterDirection parameterDirection, bool isNullable, byte precision, byte scale, string srcColumn, System.Data.DataRowVersion srcVersion, object value) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public OdbcParameter(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, System.Data.ParameterDirection parameterDirection, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value) { }
public OdbcParameter(string name, System.Data.Odbc.OdbcType type, int size, string sourcecolumn) { }
public OdbcParameter(string name, object value) { }
public override System.Data.DbType DbType { get { throw null; } set { } }
public override System.Data.ParameterDirection Direction { get { throw null; } set { } }
public override bool IsNullable { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(System.Data.Odbc.OdbcType.NChar)]
[System.Data.Common.DbProviderSpecificTypePropertyAttribute(true)]
public System.Data.Odbc.OdbcType OdbcType { get { throw null; } set { } }
public override string ParameterName { get { throw null; } set { } }
public new byte Precision { get { throw null; } set { } }
public new byte Scale { get { throw null; } set { } }
public override int Size { get { throw null; } set { } }
public override string SourceColumn { get { throw null; } set { } }
public override bool SourceColumnNullMapping { get { throw null; } set { } }
public override System.Data.DataRowVersion SourceVersion { get { throw null; } set { } }
public override object Value { get { throw null; } set { } }
public override void ResetDbType() { }
public void ResetOdbcType() { }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
}
public sealed partial class OdbcParameterCollection : System.Data.Common.DbParameterCollection
{
internal OdbcParameterCollection() { }
public override int Count { get { throw null; } }
public override bool IsFixedSize { get { throw null; } }
public override bool IsReadOnly { get { throw null; } }
public override bool IsSynchronized { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new System.Data.Odbc.OdbcParameter this[int index] { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new System.Data.Odbc.OdbcParameter this[string parameterName] { get { throw null; } set { } }
public override object SyncRoot { get { throw null; } }
public System.Data.Odbc.OdbcParameter Add(System.Data.Odbc.OdbcParameter value) { throw null; }
public override int Add(object value) { throw null; }
public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType) { throw null; }
public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType, int size) { throw null; }
public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, string sourceColumn) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value). https://go.microsoft.com/fwlink/?linkid=14202", false)]
public System.Data.Odbc.OdbcParameter Add(string parameterName, object value) { throw null; }
public override void AddRange(System.Array values) { }
public void AddRange(System.Data.Odbc.OdbcParameter[] values) { }
public System.Data.Odbc.OdbcParameter AddWithValue(string parameterName, object value) { throw null; }
public override void Clear() { }
public bool Contains(System.Data.Odbc.OdbcParameter value) { throw null; }
public override bool Contains(object value) { throw null; }
public override bool Contains(string value) { throw null; }
public override void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Data.Odbc.OdbcParameter[] array, int index) { }
public override System.Collections.IEnumerator GetEnumerator() { throw null; }
protected override System.Data.Common.DbParameter GetParameter(int index) { throw null; }
protected override System.Data.Common.DbParameter GetParameter(string parameterName) { throw null; }
public int IndexOf(System.Data.Odbc.OdbcParameter value) { throw null; }
public override int IndexOf(object value) { throw null; }
public override int IndexOf(string parameterName) { throw null; }
public void Insert(int index, System.Data.Odbc.OdbcParameter value) { }
public override void Insert(int index, object value) { }
public void Remove(System.Data.Odbc.OdbcParameter value) { }
public override void Remove(object value) { }
public override void RemoveAt(int index) { }
public override void RemoveAt(string parameterName) { }
protected override void SetParameter(int index, System.Data.Common.DbParameter value) { }
protected override void SetParameter(string parameterName, System.Data.Common.DbParameter value) { }
}
public sealed partial class OdbcRowUpdatedEventArgs : System.Data.Common.RowUpdatedEventArgs
{
public OdbcRowUpdatedEventArgs(System.Data.DataRow row, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { }
public new System.Data.Odbc.OdbcCommand Command { get { throw null; } }
}
public delegate void OdbcRowUpdatedEventHandler(object sender, System.Data.Odbc.OdbcRowUpdatedEventArgs e);
public sealed partial class OdbcRowUpdatingEventArgs : System.Data.Common.RowUpdatingEventArgs
{
public OdbcRowUpdatingEventArgs(System.Data.DataRow row, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { }
protected override System.Data.IDbCommand BaseCommand { get { throw null; } set { } }
public new System.Data.Odbc.OdbcCommand Command { get { throw null; } set { } }
}
public delegate void OdbcRowUpdatingEventHandler(object sender, System.Data.Odbc.OdbcRowUpdatingEventArgs e);
public sealed partial class OdbcTransaction : System.Data.Common.DbTransaction
{
internal OdbcTransaction() { }
public new System.Data.Odbc.OdbcConnection Connection { get { throw null; } }
protected override System.Data.Common.DbConnection DbConnection { get { throw null; } }
public override System.Data.IsolationLevel IsolationLevel { get { throw null; } }
public override void Commit() { }
protected override void Dispose(bool disposing) { }
public override void Rollback() { }
}
public enum OdbcType
{
BigInt = 1,
Binary = 2,
Bit = 3,
Char = 4,
DateTime = 5,
Decimal = 6,
Numeric = 7,
Double = 8,
Image = 9,
Int = 10,
NChar = 11,
NText = 12,
NVarChar = 13,
Real = 14,
UniqueIdentifier = 15,
SmallDateTime = 16,
SmallInt = 17,
Text = 18,
Timestamp = 19,
TinyInt = 20,
VarBinary = 21,
VarChar = 22,
Date = 23,
Time = 24,
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// WebhookResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Chat.V2.Service.Channel
{
public class WebhookResource : Resource
{
public sealed class TypeEnum : StringEnum
{
private TypeEnum(string value) : base(value) {}
public TypeEnum() {}
public static implicit operator TypeEnum(string value)
{
return new TypeEnum(value);
}
public static readonly TypeEnum Webhook = new TypeEnum("webhook");
public static readonly TypeEnum Trigger = new TypeEnum("trigger");
public static readonly TypeEnum Studio = new TypeEnum("studio");
}
public sealed class MethodEnum : StringEnum
{
private MethodEnum(string value) : base(value) {}
public MethodEnum() {}
public static implicit operator MethodEnum(string value)
{
return new MethodEnum(value);
}
public static readonly MethodEnum Get = new MethodEnum("GET");
public static readonly MethodEnum Post = new MethodEnum("POST");
}
private static Request BuildReadRequest(ReadWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Webhooks",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static ResourceSet<WebhookResource> Read(ReadWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<WebhookResource>.FromJson("webhooks", response.Content);
return new ResourceSet<WebhookResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WebhookResource>> ReadAsync(ReadWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<WebhookResource>.FromJson("webhooks", response.Content);
return new ResourceSet<WebhookResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resources to read belong to </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static ResourceSet<WebhookResource> Read(string pathServiceSid,
string pathChannelSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWebhookOptions(pathServiceSid, pathChannelSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resources to read belong to </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WebhookResource>> ReadAsync(string pathServiceSid,
string pathChannelSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWebhookOptions(pathServiceSid, pathChannelSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<WebhookResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<WebhookResource>.FromJson("webhooks", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<WebhookResource> NextPage(Page<WebhookResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<WebhookResource>.FromJson("webhooks", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<WebhookResource> PreviousPage(Page<WebhookResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<WebhookResource>.FromJson("webhooks", response.Content);
}
private static Request BuildFetchRequest(FetchWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Webhooks/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Fetch(FetchWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> FetchAsync(FetchWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service with the Channel to fetch the Webhook resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resource to fetch belongs to </param>
/// <param name="pathSid"> The SID of the Channel Webhook resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Fetch(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchWebhookOptions(pathServiceSid, pathChannelSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service with the Channel to fetch the Webhook resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resource to fetch belongs to </param>
/// <param name="pathSid"> The SID of the Channel Webhook resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> FetchAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchWebhookOptions(pathServiceSid, pathChannelSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Webhooks",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Create(CreateWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> CreateAsync(CreateWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service with the Channel to create the resource under </param>
/// <param name="pathChannelSid"> The SID of the Channel the new resource belongs to </param>
/// <param name="type"> The type of webhook </param>
/// <param name="configurationUrl"> The URL of the webhook to call </param>
/// <param name="configurationMethod"> The HTTP method used to call `configuration.url` </param>
/// <param name="configurationFilters"> The events that cause us to call the Channel Webhook </param>
/// <param name="configurationTriggers"> A string that will cause us to call the webhook when it is found in a message
/// body </param>
/// <param name="configurationFlowSid"> The SID of the Studio Flow to call when an event occurs </param>
/// <param name="configurationRetryCount"> The number of times to retry the webhook if the first attempt fails </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Create(string pathServiceSid,
string pathChannelSid,
WebhookResource.TypeEnum type,
string configurationUrl = null,
WebhookResource.MethodEnum configurationMethod = null,
List<string> configurationFilters = null,
List<string> configurationTriggers = null,
string configurationFlowSid = null,
int? configurationRetryCount = null,
ITwilioRestClient client = null)
{
var options = new CreateWebhookOptions(pathServiceSid, pathChannelSid, type){ConfigurationUrl = configurationUrl, ConfigurationMethod = configurationMethod, ConfigurationFilters = configurationFilters, ConfigurationTriggers = configurationTriggers, ConfigurationFlowSid = configurationFlowSid, ConfigurationRetryCount = configurationRetryCount};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service with the Channel to create the resource under </param>
/// <param name="pathChannelSid"> The SID of the Channel the new resource belongs to </param>
/// <param name="type"> The type of webhook </param>
/// <param name="configurationUrl"> The URL of the webhook to call </param>
/// <param name="configurationMethod"> The HTTP method used to call `configuration.url` </param>
/// <param name="configurationFilters"> The events that cause us to call the Channel Webhook </param>
/// <param name="configurationTriggers"> A string that will cause us to call the webhook when it is found in a message
/// body </param>
/// <param name="configurationFlowSid"> The SID of the Studio Flow to call when an event occurs </param>
/// <param name="configurationRetryCount"> The number of times to retry the webhook if the first attempt fails </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> CreateAsync(string pathServiceSid,
string pathChannelSid,
WebhookResource.TypeEnum type,
string configurationUrl = null,
WebhookResource.MethodEnum configurationMethod = null,
List<string> configurationFilters = null,
List<string> configurationTriggers = null,
string configurationFlowSid = null,
int? configurationRetryCount = null,
ITwilioRestClient client = null)
{
var options = new CreateWebhookOptions(pathServiceSid, pathChannelSid, type){ConfigurationUrl = configurationUrl, ConfigurationMethod = configurationMethod, ConfigurationFilters = configurationFilters, ConfigurationTriggers = configurationTriggers, ConfigurationFlowSid = configurationFlowSid, ConfigurationRetryCount = configurationRetryCount};
return await CreateAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Webhooks/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Update(UpdateWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> UpdateAsync(UpdateWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service with the Channel that has the Webhook resource to update
/// </param>
/// <param name="pathChannelSid"> The SID of the Channel the resource to update belongs to </param>
/// <param name="pathSid"> The SID of the resource </param>
/// <param name="configurationUrl"> The URL of the webhook to call </param>
/// <param name="configurationMethod"> The HTTP method used to call `configuration.url` </param>
/// <param name="configurationFilters"> The events that cause us to call the Channel Webhook </param>
/// <param name="configurationTriggers"> A string that will cause us to call the webhook when it is found in a message
/// body </param>
/// <param name="configurationFlowSid"> The SID of the Studio Flow to call when an event occurs </param>
/// <param name="configurationRetryCount"> The number of times to retry the webhook if the first attempt fails </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Update(string pathServiceSid,
string pathChannelSid,
string pathSid,
string configurationUrl = null,
WebhookResource.MethodEnum configurationMethod = null,
List<string> configurationFilters = null,
List<string> configurationTriggers = null,
string configurationFlowSid = null,
int? configurationRetryCount = null,
ITwilioRestClient client = null)
{
var options = new UpdateWebhookOptions(pathServiceSid, pathChannelSid, pathSid){ConfigurationUrl = configurationUrl, ConfigurationMethod = configurationMethod, ConfigurationFilters = configurationFilters, ConfigurationTriggers = configurationTriggers, ConfigurationFlowSid = configurationFlowSid, ConfigurationRetryCount = configurationRetryCount};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service with the Channel that has the Webhook resource to update
/// </param>
/// <param name="pathChannelSid"> The SID of the Channel the resource to update belongs to </param>
/// <param name="pathSid"> The SID of the resource </param>
/// <param name="configurationUrl"> The URL of the webhook to call </param>
/// <param name="configurationMethod"> The HTTP method used to call `configuration.url` </param>
/// <param name="configurationFilters"> The events that cause us to call the Channel Webhook </param>
/// <param name="configurationTriggers"> A string that will cause us to call the webhook when it is found in a message
/// body </param>
/// <param name="configurationFlowSid"> The SID of the Studio Flow to call when an event occurs </param>
/// <param name="configurationRetryCount"> The number of times to retry the webhook if the first attempt fails </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> UpdateAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
string configurationUrl = null,
WebhookResource.MethodEnum configurationMethod = null,
List<string> configurationFilters = null,
List<string> configurationTriggers = null,
string configurationFlowSid = null,
int? configurationRetryCount = null,
ITwilioRestClient client = null)
{
var options = new UpdateWebhookOptions(pathServiceSid, pathChannelSid, pathSid){ConfigurationUrl = configurationUrl, ConfigurationMethod = configurationMethod, ConfigurationFilters = configurationFilters, ConfigurationTriggers = configurationTriggers, ConfigurationFlowSid = configurationFlowSid, ConfigurationRetryCount = configurationRetryCount};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Webhooks/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static bool Delete(DeleteWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service with the Channel to delete the Webhook resource from </param>
/// <param name="pathChannelSid"> The SID of the channel the resource to delete belongs to </param>
/// <param name="pathSid"> The SID of the Channel Webhook resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static bool Delete(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteWebhookOptions(pathServiceSid, pathChannelSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service with the Channel to delete the Webhook resource from </param>
/// <param name="pathChannelSid"> The SID of the channel the resource to delete belongs to </param>
/// <param name="pathSid"> The SID of the Channel Webhook resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteWebhookOptions(pathServiceSid, pathChannelSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a WebhookResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> WebhookResource object represented by the provided JSON </returns>
public static WebhookResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<WebhookResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Service that the Channel Webhook resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The SID of the Channel the Channel Webhook resource belongs to
/// </summary>
[JsonProperty("channel_sid")]
public string ChannelSid { get; private set; }
/// <summary>
/// The type of webhook
/// </summary>
[JsonProperty("type")]
public string Type { get; private set; }
/// <summary>
/// The absolute URL of the Channel Webhook resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The JSON string that describes the configuration object for the channel webhook
/// </summary>
[JsonProperty("configuration")]
public object Configuration { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
private WebhookResource()
{
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// Parse(System.String,System.Globalization.NumberStyles,System.IFormatProvider)
/// </summary>
public class DecimalParse3
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negitive]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Calling Parse method.");
try
{
Decimal m1 = new decimal(TestLibrary.Generator.GetDouble(-55));
CultureInfo myCulture = CultureInfo.InvariantCulture;
string m1ToString = m1.ToString(myCulture);
Decimal expectValue = m1;
retVal = VerifyHelper(m1, m1ToString, NumberStyles.AllowDecimalPoint, "001.1") & retVal;
retVal = VerifyHelper(m1, m1ToString, NumberStyles.Any, "001.2") & retVal;
retVal = VerifyHelper(m1, m1ToString, NumberStyles.Currency, "001.3") & retVal;
retVal = VerifyHelper(m1, m1ToString, NumberStyles.Float, "001.4") & retVal;
retVal = VerifyHelper(m1, m1ToString, NumberStyles.Number, "001.5") & retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Calling Parse method and the decimal is MaxValue and MinValue.");
try
{
Decimal m1 = Decimal.MaxValue;
CultureInfo myCulture = CultureInfo.CurrentCulture;
string m1ToString = m1.ToString(myCulture);
Decimal expectValue = m1;
Decimal actualValue = Decimal.Parse(m1ToString, NumberStyles.Any, myCulture);
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("002.1", "Parse method should return " + expectValue);
retVal = false;
}
m1 = Decimal.MinValue;
m1ToString = m1.ToString(myCulture);
expectValue = m1;
actualValue = Decimal.Parse(m1ToString,NumberStyles.Any);
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("002.2", "Parse method should return " + expectValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Calling Parse method and the decimal is Especial value.");
try
{
Decimal m1 = -9876543210.9876543210m;
CultureInfo myCulture = CultureInfo.CurrentCulture;
string m1ToString = m1.ToString(myCulture);
Decimal expectValue = m1;
Decimal actualValue = Decimal.Parse(m1ToString, NumberStyles.Any, myCulture);
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("003.1", "Parse method should return " + expectValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Negitive test
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: s is a null reference.");
try
{
string m1ToString = null;
CultureInfo myCluture = CultureInfo.InvariantCulture;
Decimal actualValue = Decimal.Parse(m1ToString, NumberStyles.Any, myCluture);
TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException should be caught." );
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: s is not in the correct format.");
try
{
string m1ToString = "ADAAAW";
CultureInfo myCluture = CultureInfo.InvariantCulture;
Decimal actualValue = Decimal.Parse(m1ToString, NumberStyles.Any, myCluture);
TestLibrary.TestFramework.LogError("102.1", "FormatException should be caught.");
retVal = false;
}
catch (FormatException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: s represents a number greater than MaxValue.");
try
{
Decimal myDecimal = decimal.MaxValue;
CultureInfo myCulture = CultureInfo.CurrentCulture;
string m1ToString = myDecimal.ToString(myCulture);
m1ToString = m1ToString + m1ToString;
Decimal actualValue = Decimal.Parse(m1ToString, NumberStyles.Any, myCulture);
TestLibrary.TestFramework.LogError("103.1", "OverflowException should be caught.");
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: s represents a number less than MinValue.");
try
{
Decimal myDecimal = decimal.MinValue;
CultureInfo myCulture = CultureInfo.CurrentCulture;
string m1ToString = myDecimal.ToString(myCulture);
m1ToString = m1ToString + Decimal.Negate(myDecimal).ToString(myCulture);
Decimal actualValue = Decimal.Parse(m1ToString, NumberStyles.Any, myCulture);
TestLibrary.TestFramework.LogError("104.1", "OverflowException should be caught.");
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: not support NumberStyles .");
try
{
Decimal m1 = new decimal(TestLibrary.Generator.GetDouble(-55));
CultureInfo myCulture = CultureInfo.InvariantCulture;
string m1ToString = m1.ToString(myCulture);
Decimal expectValue = m1;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.AllowCurrencySymbol, "105.1") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.AllowExponent, "105.2") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.AllowLeadingSign, "105.4") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.AllowLeadingWhite, "105.5") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.AllowParentheses, "105.6") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.AllowThousands, "105.7") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.AllowTrailingSign, "105.8") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.AllowTrailingWhite, "105.9") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.Integer, "105.11") & retVal;
retVal = VerifyNegHelper(m1, m1ToString, NumberStyles.None, "105.12") & retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: style is the AllowHexSpecifier value.");
try
{
Decimal m1 = new decimal(TestLibrary.Generator.GetDouble(-55));
CultureInfo myCulture = CultureInfo.InvariantCulture;
string m1ToString = m1.ToString(myCulture);
Decimal expectValue = m1;
retVal = VerifyNegHexHelper(m1, m1ToString, NumberStyles.AllowHexSpecifier, "106.1") & retVal;
retVal = VerifyNegHexHelper(m1, m1ToString, NumberStyles.HexNumber, "106.2") & retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: style is not a NumberStyles value.");
try
{
Decimal m1 = new decimal(TestLibrary.Generator.GetDouble(-55));
CultureInfo myCulture = CultureInfo.InvariantCulture;
string m1ToString = m1.ToString(myCulture);
Decimal expectValue = m1;
retVal = VerifyNegHexHelper(m1, m1ToString,(NumberStyles)9999, "107.1") & retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
DecimalParse3 test = new DecimalParse3();
TestLibrary.TestFramework.BeginTestCase("DecimalParse3");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region private method
private bool VerifyHelper(Decimal expectValue, string testValue, NumberStyles myNumberStyles, string errorno)
{
bool retVal = true;
try
{
CultureInfo myCluture = CultureInfo.InvariantCulture;
Decimal actualValue = Decimal.Parse(testValue, myNumberStyles, myCluture);
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError(errorno, "Parse should return " + expectValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError(errorno + ".0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
private bool VerifyNegHelper(Decimal expectValue, string testValue, NumberStyles myNumberStyles, string errorno)
{
bool retVal = true;
try
{
CultureInfo myCluture = CultureInfo.InvariantCulture;
Decimal actualValue = Decimal.Parse(testValue, myNumberStyles, myCluture);
TestLibrary.TestFramework.LogError(errorno, "FormatException should be caught.");
retVal = false;
}
catch (FormatException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError(errorno + ".0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
private bool VerifyNegHexHelper(Decimal expectValue, string testValue, NumberStyles myNumberStyles, string errorno)
{
bool retVal = true;
try
{
CultureInfo myCluture = CultureInfo.InvariantCulture;
Decimal actualValue = Decimal.Parse(testValue, myNumberStyles, myCluture);
TestLibrary.TestFramework.LogError(errorno, "ArgumentException should be caught.");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError(errorno + ".0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
namespace Avalonia.Input
{
/// <summary>
/// Defines the keys available on a keyboard.
/// </summary>
public enum Key
{
/// <summary>
/// No key pressed.
/// </summary>
None = 0,
/// <summary>
/// The Cancel key.
/// </summary>
Cancel = 1,
/// <summary>
/// The Back key.
/// </summary>
Back = 2,
/// <summary>
/// The Tab key.
/// </summary>
Tab = 3,
/// <summary>
/// The Linefeed key.
/// </summary>
LineFeed = 4,
/// <summary>
/// The Clear key.
/// </summary>
Clear = 5,
/// <summary>
/// The Return key.
/// </summary>
Return = 6,
/// <summary>
/// The Enter key.
/// </summary>
Enter = 6,
/// <summary>
/// The Pause key.
/// </summary>
Pause = 7,
/// <summary>
/// The Caps Lock key.
/// </summary>
CapsLock = 8,
/// <summary>
/// The Caps Lock key.
/// </summary>
Capital = 8,
/// <summary>
/// The IME Hangul mode key.
/// </summary>
HangulMode = 9,
/// <summary>
/// The IME Kana mode key.
/// </summary>
KanaMode = 9,
/// <summary>
/// The IME Janja mode key.
/// </summary>
JunjaMode = 10,
/// <summary>
/// The IME Final mode key.
/// </summary>
FinalMode = 11,
/// <summary>
/// The IME Kanji mode key.
/// </summary>
KanjiMode = 12,
/// <summary>
/// The IME Hanja mode key.
/// </summary>
HanjaMode = 12,
/// <summary>
/// The Escape key.
/// </summary>
Escape = 13,
/// <summary>
/// The IME Convert key.
/// </summary>
ImeConvert = 14,
/// <summary>
/// The IME NonConvert key.
/// </summary>
ImeNonConvert = 15,
/// <summary>
/// The IME Accept key.
/// </summary>
ImeAccept = 16,
/// <summary>
/// The IME Mode change key.
/// </summary>
ImeModeChange = 17,
/// <summary>
/// The space bar.
/// </summary>
Space = 18,
/// <summary>
/// The Page Up key.
/// </summary>
PageUp = 19,
/// <summary>
/// The Page Up key.
/// </summary>
Prior = 19,
/// <summary>
/// The Page Down key.
/// </summary>
PageDown = 20,
/// <summary>
/// The Page Down key.
/// </summary>
Next = 20,
/// <summary>
/// The End key.
/// </summary>
End = 21,
/// <summary>
/// The Home key.
/// </summary>
Home = 22,
/// <summary>
/// The Left arrow key.
/// </summary>
Left = 23,
/// <summary>
/// The Up arrow key.
/// </summary>
Up = 24,
/// <summary>
/// The Right arrow key.
/// </summary>
Right = 25,
/// <summary>
/// The Down arrow key.
/// </summary>
Down = 26,
/// <summary>
/// The Select key.
/// </summary>
Select = 27,
/// <summary>
/// The Print key.
/// </summary>
Print = 28,
/// <summary>
/// The Execute key.
/// </summary>
Execute = 29,
/// <summary>
/// The Print Screen key.
/// </summary>
Snapshot = 30,
/// <summary>
/// The Print Screen key.
/// </summary>
PrintScreen = 30,
/// <summary>
/// The Insert key.
/// </summary>
Insert = 31,
/// <summary>
/// The Delete key.
/// </summary>
Delete = 32,
/// <summary>
/// The Help key.
/// </summary>
Help = 33,
/// <summary>
/// The 0 key.
/// </summary>
D0 = 34,
/// <summary>
/// The 1 key.
/// </summary>
D1 = 35,
/// <summary>
/// The 2 key.
/// </summary>
D2 = 36,
/// <summary>
/// The 3 key.
/// </summary>
D3 = 37,
/// <summary>
/// The 4 key.
/// </summary>
D4 = 38,
/// <summary>
/// The 5 key.
/// </summary>
D5 = 39,
/// <summary>
/// The 6 key.
/// </summary>
D6 = 40,
/// <summary>
/// The 7 key.
/// </summary>
D7 = 41,
/// <summary>
/// The 8 key.
/// </summary>
D8 = 42,
/// <summary>
/// The 9 key.
/// </summary>
D9 = 43,
/// <summary>
/// The A key.
/// </summary>
A = 44,
/// <summary>
/// The B key.
/// </summary>
B = 45,
/// <summary>
/// The C key.
/// </summary>
C = 46,
/// <summary>
/// The D key.
/// </summary>
D = 47,
/// <summary>
/// The E key.
/// </summary>
E = 48,
/// <summary>
/// The F key.
/// </summary>
F = 49,
/// <summary>
/// The G key.
/// </summary>
G = 50,
/// <summary>
/// The H key.
/// </summary>
H = 51,
/// <summary>
/// The I key.
/// </summary>
I = 52,
/// <summary>
/// The J key.
/// </summary>
J = 53,
/// <summary>
/// The K key.
/// </summary>
K = 54,
/// <summary>
/// The L key.
/// </summary>
L = 55,
/// <summary>
/// The M key.
/// </summary>
M = 56,
/// <summary>
/// The N key.
/// </summary>
N = 57,
/// <summary>
/// The O key.
/// </summary>
O = 58,
/// <summary>
/// The P key.
/// </summary>
P = 59,
/// <summary>
/// The Q key.
/// </summary>
Q = 60,
/// <summary>
/// The R key.
/// </summary>
R = 61,
/// <summary>
/// The S key.
/// </summary>
S = 62,
/// <summary>
/// The T key.
/// </summary>
T = 63,
/// <summary>
/// The U key.
/// </summary>
U = 64,
/// <summary>
/// The V key.
/// </summary>
V = 65,
/// <summary>
/// The W key.
/// </summary>
W = 66,
/// <summary>
/// The X key.
/// </summary>
X = 67,
/// <summary>
/// The Y key.
/// </summary>
Y = 68,
/// <summary>
/// The Z key.
/// </summary>
Z = 69,
/// <summary>
/// The left Windows key.
/// </summary>
LWin = 70,
/// <summary>
/// The right Windows key.
/// </summary>
RWin = 71,
/// <summary>
/// The Application key.
/// </summary>
Apps = 72,
/// <summary>
/// The Sleep key.
/// </summary>
Sleep = 73,
/// <summary>
/// The 0 key on the numeric keypad.
/// </summary>
NumPad0 = 74,
/// <summary>
/// The 1 key on the numeric keypad.
/// </summary>
NumPad1 = 75,
/// <summary>
/// The 2 key on the numeric keypad.
/// </summary>
NumPad2 = 76,
/// <summary>
/// The 3 key on the numeric keypad.
/// </summary>
NumPad3 = 77,
/// <summary>
/// The 4 key on the numeric keypad.
/// </summary>
NumPad4 = 78,
/// <summary>
/// The 5 key on the numeric keypad.
/// </summary>
NumPad5 = 79,
/// <summary>
/// The 6 key on the numeric keypad.
/// </summary>
NumPad6 = 80,
/// <summary>
/// The 7 key on the numeric keypad.
/// </summary>
NumPad7 = 81,
/// <summary>
/// The 8 key on the numeric keypad.
/// </summary>
NumPad8 = 82,
/// <summary>
/// The 9 key on the numeric keypad.
/// </summary>
NumPad9 = 83,
/// <summary>
/// The Multiply key.
/// </summary>
Multiply = 84,
/// <summary>
/// The Add key.
/// </summary>
Add = 85,
/// <summary>
/// The Separator key.
/// </summary>
Separator = 86,
/// <summary>
/// The Subtract key.
/// </summary>
Subtract = 87,
/// <summary>
/// The Decimal key.
/// </summary>
Decimal = 88,
/// <summary>
/// The Divide key.
/// </summary>
Divide = 89,
/// <summary>
/// The F1 key.
/// </summary>
F1 = 90,
/// <summary>
/// The F2 key.
/// </summary>
F2 = 91,
/// <summary>
/// The F3 key.
/// </summary>
F3 = 92,
/// <summary>
/// The F4 key.
/// </summary>
F4 = 93,
/// <summary>
/// The F5 key.
/// </summary>
F5 = 94,
/// <summary>
/// The F6 key.
/// </summary>
F6 = 95,
/// <summary>
/// The F7 key.
/// </summary>
F7 = 96,
/// <summary>
/// The F8 key.
/// </summary>
F8 = 97,
/// <summary>
/// The F9 key.
/// </summary>
F9 = 98,
/// <summary>
/// The F10 key.
/// </summary>
F10 = 99,
/// <summary>
/// The F11 key.
/// </summary>
F11 = 100,
/// <summary>
/// The F12 key.
/// </summary>
F12 = 101,
/// <summary>
/// The F13 key.
/// </summary>
F13 = 102,
/// <summary>
/// The F14 key.
/// </summary>
F14 = 103,
/// <summary>
/// The F15 key.
/// </summary>
F15 = 104,
/// <summary>
/// The F16 key.
/// </summary>
F16 = 105,
/// <summary>
/// The F17 key.
/// </summary>
F17 = 106,
/// <summary>
/// The F18 key.
/// </summary>
F18 = 107,
/// <summary>
/// The F19 key.
/// </summary>
F19 = 108,
/// <summary>
/// The F20 key.
/// </summary>
F20 = 109,
/// <summary>
/// The F21 key.
/// </summary>
F21 = 110,
/// <summary>
/// The F22 key.
/// </summary>
F22 = 111,
/// <summary>
/// The F23 key.
/// </summary>
F23 = 112,
/// <summary>
/// The F24 key.
/// </summary>
F24 = 113,
/// <summary>
/// The Numlock key.
/// </summary>
NumLock = 114,
/// <summary>
/// The Scroll key.
/// </summary>
Scroll = 115,
/// <summary>
/// The left Shift key.
/// </summary>
LeftShift = 116,
/// <summary>
/// The right Shift key.
/// </summary>
RightShift = 117,
/// <summary>
/// The left Ctrl key.
/// </summary>
LeftCtrl = 118,
/// <summary>
/// The right Ctrl key.
/// </summary>
RightCtrl = 119,
/// <summary>
/// The left Alt key.
/// </summary>
LeftAlt = 120,
/// <summary>
/// The right Alt key.
/// </summary>
RightAlt = 121,
/// <summary>
/// The browser Back key.
/// </summary>
BrowserBack = 122,
/// <summary>
/// The browser Forward key.
/// </summary>
BrowserForward = 123,
/// <summary>
/// The browser Refresh key.
/// </summary>
BrowserRefresh = 124,
/// <summary>
/// The browser Stop key.
/// </summary>
BrowserStop = 125,
/// <summary>
/// The browser Search key.
/// </summary>
BrowserSearch = 126,
/// <summary>
/// The browser Favorites key.
/// </summary>
BrowserFavorites = 127,
/// <summary>
/// The browser Home key.
/// </summary>
BrowserHome = 128,
/// <summary>
/// The Volume Mute key.
/// </summary>
VolumeMute = 129,
/// <summary>
/// The Volume Down key.
/// </summary>
VolumeDown = 130,
/// <summary>
/// The Volume Up key.
/// </summary>
VolumeUp = 131,
/// <summary>
/// The media Next Track key.
/// </summary>
MediaNextTrack = 132,
/// <summary>
/// The media Previous Track key.
/// </summary>
MediaPreviousTrack = 133,
/// <summary>
/// The media Stop key.
/// </summary>
MediaStop = 134,
/// <summary>
/// The media Play/Pause key.
/// </summary>
MediaPlayPause = 135,
/// <summary>
/// The Launch Mail key.
/// </summary>
LaunchMail = 136,
/// <summary>
/// The Select Media key.
/// </summary>
SelectMedia = 137,
/// <summary>
/// The Launch Application 1 key.
/// </summary>
LaunchApplication1 = 138,
/// <summary>
/// The Launch Application 2 key.
/// </summary>
LaunchApplication2 = 139,
/// <summary>
/// The OEM Semicolon key.
/// </summary>
OemSemicolon = 140,
/// <summary>
/// The OEM 1 key.
/// </summary>
Oem1 = 140,
/// <summary>
/// The OEM Plus key.
/// </summary>
OemPlus = 141,
/// <summary>
/// The OEM Comma key.
/// </summary>
OemComma = 142,
/// <summary>
/// The OEM Minus key.
/// </summary>
OemMinus = 143,
/// <summary>
/// The OEM Period key.
/// </summary>
OemPeriod = 144,
/// <summary>
/// The OEM Question Mark key.
/// </summary>
OemQuestion = 145,
/// <summary>
/// The OEM 2 key.
/// </summary>
Oem2 = 145,
/// <summary>
/// The OEM Tilde key.
/// </summary>
OemTilde = 146,
/// <summary>
/// The OEM 3 key.
/// </summary>
Oem3 = 146,
/// <summary>
/// The ABNT_C1 (Brazilian) key.
/// </summary>
AbntC1 = 147,
/// <summary>
/// The ABNT_C2 (Brazilian) key.
/// </summary>
AbntC2 = 148,
/// <summary>
/// The OEM Open Brackets key.
/// </summary>
OemOpenBrackets = 149,
/// <summary>
/// The OEM 4 key.
/// </summary>
Oem4 = 149,
/// <summary>
/// The OEM Pipe key.
/// </summary>
OemPipe = 150,
/// <summary>
/// The OEM 5 key.
/// </summary>
Oem5 = 150,
/// <summary>
/// The OEM Close Brackets key.
/// </summary>
OemCloseBrackets = 151,
/// <summary>
/// The OEM 6 key.
/// </summary>
Oem6 = 151,
/// <summary>
/// The OEM Quotes key.
/// </summary>
OemQuotes = 152,
/// <summary>
/// The OEM 7 key.
/// </summary>
Oem7 = 152,
/// <summary>
/// The OEM 8 key.
/// </summary>
Oem8 = 153,
/// <summary>
/// The OEM Backslash key.
/// </summary>
OemBackslash = 154,
/// <summary>
/// The OEM 3 key.
/// </summary>
Oem102 = 154,
/// <summary>
/// A special key masking the real key being processed by an IME.
/// </summary>
ImeProcessed = 155,
/// <summary>
/// A special key masking the real key being processed as a system key.
/// </summary>
System = 156,
/// <summary>
/// The OEM ATTN key.
/// </summary>
OemAttn = 157,
/// <summary>
/// The DBE_ALPHANUMERIC key.
/// </summary>
DbeAlphanumeric = 157,
/// <summary>
/// The OEM Finish key.
/// </summary>
OemFinish = 158,
/// <summary>
/// The DBE_KATAKANA key.
/// </summary>
DbeKatakana = 158,
/// <summary>
/// The DBE_HIRAGANA key.
/// </summary>
DbeHiragana = 159,
/// <summary>
/// The OEM Copy key.
/// </summary>
OemCopy = 159,
/// <summary>
/// The DBE_SBCSCHAR key.
/// </summary>
DbeSbcsChar = 160,
/// <summary>
/// The OEM Auto key.
/// </summary>
OemAuto = 160,
/// <summary>
/// The DBE_DBCSCHAR key.
/// </summary>
DbeDbcsChar = 161,
/// <summary>
/// The OEM ENLW key.
/// </summary>
OemEnlw = 161,
/// <summary>
/// The OEM BackTab key.
/// </summary>
OemBackTab = 162,
/// <summary>
/// The DBE_ROMAN key.
/// </summary>
DbeRoman = 162,
/// <summary>
/// The DBE_NOROMAN key.
/// </summary>
DbeNoRoman = 163,
/// <summary>
/// The ATTN key.
/// </summary>
Attn = 163,
/// <summary>
/// The CRSEL key.
/// </summary>
CrSel = 164,
/// <summary>
/// The DBE_ENTERWORDREGISTERMODE key.
/// </summary>
DbeEnterWordRegisterMode = 164,
/// <summary>
/// The EXSEL key.
/// </summary>
ExSel = 165,
/// <summary>
/// The DBE_ENTERIMECONFIGMODE key.
/// </summary>
DbeEnterImeConfigureMode = 165,
/// <summary>
/// The ERASE EOF Key.
/// </summary>
EraseEof = 166,
/// <summary>
/// The DBE_FLUSHSTRING key.
/// </summary>
DbeFlushString = 166,
/// <summary>
/// The Play key.
/// </summary>
Play = 167,
/// <summary>
/// The DBE_CODEINPUT key.
/// </summary>
DbeCodeInput = 167,
/// <summary>
/// The DBE_NOCODEINPUT key.
/// </summary>
DbeNoCodeInput = 168,
/// <summary>
/// The Zoom key.
/// </summary>
Zoom = 168,
/// <summary>
/// Reserved for future use.
/// </summary>
NoName = 169,
/// <summary>
/// The DBE_DETERMINESTRING key.
/// </summary>
DbeDetermineString = 169,
/// <summary>
/// The DBE_ENTERDLGCONVERSIONMODE key.
/// </summary>
DbeEnterDialogConversionMode = 170,
/// <summary>
/// The PA1 key.
/// </summary>
Pa1 = 170,
/// <summary>
/// The OEM Clear key.
/// </summary>
OemClear = 171,
/// <summary>
/// The key is used with another key to create a single combined character.
/// </summary>
DeadCharProcessed = 172,
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Description: FontFamilyIdentifier type
//
// History:
// 5/6/2005 : niklasb - Created
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Security;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using MS.Utility;
using MS.Internal;
using MS.Internal.Shaping;
using MS.Internal.FontCache;
using MS.Internal.TextFormatting;
namespace MS.Internal.FontFace
{
/// <summary>
/// The FontFamilyIdentifier value type encapsulates a friendly name and base Uri
/// and provides access to the corresponding canonical name(s) via an indexer.
/// </summary>
//
// The friendly name is a string in the format passed to the FontFamily constructor and the
// corresponding type converter. It comprises one or more font family references separated by
// commas (with literal commas escaped by doubling). Each font family reference comprises a
// family name and an optional location.
//
// Pseudo-BNF:
//
// friendlyName = ESCAPED(fontFamilyReference) *( "," ESCAPED(fontFamilyReference) )
// fontFamilyReference = [ location "#" ] escapedFamilyName
// location = "" | relativeUri | absoluteUri
//
// where ESCAPED(fontFamilyReference) denotes a fontFamilyReference in which comma characters (",")
// have been replaced by doubled commas (",,").
//
// Both the location (if present) and the escapedFamilyName may contain hexadecimal escape
// sequences in the form %XX as in URI references.
//
// The location may be an empty string so "#ARIAL" is a valid font family reference;
// in fact it is the normalized form of "Arial".
//
// Canonicalization
//
// Canonicalization is the process of converting a font family reference to an absolute URI
// which specifies the font family location, plus a fragment which specifies the family name.
// The family name is converted to uppercase (since family names are not case-sensitive) but
// the rest of the URI is not.
//
// The process for canonicalizing the entire friendly name is as follows:
//
// 1. Split the friendly name into font family references.
// Treat single commas (",") as delimiters, and unescape double commas (",,").
//
// 2. Convert each font family reference to a normalized form.
// See Util.NormalizeFontFamilyReference.
//
// 3. Canonicalize the normalized font family reference.
// See Util.GetCanonicalUriForFamily.
//
// This is essentially what the Canonicalize method does, with addition of caching the resulting
// canonical names in the TypefaceMetricsCache. To save working set, the result of canonicalization
// is stored as a single null-delimited string rather than an array of strings.
//
// Since canonicalization is potentially expensive, we do not always canonicalize the entire
// friendly name. In this case, the indexer canonicalizes the requested font family reference
// on demand. However, we still cache the result in the TypefaceMetricsCache.
//
internal struct FontFamilyIdentifier
{
/// <summary>
/// FontFamilyIdentifier constructor
/// </summary>
/// <param name="friendlyName">friendly name in the format passed to
/// FontFamily constructor and type converter.</param>
/// <param name="baseUri">Base Uri used to resolve the location part of a font family reference
/// if one exists and is relative</param>
internal FontFamilyIdentifier(string friendlyName, Uri baseUri)
{
_friendlyName = friendlyName;
_baseUri = baseUri;
_tokenCount = (friendlyName != null) ? -1 : 0;
_canonicalReferences = null;
}
/// <summary>
/// Create a FontFamilyIdentifier by concatenating two existing identifiers.
/// </summary>
internal FontFamilyIdentifier(FontFamilyIdentifier first, FontFamilyIdentifier second)
{
first.Canonicalize();
second.Canonicalize();
_friendlyName = null;
_tokenCount = first._tokenCount + second._tokenCount;
_baseUri = null;
if (first._tokenCount == 0)
{
_canonicalReferences = second._canonicalReferences;
}
else if (second._tokenCount == 0)
{
_canonicalReferences = first._canonicalReferences;
}
else
{
_canonicalReferences = new CanonicalFontFamilyReference[_tokenCount];
int i = 0;
foreach (CanonicalFontFamilyReference family in first._canonicalReferences)
{
_canonicalReferences[i++] = family;
}
foreach (CanonicalFontFamilyReference family in second._canonicalReferences)
{
_canonicalReferences[i++] = family;
}
}
}
internal string Source
{
get { return _friendlyName; }
}
internal Uri BaseUri
{
get { return _baseUri; }
}
public bool Equals(FontFamilyIdentifier other)
{
if (_friendlyName == other._friendlyName && _baseUri == other._baseUri)
return true;
int c = Count;
if (other.Count != c)
return false;
if (c != 0)
{
Canonicalize();
other.Canonicalize();
for (int i = 0; i < c; ++i)
{
if (!_canonicalReferences[i].Equals(other._canonicalReferences[i]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
return obj is FontFamilyIdentifier && Equals((FontFamilyIdentifier)obj);
}
public override int GetHashCode()
{
int hash = 1;
if (Count != 0)
{
Canonicalize();
foreach (CanonicalFontFamilyReference family in _canonicalReferences)
{
hash = HashFn.HashMultiply(hash) + family.GetHashCode();
}
}
return HashFn.HashScramble(hash);
}
internal int Count
{
get
{
// negative value represents uninitialized count
if (_tokenCount < 0)
{
_tokenCount = CountTokens(_friendlyName);
}
return _tokenCount;
}
}
internal CanonicalFontFamilyReference this[int tokenIndex]
{
get
{
if (tokenIndex < 0 || tokenIndex >= Count)
throw new ArgumentOutOfRangeException("tokenIndex");
// Have we already been canonicalized?
if (_canonicalReferences != null)
{
// We have already canonicalized. This is typically the case for longer-lived
// identifiers such as belong to FontFamily objects.
return _canonicalReferences[tokenIndex];
}
else
{
// We have not already canonicalized. This is probably a short-lived object so
// it's not worthwhile to canonicalize all the names up front and cache them for
// later use. Just canonicalize each name as we need it.
// find the Nth font family reference.
int i, length;
int j = FindToken(_friendlyName, 0, out i, out length);
for (int k = 0; k < tokenIndex; ++k)
{
j = FindToken(_friendlyName, j, out i, out length);
}
// canonicalize just this font family reference
return GetCanonicalReference(i, length);
}
}
}
/// <SecurityNote>
/// Critical - as it accesses canonical names as raw strings
/// Safe - as information is not returned but stored in SecurityCritical _canonicalReferences field
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal void Canonicalize()
{
if (_canonicalReferences != null)
return;
int count = this.Count;
if (count == 0)
return;
// First look up the entire friendly name in the cache; this may enable us to
// save working set by sharing the same array of may equal FontFamilyIdentifier.
BasedFriendlyName hashKey = new BasedFriendlyName(_baseUri, _friendlyName);
CanonicalFontFamilyReference[] canonicalReferences = TypefaceMetricsCache.ReadonlyLookup(hashKey) as CanonicalFontFamilyReference[];
if (canonicalReferences == null)
{
// We need to construct a new array.
canonicalReferences = new CanonicalFontFamilyReference[count];
// Add the first canonical family reference.
int i, length;
int j = FindToken(_friendlyName, 0, out i, out length);
canonicalReferences[0] = GetCanonicalReference(i, length);
// Add subsequent family references.
for (int k = 1; k < count; ++k)
{
j = FindToken(_friendlyName, j, out i, out length);
canonicalReferences[k] = GetCanonicalReference(i, length);
}
// Add the array to the cache.
TypefaceMetricsCache.Add(hashKey, canonicalReferences);
}
// for thread safety, we assign to the field only after the array is fully initialized
_canonicalReferences = canonicalReferences;
}
#region Friendly name parsing methods
private static int CountTokens(string friendlyName)
{
int count = 0;
int i, length;
int j = FindToken(friendlyName, 0, out i, out length);
while (j >= 0)
{
// Limit the number of family names in a single string.
if (++count == MaxFamilyNamePerFamilyMapTarget)
break;
j = FindToken(friendlyName, j, out i, out length);
}
return count;
}
/// <summary>
/// Scans the specified friendly name starting at the specified index and gets the index and
/// length of the first token it finds.
/// </summary>
/// <param name="friendlyName">friendly name containing zero or more comma-delimited tokens</param>
/// <param name="i">character index to scan from</param>
/// <param name="tokenIndex">receives the index of the token (or zero if none)</param>
/// <param name="tokenLength">receives the length of the token (or zero if none)</param>
/// <returns>If a token was found, the return value is a positive integer specifying where to begin
/// scanning for the next token; if no token was found, the return value is -1.</returns>
private static int FindToken(string friendlyName, int i, out int tokenIndex, out int tokenLength)
{
int length = friendlyName.Length;
while (i < length)
{
// skip leading whitespace
while (i < length && char.IsWhiteSpace(friendlyName[i]))
++i;
int begin = i;
// find delimiter or end of string
while (i < length)
{
if (friendlyName[i] == FamilyNameDelimiter)
{
if (i + 1 < length && friendlyName[i + 1] == FamilyNameDelimiter)
{
// Don't treat double commas as the family name delimiter.
i += 2;
}
else
{
break; // single comma delimiter
}
}
else if (friendlyName[i] == '\0')
{
break; // might as well treat null as a delimiter too
}
else
{
++i;
}
}
// exclude trailing whitespace
int end = i;
while (end > begin && char.IsWhiteSpace(friendlyName[end - 1]))
--end;
// make sure it's not an empty string
if (begin < end)
{
tokenIndex = begin;
tokenLength = end - begin;
return i + 1;
}
// continue after delimiter
++i;
}
// no token
tokenIndex = length;
tokenLength = 0;
return -1;
}
private CanonicalFontFamilyReference GetCanonicalReference(int startIndex, int length)
{
string normalizedString = Util.GetNormalizedFontFamilyReference(_friendlyName, startIndex, length);
// For caching normalized names, we use a different type of key which does not compare equal
// to the keys we used for caching friendly names.
BasedNormalizedName hashKey = new BasedNormalizedName(_baseUri, normalizedString);
// Look up the normalized string and base URI in the cache?
CanonicalFontFamilyReference canonicalReference = TypefaceMetricsCache.ReadonlyLookup(hashKey) as CanonicalFontFamilyReference;
// Do we already have a cached font family reference?
if (canonicalReference == null)
{
// Not in cache. Construct a new font family reference.
canonicalReference = CanonicalFontFamilyReference.Create(_baseUri, normalizedString);
// Add it to the cache.
TypefaceMetricsCache.Add(hashKey, canonicalReference);
}
return canonicalReference;
}
#endregion
#region BasedFriendlyName and BasedNormalizedName
/// <summary>
/// BasedFriendlyName represents a friendly name with an associated URI or use as a hash key.
/// </summary>
private sealed class BasedFriendlyName : BasedName
{
public BasedFriendlyName(Uri baseUri, string name)
: base(baseUri, name)
{
}
public override int GetHashCode()
{
// Specify a different seed than BasedNormalizedName
return InternalGetHashCode(1);
}
public override bool Equals(object obj)
{
// Only compare equal to other BasedFriendlyName objects
return InternalEquals(obj as BasedFriendlyName);
}
}
/// <summary>
/// BasedNormalizedName represents a normalized name with an associated URI or use as a hash key.
/// </summary>
private sealed class BasedNormalizedName : BasedName
{
public BasedNormalizedName(Uri baseUri, string name)
: base(baseUri, name)
{
}
public override int GetHashCode()
{
// Specify a different seed than BasedFriendlyName
return InternalGetHashCode(int.MaxValue);
}
public override bool Equals(object obj)
{
// Only compare equal to other BasedNormalizedName objects
return InternalEquals(obj as BasedNormalizedName);
}
}
/// <summary>
/// BasedName implements shared functionality of BasedFriendlyName and BasedNormalizedName.
/// The reason for the two derived classes (and for not just using Pair) is that we don't
/// want these two different types of keys to compare equal.
/// </summary>
private abstract class BasedName
{
private Uri _baseUri;
private string _name;
protected BasedName(Uri baseUri, string name)
{
_baseUri = baseUri;
_name = name;
}
public abstract override int GetHashCode();
public abstract override bool Equals(object obj);
protected int InternalGetHashCode(int seed)
{
int hash = seed;
if (_baseUri != null)
hash += HashFn.HashMultiply(_baseUri.GetHashCode());
if (_name != null)
hash = HashFn.HashMultiply(hash) + _name.GetHashCode();
return HashFn.HashScramble(hash);
}
protected bool InternalEquals(BasedName other)
{
return other != null &&
other._baseUri == _baseUri &&
other._name == _name;
}
}
#endregion
private string _friendlyName;
private Uri _baseUri;
private int _tokenCount;
private CanonicalFontFamilyReference[] _canonicalReferences;
internal const char FamilyNameDelimiter = ',';
internal const int MaxFamilyNamePerFamilyMapTarget = 32;
}
}
| |
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Microsoft.VisualStudio.Services.Agent.Worker.Build;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.Build
{
public sealed class GitSourceProviderL0
{
private Mock<IGitCommandManager> GetDefaultGitCommandMock()
{
Mock<IGitCommandManager> _gitCommandManager = new Mock<IGitCommandManager>();
_gitCommandManager
.Setup(x => x.LoadGitExecutionInfo(It.IsAny<IExecutionContext>()))
.Returns(Task.CompletedTask);
_gitCommandManager
.Setup(x => x.GitInit(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitRemoteAdd(It.IsAny<IExecutionContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitFetch(It.IsAny<IExecutionContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<List<string>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitCheckout(It.IsAny<IExecutionContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitClean(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitReset(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitRemoteSetUrl(It.IsAny<IExecutionContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitRemoteSetPushUrl(It.IsAny<IExecutionContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitSubmoduleInit(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitSubmoduleUpdate(It.IsAny<IExecutionContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitGetFetchUrl(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
.Returns(Task.FromResult<Uri>(new Uri("https://github.com/Microsoft/vsts-agent")));
_gitCommandManager
.Setup(x => x.GitDisableAutoGC(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
.Returns(Task.FromResult<int>(0));
_gitCommandManager
.Setup(x => x.GitVersion(It.IsAny<IExecutionContext>()))
.Returns(Task.FromResult<Version>(new Version(2, 7)));
return _gitCommandManager;
}
private Mock<IExecutionContext> GetTestExecutionContext(TestHostContext tc, string sourceFolder, string sourceBranch, string sourceVersion, bool enableAuth)
{
var trace = tc.GetTrace();
var executionContext = new Mock<IExecutionContext>();
List<string> warnings;
executionContext
.Setup(x => x.Variables)
.Returns(new Variables(tc, copy: new Dictionary<string, string>(), maskHints: new List<MaskHint>(), warnings: out warnings));
executionContext
.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>()))
.Callback((string tag, string message) =>
{
trace.Info($"{tag}{message}");
});
executionContext
.Setup(x => x.WriteDebug)
.Returns(true);
executionContext.Object.Variables.Set(Constants.Variables.Build.SourcesDirectory, sourceFolder);
executionContext.Object.Variables.Set(Constants.Variables.Build.SourceBranch, sourceBranch);
executionContext.Object.Variables.Set(Constants.Variables.Build.SourceVersion, sourceVersion);
executionContext.Object.Variables.Set(Constants.Variables.System.EnableAccessToken, enableAuth.ToString());
return executionContext;
}
private ServiceEndpoint GetTestSourceEndpoint(string url, bool clean, bool checkoutSubmodules)
{
var endpoint = new ServiceEndpoint();
endpoint.Data[WellKnownEndpointData.Clean] = clean.ToString();
endpoint.Data[WellKnownEndpointData.CheckoutSubmodules] = checkoutSubmodules.ToString();
endpoint.Url = new Uri(url);
endpoint.Authorization = new EndpointAuthorization()
{
Scheme = EndpointAuthorizationSchemes.UsernamePassword
};
endpoint.Authorization.Parameters[EndpointAuthorizationParameters.Username] = "someuser";
endpoint.Authorization.Parameters[EndpointAuthorizationParameters.Password] = "SomePassword!";
return endpoint;
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void GetSourceGitClone()
{
using (TestHostContext tc = new TestHostContext(this))
{
// Arrange.
string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "master", "a596e13f5db8869f44574be0392fb8fe1e790ce4", false);
var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", false, false);
var _gitCommandManager = GetDefaultGitCommandMock();
tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
tc.SetSingleton<IWhichUtil>(new WhichUtil());
GitSourceProvider gitSourceProvider = new GitSourceProvider();
gitSourceProvider.Initialize(tc);
// Act.
gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();
// Assert.
_gitCommandManager.Verify(x => x.GitInit(executionContext.Object, dumySourceFolder));
_gitCommandManager.Verify(x => x.GitRemoteAdd(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, "a596e13f5db8869f44574be0392fb8fe1e790ce4", It.IsAny<CancellationToken>()));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void GetSourceGitFetch()
{
using (TestHostContext tc = new TestHostContext(this))
{
var trace = tc.GetTrace();
// Arrange.
string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
try
{
Directory.CreateDirectory(dumySourceFolder);
string dumyGitFolder = Path.Combine(dumySourceFolder, ".git");
Directory.CreateDirectory(dumyGitFolder);
string dumyGitConfig = Path.Combine(dumyGitFolder, "config");
File.WriteAllText(dumyGitConfig, "test git confg file");
var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "master", "a596e13f5db8869f44574be0392fb8fe1e790ce4", false);
var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", false, false);
var _gitCommandManager = GetDefaultGitCommandMock();
tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
tc.SetSingleton<IWhichUtil>(new WhichUtil());
GitSourceProvider gitSourceProvider = new GitSourceProvider();
gitSourceProvider.Initialize(tc);
// Act.
gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();
// Assert.
_gitCommandManager.Verify(x => x.GitDisableAutoGC(executionContext.Object, dumySourceFolder));
_gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://someuser:SomePassword%21@github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://someuser:SomePassword%21@github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitFetch(executionContext.Object, dumySourceFolder, "origin", It.IsAny<List<string>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()));
_gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, "a596e13f5db8869f44574be0392fb8fe1e790ce4", It.IsAny<CancellationToken>()));
}
finally
{
IOUtil.DeleteDirectory(dumySourceFolder, CancellationToken.None);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void GetSourceGitClonePR()
{
using (TestHostContext tc = new TestHostContext(this))
{
var trace = tc.GetTrace();
// Arrange.
string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "refs/pull/12345", "a596e13f5db8869f44574be0392fb8fe1e790ce4", false);
var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", false, false);
var _gitCommandManager = GetDefaultGitCommandMock();
tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
tc.SetSingleton<IWhichUtil>(new WhichUtil());
GitSourceProvider gitSourceProvider = new GitSourceProvider();
gitSourceProvider.Initialize(tc);
// Act.
gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();
// Assert.
_gitCommandManager.Verify(x => x.GitInit(executionContext.Object, dumySourceFolder));
_gitCommandManager.Verify(x => x.GitRemoteAdd(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitFetch(executionContext.Object, dumySourceFolder, "origin", new List<string>() { "+refs/pull/12345:refs/remotes/pull/12345" }, It.IsAny<string>(), It.IsAny<CancellationToken>()));
_gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, It.Is<string>(s => s.Equals("refs/remotes/pull/12345")), It.IsAny<CancellationToken>()));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void GetSourceGitFetchPR()
{
using (TestHostContext tc = new TestHostContext(this))
{
var trace = tc.GetTrace();
// Arrange.
string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
try
{
Directory.CreateDirectory(dumySourceFolder);
string dumyGitFolder = Path.Combine(dumySourceFolder, ".git");
Directory.CreateDirectory(dumyGitFolder);
string dumyGitConfig = Path.Combine(dumyGitFolder, "config");
File.WriteAllText(dumyGitConfig, "test git confg file");
var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "refs/pull/12345/merge", "a596e13f5db8869f44574be0392fb8fe1e790ce4", false);
var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", false, false);
var _gitCommandManager = GetDefaultGitCommandMock();
tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
tc.SetSingleton<IWhichUtil>(new WhichUtil());
GitSourceProvider gitSourceProvider = new GitSourceProvider();
gitSourceProvider.Initialize(tc);
// Act.
gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();
// Assert.
_gitCommandManager.Verify(x => x.GitDisableAutoGC(executionContext.Object, dumySourceFolder));
_gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://someuser:SomePassword%21@github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://someuser:SomePassword%21@github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitFetch(executionContext.Object, dumySourceFolder, "origin", new List<string>() { "+refs/pull/12345/merge:refs/remotes/pull/12345/merge" }, It.IsAny<string>(), It.IsAny<CancellationToken>()));
_gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, "refs/remotes/pull/12345/merge", It.IsAny<CancellationToken>()));
}
finally
{
IOUtil.DeleteDirectory(dumySourceFolder, CancellationToken.None);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void GetSourceReCloneOnUrlNotMatch()
{
using (TestHostContext tc = new TestHostContext(this))
{
var trace = tc.GetTrace();
// Arrange.
string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
try
{
Directory.CreateDirectory(dumySourceFolder);
string dumyGitFolder = Path.Combine(dumySourceFolder, ".git");
Directory.CreateDirectory(dumyGitFolder);
string dumyGitConfig = Path.Combine(dumyGitFolder, "config");
File.WriteAllText(dumyGitConfig, "test git confg file");
var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "refs/heads/users/user1", "", true);
var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", false, false);
var _gitCommandManager = GetDefaultGitCommandMock();
_gitCommandManager
.Setup(x => x.GitGetFetchUrl(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
.Returns(Task.FromResult<Uri>(new Uri("https://github.com/Microsoft/vsts-another-agent")));
tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
tc.SetSingleton<IWhichUtil>(new WhichUtil());
GitSourceProvider gitSourceProvider = new GitSourceProvider();
gitSourceProvider.Initialize(tc);
// Act.
gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();
// Assert.
_gitCommandManager.Verify(x => x.GitInit(executionContext.Object, dumySourceFolder));
_gitCommandManager.Verify(x => x.GitRemoteAdd(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, "refs/remotes/origin/users/user1", It.IsAny<CancellationToken>()));
}
finally
{
IOUtil.DeleteDirectory(dumySourceFolder, CancellationToken.None);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void GetSourceGitFetchWithClean()
{
using (TestHostContext tc = new TestHostContext(this))
{
var trace = tc.GetTrace();
// Arrange.
string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
try
{
Directory.CreateDirectory(dumySourceFolder);
string dumyGitFolder = Path.Combine(dumySourceFolder, ".git");
Directory.CreateDirectory(dumyGitFolder);
string dumyGitConfig = Path.Combine(dumyGitFolder, "config");
File.WriteAllText(dumyGitConfig, "test git confg file");
var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "refs/remotes/origin/master", "", false);
var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", true, false);
var _gitCommandManager = GetDefaultGitCommandMock();
tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
tc.SetSingleton<IWhichUtil>(new WhichUtil());
GitSourceProvider gitSourceProvider = new GitSourceProvider();
gitSourceProvider.Initialize(tc);
// Act.
gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();
// Assert.
_gitCommandManager.Verify(x => x.GitClean(executionContext.Object, dumySourceFolder));
_gitCommandManager.Verify(x => x.GitReset(executionContext.Object, dumySourceFolder));
_gitCommandManager.Verify(x => x.GitDisableAutoGC(executionContext.Object, dumySourceFolder));
_gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", It.Is<string>(s => s.Equals("https://someuser:SomePassword%21@github.com/Microsoft/vsts-agent"))));
_gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", It.Is<string>(s => s.Equals("https://someuser:SomePassword%21@github.com/Microsoft/vsts-agent"))));
_gitCommandManager.Verify(x => x.GitFetch(executionContext.Object, dumySourceFolder, "origin", It.IsAny<List<string>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()));
_gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
_gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, "refs/remotes/origin/master", It.IsAny<CancellationToken>()));
}
finally
{
IOUtil.DeleteDirectory(dumySourceFolder, CancellationToken.None);
}
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Daniel Kollmann
// 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 Daniel Kollmann nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using Brainiac.Design.Properties;
namespace Brainiac.Design.Nodes
{
public partial class Node
{
/// <summary>
/// A connector which is used to allow a node to have children.
/// </summary>
public abstract class Connector
{
/// <summary>
/// The number of children connected.
/// </summary>
public abstract int ChildCount { get; }
/// <summary>
/// Gets a child with a given index.
/// </summary>
/// <param name="index">The index of the child we want to get.</param>
/// <returns>Returns the requested child.</returns>
public abstract Node GetChild(int index);
/// <summary>
/// Adds a child to this connector.
/// </summary>
/// <param name="node">The node we want to add.</param>
/// <returns>Returns false if the connector does not allow any more nodes to be added.</returns>
public abstract bool AddChild(Node node);
/// <summary>
/// Adds a child to this connector on a given position.
/// </summary>
/// <param name="node">The node we want to add.</param>
/// <param name="index">The position we want to add the node at.</param>
/// <returns>Returns false if the connector does not allow any more nodes to be added.</returns>
public abstract bool AddChild(Node node, int index);
/// <summary>
/// Checks if the connector can connect to more children.
/// </summary>
/// <param name="count">The number of children we want to connect.</param>
/// <returns>Returns true if the given number of children can be connected.</returns>
public abstract bool AcceptsChildren(int count);
/// <summary>
/// Removes a child from this connector.
/// </summary>
/// <param name="node">The child we want to remove.</param>
/// <returns>Returns false if the connector is read-only.</returns>
public abstract bool RemoveChild(Node node);
/// <summary>
/// Clears all connected children.
/// </summary>
public abstract void ClearChildren();
/// <summary>
/// Clears all connected children but does not clear the stored connector of the children. Used to improve performance in some situations.
/// </summary>
public abstract void ClearChildrenInternal();
/// <summary>
/// Gets the index of a child.
/// </summary>
/// <param name="node">The child whose index we want to have.</param>
/// <returns>Returns -1 if the child could not be found.</returns>
public abstract int GetChildIndex(Node node);
/// <summary>
/// Allows direct access to the connected children.
/// </summary>
/// <param name="n">The index of the child we want to get.</param>
/// <returns>Returns the requested child.</returns>
public Node this[int n]
{
get { return GetChild(n); }
}
/// <summary>
/// The ConnectedChildren the connector is registered at.
/// </summary>
protected ConnectedChildren _connectedChildren;
protected int _minCount;
/// <summary>
/// The minimum number of connectors shown on the node.
/// </summary>
public int MinCount
{
get { return _minCount; }
}
protected int _maxCount;
/// <summary>
/// The maximum number of children accepted by the connector.
/// </summary>
public int MaxCount
{
get { return _maxCount; }
}
protected string _label;
/// <summary>
/// Stores if the label contains {0} for the index
/// </summary>
protected bool _labelIncludesIndex;
/// <summary>
/// The label used to generate the individual label for each connected child.
/// </summary>
public string BaseLabel
{
get { return _label; }
set
{
_label= value;
_labelIncludesIndex= value.Contains("{0}");
}
}
protected string _identifier;
/// <summary>
/// The identifier of the connector.
/// </summary>
public string Identifier
{
get { return _identifier; }
}
protected bool _isReadOnly= false;
/// <summary>
/// Stores if the connector is read-only, used for displaying sub-referenced behaviours and impulses.
/// </summary>
public bool IsReadOnly
{
get { return _isReadOnly; }
set { _isReadOnly= value; }
}
/// <summary>
/// The node this connector belongs to.
/// </summary>
public Node Owner
{
get { return _connectedChildren.Owner; }
}
/// <summary>
/// Creates a new connector.
/// </summary>
/// <param name="connectedChildren">Usually the _children member of a node.</param>
/// <param name="label">The label which is used to generate the individual label for each connected child. May contain {0} to include the index.</param>
/// <param name="identifier">The identifier of the connector.</param>
/// <param name="minCount">The minimum number of subitems shown for the connector.</param>
/// <param name="maxCount">The maximum number of children the connector can have.</param>
public Connector(ConnectedChildren connectedChildren, string label, string identifier, int minCount, int maxCount)
{
Debug.Check(connectedChildren !=null);
Debug.Check(minCount >=1);
Debug.Check(maxCount >=minCount);
_connectedChildren= connectedChildren;
BaseLabel= label;
_identifier= identifier;
_minCount= minCount;
_maxCount= maxCount;
// register the connector
_connectedChildren.RegisterConnector(this);
}
/// <summary>
/// Gnerates an individual label for a conencted child.
/// </summary>
/// <param name="index">The index of the child connected to this connector.</param>
/// <returns>Returns individual label for connected child.</returns>
public virtual string GetLabel(int index)
{
return _labelIncludesIndex ? string.Format(_label, index +1) : _label;
}
/// <summary>
/// Generates a list of connector subitems.
/// </summary>
/// <param name="firstIndex">The first connector subitem found on the node.</param>
/// <returns>Returns alist of all connector subitems.</returns>
protected List<SubItemConnector> CollectSubItems(out int firstIndex)
{
List<SubItemConnector> list= new List<SubItemConnector>();
firstIndex= -1;
// for each subitem...
for(int i= 0; i <_connectedChildren.Owner.SubItems.Count; ++i)
{
// check if it is a connector subitem
SubItemConnector subconn= _connectedChildren.Owner.SubItems[i] as SubItemConnector;
if(subconn !=null && subconn.Connector ==this)
{
// remember the index of the first connector subitem found
if(firstIndex ==-1)
firstIndex= i;
// add subitem to list
list.Add(subconn);
}
else
{
// subitems of a connector must be next to each other
if(firstIndex >=0)
break;
}
}
// check if we have found any subitems
if(list.Count <1)
throw new Exception(Resources.ExceptionNoSubItemForConnector);
// check that we have found enough of them and not too many
Debug.Check(list.Count >=_minCount && list.Count <=_maxCount);
return list;
}
/// <summary>
/// Rebuilds the stored indices on the connector subitems.
/// </summary>
protected void RebuildSubItemIndices()
{
int firstIndex;
List<SubItemConnector> subitems= CollectSubItems(out firstIndex);
// check that we have a connector subitem for every child. Due to the minimum count, there can be more connector subitems than children
Debug.Check(subitems.Count >=ChildCount);
for(int i= 0; i <subitems.Count; ++i)
{
// assign correct index
subitems[i].Index= i;
#if DEBUG
// check if the stored child is the same from the connector
if(i <ChildCount)
Debug.Check(subitems[i].Child ==GetChild(i));
#endif
}
}
/// <summary>
/// Adds a connector subitem for a given child.
/// </summary>
/// <param name="child">The child we want to add a connecor subitem for.</param>
protected void AddSubItem(Node child)
{
int firstIndex;
List<SubItemConnector> subitems= CollectSubItems(out firstIndex);
// check if there is a connector subitem with child due to the minimum count
foreach(SubItemConnector subitem in subitems)
{
if(subitem.Child ==null)
{
// simply reuse the connector subitem
subitem.Child= child;
return;
}
}
// add a new connector subitem
_connectedChildren.Owner.AddSubItem(new SubItemConnector(this, child, subitems.Count), firstIndex + subitems.Count);
}
/// <summary>
/// Adds a connector subitem for a given child at a given position.
/// </summary>
/// <param name="child">The child we want to add a connector subitem for.</param>
/// <param name="index">The position we want to add the subitem at.</param>
protected void AddSubItem(Node child, int index)
{
int firstIndex;
List<SubItemConnector> subitems= CollectSubItems(out firstIndex);
// we want to add inside the minimum count it can be that there is a connector subitem which has no child (due to minimum count)
if(index <_minCount)
{
foreach(SubItemConnector subitem in subitems)
{
if(subitem.Child ==null)
{
// if there is a free connector subitem we drop it so we can add a new one for our child
_connectedChildren.Owner.RemoveSubItem(subitem);
break;
}
}
}
// add a connector subitem for the child
_connectedChildren.Owner.AddSubItem(new SubItemConnector(this, child, subitems.Count), firstIndex + index);
RebuildSubItemIndices();
}
/// <summary>
/// Removes a connector subitem for a child.
/// </summary>
/// <param name="child">The child whose connector subitem we want to remove.</param>
protected void RemoveSubItem(Node child)
{
int firstIndex;
List<SubItemConnector> subitems= CollectSubItems(out firstIndex);
// find the connector subitem for this child...
for(int i= 0; i <subitems.Count; ++i)
{
SubItemConnector subitem= subitems[i];
// when we found it...
if(subitem.Child ==child)
{
// remove the subitem
_connectedChildren.Owner.RemoveSubItem(subitem);
// if we do not fullfil the minimum count, re add it at the end and clear the child
if(subitems.Count -1 <_minCount)
{
subitem.Child= null;
_connectedChildren.Owner.AddSubItem(subitem, firstIndex + subitems.Count -1);
}
// update stored indices on connector subitems
RebuildSubItemIndices();
return;
}
}
throw new Exception(Resources.ExceptionSubItemIsNoChild);
}
/// <summary>
/// Clears all connector subitems from the node.
/// </summary>
protected void ClearSubItems()
{
int firstIndex;
List<SubItemConnector> subitems= CollectSubItems(out firstIndex);
// for all connector subitems
for(int i= 0; i <subitems.Count; ++i)
{
// clear the minimum ones and remove the others
if(i <_minCount)
subitems[i].Child= null;
else _connectedChildren.Owner.RemoveSubItem(subitems[i]);
}
}
/// <summary>
/// Checks if the connector connectes to a given node.
/// </summary>
/// <param name="node">The node we want to check to be a child.</param>
/// <returns>Returns true if the node ia child of this connector.</returns>
public bool HasChild(Node node)
{
for(int i= 0; i <ChildCount; ++i)
{
if(GetChild(i) ==node)
return true;
}
return false;
}
public override string ToString()
{
return _connectedChildren.Owner.ToString() +':'+ _identifier;
}
}
}
}
| |
//
// PKCS8.cs: PKCS #8 - Private-Key Information Syntax Standard
// ftp://ftp.rsasecurity.com/pub/pkcs/doc/pkcs-8.doc
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
using Mono.Security.X509;
namespace Mono.Security.Cryptography {
#if INSIDE_CORLIB
internal
#else
public
#endif
sealed class PKCS8 {
public enum KeyInfo {
PrivateKey,
EncryptedPrivateKey,
Unknown
}
private PKCS8 ()
{
}
static public KeyInfo GetType (byte[] data)
{
if (data == null)
throw new ArgumentNullException ("data");
KeyInfo ki = KeyInfo.Unknown;
try {
ASN1 top = new ASN1 (data);
if ((top.Tag == 0x30) && (top.Count > 0)) {
ASN1 firstLevel = top [0];
switch (firstLevel.Tag) {
case 0x02:
ki = KeyInfo.PrivateKey;
break;
case 0x30:
ki = KeyInfo.EncryptedPrivateKey;
break;
}
}
}
catch {
throw new CryptographicException ("invalid ASN.1 data");
}
return ki;
}
/*
* PrivateKeyInfo ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] IMPLICIT Attributes OPTIONAL
* }
*
* Version ::= INTEGER
*
* PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
*
* PrivateKey ::= OCTET STRING
*
* Attributes ::= SET OF Attribute
*/
public class PrivateKeyInfo {
private int _version;
private string _algorithm;
private byte[] _key;
private ArrayList _list;
public PrivateKeyInfo ()
{
_version = 0;
_list = new ArrayList ();
}
public PrivateKeyInfo (byte[] data) : this ()
{
Decode (data);
}
// properties
public string Algorithm {
get { return _algorithm; }
set { _algorithm = value; }
}
public ArrayList Attributes {
get { return _list; }
}
public byte[] PrivateKey {
get {
if (_key == null)
return null;
return (byte[]) _key.Clone ();
}
set {
if (value == null)
throw new ArgumentNullException ("PrivateKey");
_key = (byte[]) value.Clone ();
}
}
public int Version {
get { return _version; }
set {
if (value < 0)
throw new ArgumentOutOfRangeException ("negative version");
_version = value;
}
}
// methods
private void Decode (byte[] data)
{
ASN1 privateKeyInfo = new ASN1 (data);
if (privateKeyInfo.Tag != 0x30)
throw new CryptographicException ("invalid PrivateKeyInfo");
ASN1 version = privateKeyInfo [0];
if (version.Tag != 0x02)
throw new CryptographicException ("invalid version");
_version = version.Value [0];
ASN1 privateKeyAlgorithm = privateKeyInfo [1];
if (privateKeyAlgorithm.Tag != 0x30)
throw new CryptographicException ("invalid algorithm");
ASN1 algorithm = privateKeyAlgorithm [0];
if (algorithm.Tag != 0x06)
throw new CryptographicException ("missing algorithm OID");
_algorithm = ASN1Convert.ToOid (algorithm);
ASN1 privateKey = privateKeyInfo [2];
_key = privateKey.Value;
// attributes [0] IMPLICIT Attributes OPTIONAL
if (privateKeyInfo.Count > 3) {
ASN1 attributes = privateKeyInfo [3];
for (int i=0; i < attributes.Count; i++) {
_list.Add (attributes [i]);
}
}
}
public byte[] GetBytes ()
{
ASN1 privateKeyAlgorithm = new ASN1 (0x30);
privateKeyAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
privateKeyAlgorithm.Add (new ASN1 (0x05)); // ASN.1 NULL
ASN1 pki = new ASN1 (0x30);
pki.Add (new ASN1 (0x02, new byte [1] { (byte) _version }));
pki.Add (privateKeyAlgorithm);
pki.Add (new ASN1 (0x04, _key));
if (_list.Count > 0) {
ASN1 attributes = new ASN1 (0xA0);
foreach (ASN1 attribute in _list) {
attributes.Add (attribute);
}
pki.Add (attributes);
}
return pki.GetBytes ();
}
// static methods
static private byte[] RemoveLeadingZero (byte[] bigInt)
{
int start = 0;
int length = bigInt.Length;
if (bigInt [0] == 0x00) {
start = 1;
length--;
}
byte[] bi = new byte [length];
Buffer.BlockCopy (bigInt, start, bi, 0, length);
return bi;
}
static private byte[] Normalize (byte[] bigInt, int length)
{
if (bigInt.Length == length)
return bigInt;
else if (bigInt.Length > length)
return RemoveLeadingZero (bigInt);
else {
// pad with 0
byte[] bi = new byte [length];
Buffer.BlockCopy (bigInt, 0, bi, (length - bigInt.Length), bigInt.Length);
return bi;
}
}
/*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*/
static public RSA DecodeRSA (byte[] keypair)
{
ASN1 privateKey = new ASN1 (keypair);
if (privateKey.Tag != 0x30)
throw new CryptographicException ("invalid private key format");
ASN1 version = privateKey [0];
if (version.Tag != 0x02)
throw new CryptographicException ("missing version");
if (privateKey.Count < 9)
throw new CryptographicException ("not enough key parameters");
RSAParameters param = new RSAParameters ();
// note: MUST remove leading 0 - else MS wont import the key
param.Modulus = RemoveLeadingZero (privateKey [1].Value);
int keysize = param.Modulus.Length;
int keysize2 = (keysize >> 1); // half-size
// size must be normalized - else MS wont import the key
param.D = Normalize (privateKey [3].Value, keysize);
param.DP = Normalize (privateKey [6].Value, keysize2);
param.DQ = Normalize (privateKey [7].Value, keysize2);
param.Exponent = RemoveLeadingZero (privateKey [2].Value);
param.InverseQ = Normalize (privateKey [8].Value, keysize2);
param.P = Normalize (privateKey [4].Value, keysize2);
param.Q = Normalize (privateKey [5].Value, keysize2);
RSA rsa = null;
try {
rsa = RSA.Create ();
rsa.ImportParameters (param);
}
catch (CryptographicException) {
// this may cause problem when this code is run under
// the SYSTEM identity on Windows (e.g. ASP.NET). See
// http://bugzilla.ximian.com/show_bug.cgi?id=77559
CspParameters csp = new CspParameters ();
csp.Flags = CspProviderFlags.UseMachineKeyStore;
rsa = new RSACryptoServiceProvider (csp);
rsa.ImportParameters (param);
}
return rsa;
}
/*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*/
static public byte[] Encode (RSA rsa)
{
RSAParameters param = rsa.ExportParameters (true);
ASN1 rsaPrivateKey = new ASN1 (0x30);
rsaPrivateKey.Add (new ASN1 (0x02, new byte [1] { 0x00 }));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Modulus));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Exponent));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.D));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.P));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Q));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DP));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DQ));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.InverseQ));
return rsaPrivateKey.GetBytes ();
}
// DSA only encode it's X private key inside an ASN.1 INTEGER (Hint: Tag == 0x02)
// which isn't enough for rebuilding the keypair. The other parameters
// can be found (98% of the time) in the X.509 certificate associated
// with the private key or (2% of the time) the parameters are in it's
// issuer X.509 certificate (not supported in the .NET framework).
static public DSA DecodeDSA (byte[] privateKey, DSAParameters dsaParameters)
{
ASN1 pvk = new ASN1 (privateKey);
if (pvk.Tag != 0x02)
throw new CryptographicException ("invalid private key format");
// X is ALWAYS 20 bytes (no matter if the key length is 512 or 1024 bits)
dsaParameters.X = Normalize (pvk.Value, 20);
DSA dsa = DSA.Create ();
dsa.ImportParameters (dsaParameters);
return dsa;
}
static public byte[] Encode (DSA dsa)
{
DSAParameters param = dsa.ExportParameters (true);
return ASN1Convert.FromUnsignedBigInteger (param.X).GetBytes ();
}
static public byte[] Encode (AsymmetricAlgorithm aa)
{
if (aa is RSA)
return Encode ((RSA)aa);
else if (aa is DSA)
return Encode ((DSA)aa);
else
throw new CryptographicException ("Unknown asymmetric algorithm {0}", aa.ToString ());
}
}
/*
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm EncryptionAlgorithmIdentifier,
* encryptedData EncryptedData
* }
*
* EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
*
* EncryptedData ::= OCTET STRING
*
* --
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
*
* -- from PKCS#5
* PBEParameter ::= SEQUENCE {
* salt OCTET STRING SIZE(8),
* iterationCount INTEGER
* }
*/
public class EncryptedPrivateKeyInfo {
private string _algorithm;
private byte[] _salt;
private int _iterations;
private byte[] _data;
public EncryptedPrivateKeyInfo () {}
public EncryptedPrivateKeyInfo (byte[] data) : this ()
{
Decode (data);
}
// properties
public string Algorithm {
get { return _algorithm; }
set { _algorithm = value; }
}
public byte[] EncryptedData {
get { return (_data == null) ? null : (byte[]) _data.Clone (); }
set { _data = (value == null) ? null : (byte[]) value.Clone (); }
}
public byte[] Salt {
get {
if (_salt == null) {
RandomNumberGenerator rng = RandomNumberGenerator.Create ();
_salt = new byte [8];
rng.GetBytes (_salt);
}
return (byte[]) _salt.Clone ();
}
set { _salt = (byte[]) value.Clone (); }
}
public int IterationCount {
get { return _iterations; }
set {
if (value < 0)
throw new ArgumentOutOfRangeException ("IterationCount", "Negative");
_iterations = value;
}
}
// methods
private void Decode (byte[] data)
{
ASN1 encryptedPrivateKeyInfo = new ASN1 (data);
if (encryptedPrivateKeyInfo.Tag != 0x30)
throw new CryptographicException ("invalid EncryptedPrivateKeyInfo");
ASN1 encryptionAlgorithm = encryptedPrivateKeyInfo [0];
if (encryptionAlgorithm.Tag != 0x30)
throw new CryptographicException ("invalid encryptionAlgorithm");
ASN1 algorithm = encryptionAlgorithm [0];
if (algorithm.Tag != 0x06)
throw new CryptographicException ("invalid algorithm");
_algorithm = ASN1Convert.ToOid (algorithm);
// parameters ANY DEFINED BY algorithm OPTIONAL
if (encryptionAlgorithm.Count > 1) {
ASN1 parameters = encryptionAlgorithm [1];
if (parameters.Tag != 0x30)
throw new CryptographicException ("invalid parameters");
ASN1 salt = parameters [0];
if (salt.Tag != 0x04)
throw new CryptographicException ("invalid salt");
_salt = salt.Value;
ASN1 iterationCount = parameters [1];
if (iterationCount.Tag != 0x02)
throw new CryptographicException ("invalid iterationCount");
_iterations = ASN1Convert.ToInt32 (iterationCount);
}
ASN1 encryptedData = encryptedPrivateKeyInfo [1];
if (encryptedData.Tag != 0x04)
throw new CryptographicException ("invalid EncryptedData");
_data = encryptedData.Value;
}
// Note: PKCS#8 doesn't define how to generate the key required for encryption
// so you're on your own. Just don't try to copy the big guys too much ;)
// Netscape: http://www.cs.auckland.ac.nz/~pgut001/pubs/netscape.txt
// Microsoft: http://www.cs.auckland.ac.nz/~pgut001/pubs/breakms.txt
public byte[] GetBytes ()
{
if (_algorithm == null)
throw new CryptographicException ("No algorithm OID specified");
ASN1 encryptionAlgorithm = new ASN1 (0x30);
encryptionAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
// parameters ANY DEFINED BY algorithm OPTIONAL
if ((_iterations > 0) || (_salt != null)) {
ASN1 salt = new ASN1 (0x04, _salt);
ASN1 iterations = ASN1Convert.FromInt32 (_iterations);
ASN1 parameters = new ASN1 (0x30);
parameters.Add (salt);
parameters.Add (iterations);
encryptionAlgorithm.Add (parameters);
}
// encapsulates EncryptedData into an OCTET STRING
ASN1 encryptedData = new ASN1 (0x04, _data);
ASN1 encryptedPrivateKeyInfo = new ASN1 (0x30);
encryptedPrivateKeyInfo.Add (encryptionAlgorithm);
encryptedPrivateKeyInfo.Add (encryptedData);
return encryptedPrivateKeyInfo.GetBytes ();
}
}
}
}
| |
// 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.Collections.Generic;
using System.Text;
namespace Microsoft.PythonTools.Parsing.Ast {
public class ClassDefinition : ScopeStatement {
private int _headerIndex;
private readonly NameExpression/*!*/ _name;
private Statement _body;
private readonly Arg[] _bases;
private DecoratorStatement _decorators;
private PythonVariable _variable; // Variable corresponding to the class name
private PythonVariable _modVariable; // Variable for the the __module__ (module name)
private PythonVariable _docVariable; // Variable for the __doc__ attribute
private PythonVariable _modNameVariable; // Variable for the module's __name__
private PythonVariable _classVariable; // Variable for the classes __class__ cell var on 3.x
public ClassDefinition(NameExpression/*!*/ name, Arg[] bases, Statement body) {
_name = name;
_bases = bases;
_body = body;
}
public int HeaderIndex {
get { return _headerIndex; }
set { _headerIndex = value; }
}
public override string/*!*/ Name {
get { return _name.Name ?? ""; }
}
public NameExpression/*!*/ NameExpression {
get { return _name; }
}
public IList<Arg> Bases {
get { return _bases; }
}
public override Statement Body {
get { return _body; }
}
public DecoratorStatement Decorators {
get {
return _decorators;
}
internal set {
_decorators = value;
}
}
/// <summary>
/// Gets the variable that this class definition was assigned to.
/// </summary>
public PythonVariable Variable {
get { return _variable; }
set { _variable = value; }
}
/// <summary>
/// Gets the variable reference for the specific assignment to the variable for this class definition.
/// </summary>
public PythonReference GetVariableReference(PythonAst ast) {
return GetVariableReference(this, ast);
}
internal PythonVariable ClassVariable {
get { return _classVariable; }
set { _classVariable = value; }
}
internal PythonVariable ModVariable {
get { return _modVariable; }
set { _modVariable = value; }
}
internal PythonVariable DocVariable {
get { return _docVariable; }
set { _docVariable = value; }
}
internal PythonVariable ModuleNameVariable {
get { return _modNameVariable; }
set { _modNameVariable = value; }
}
internal override bool HasLateBoundVariableSets {
get {
return base.HasLateBoundVariableSets || NeedsLocalsDictionary;
}
set {
base.HasLateBoundVariableSets = value;
}
}
internal override bool NeedsLocalContext {
get {
return true;
}
}
internal override bool ExposesLocalVariable(PythonVariable variable) {
return true;
}
internal override bool TryBindOuter(ScopeStatement from, string name, bool allowGlobals, out PythonVariable variable) {
if (name == "__class__" && _classVariable != null) {
// 3.x has a cell var called __class__ which can be bound by inner scopes
variable = _classVariable;
return true;
}
return base.TryBindOuter(from, name, allowGlobals, out variable);
}
internal override PythonVariable BindReference(PythonNameBinder binder, string name) {
PythonVariable variable;
// Python semantics: The variables bound local in the class
// scope are accessed by name - the dictionary behavior of classes
if (TryGetVariable(name, out variable)) {
// TODO: This results in doing a dictionary lookup to get/set the local,
// when it should probably be an uninitialized check / global lookup for gets
// and a direct set
if (variable.Kind == VariableKind.Global) {
AddReferencedGlobal(name);
} else if (variable.Kind == VariableKind.Local) {
return null;
}
return variable;
}
// Try to bind in outer scopes, if we have an unqualified exec we need to leave the
// variables as free for the same reason that locals are accessed by name.
for (ScopeStatement parent = Parent; parent != null; parent = parent.Parent) {
if (parent.TryBindOuter(this, name, true, out variable)) {
return variable;
}
}
return null;
}
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_decorators != null) {
_decorators.Walk(walker);
}
if (_bases != null) {
foreach (var b in _bases) {
b.Walk(walker);
}
}
if (_body != null) {
_body.Walk(walker);
}
}
walker.PostWalk(this);
}
public SourceLocation Header {
get { return GlobalParent.IndexToLocation(_headerIndex); }
}
internal override void AppendCodeStringStmt(StringBuilder res, PythonAst ast, CodeFormattingOptions format) {
if (Decorators != null) {
Decorators.AppendCodeString(res, ast, format);
}
format.ReflowComment(res, this.GetProceedingWhiteSpace(ast));
res.Append("class");
res.Append(this.GetSecondWhiteSpace(ast));
res.Append(this.GetVerbatimImage(ast) ?? Name);
if (!this.IsAltForm(ast)) {
format.Append(
res,
format.SpaceBeforeClassDeclarationParen,
" ",
"",
this.GetThirdWhiteSpace(ast)
);
res.Append('(');
}
if (Bases.Count != 0) {
ListExpression.AppendItems(
res,
ast,
format,
"",
"",
this,
this.Bases.Count,
(i, sb) => {
if(format.SpaceWithinClassDeclarationParens != null && i == 0) {
// need to remove any leading whitespace which was preserved for
// the 1st param, and then force the correct whitespace.
Bases[i].AppendCodeString(sb, ast, format, format.SpaceWithinClassDeclarationParens.Value ? " " : "");
} else {
Bases[i].AppendCodeString(sb, ast, format);
}
}
);
} else if (!this.IsAltForm(ast)) {
if (format.SpaceWithinEmptyBaseClassList != null && format.SpaceWithinEmptyBaseClassList.Value) {
res.Append(' ');
}
}
if (!this.IsAltForm(ast) && !this.IsMissingCloseGrouping(ast)) {
if (Bases.Count != 0 ||
format.SpaceWithinEmptyBaseClassList == null ||
!String.IsNullOrWhiteSpace(this.GetFourthWhiteSpace(ast))) {
format.Append(
res,
format.SpaceWithinClassDeclarationParens,
" ",
"",
this.GetFourthWhiteSpace(ast)
);
}
res.Append(')');
}
_body.AppendCodeString(res, ast, format);
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* an implementation of the AES (Rijndael)), from FIPS-197.
* <p>
* For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>.
*
* This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
* <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a>
*
* There are three levels of tradeoff of speed vs memory
* Because java has no preprocessor), they are written as three separate classes from which to choose
*
* The fastest uses 8Kbytes of static tables to precompute round calculations), 4 256 word tables for encryption
* and 4 for decryption.
*
* The middle performance version uses only one 256 word table for each), for a total of 2Kbytes),
* adding 12 rotate operations per round to compute the values contained in the other tables from
* the contents of the first
*
* The slowest version uses no static tables at all and computes the values in each round
* </p>
* <p>
* This file contains the fast version with 8Kbytes of static tables for round precomputation
* </p>
*/
public class AesFastEngine
: IBlockCipher
{
// The S box
private static readonly byte[] S =
{
99, 124, 119, 123, 242, 107, 111, 197,
48, 1, 103, 43, 254, 215, 171, 118,
202, 130, 201, 125, 250, 89, 71, 240,
173, 212, 162, 175, 156, 164, 114, 192,
183, 253, 147, 38, 54, 63, 247, 204,
52, 165, 229, 241, 113, 216, 49, 21,
4, 199, 35, 195, 24, 150, 5, 154,
7, 18, 128, 226, 235, 39, 178, 117,
9, 131, 44, 26, 27, 110, 90, 160,
82, 59, 214, 179, 41, 227, 47, 132,
83, 209, 0, 237, 32, 252, 177, 91,
106, 203, 190, 57, 74, 76, 88, 207,
208, 239, 170, 251, 67, 77, 51, 133,
69, 249, 2, 127, 80, 60, 159, 168,
81, 163, 64, 143, 146, 157, 56, 245,
188, 182, 218, 33, 16, 255, 243, 210,
205, 12, 19, 236, 95, 151, 68, 23,
196, 167, 126, 61, 100, 93, 25, 115,
96, 129, 79, 220, 34, 42, 144, 136,
70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92,
194, 211, 172, 98, 145, 149, 228, 121,
231, 200, 55, 109, 141, 213, 78, 169,
108, 86, 244, 234, 101, 122, 174, 8,
186, 120, 37, 46, 28, 166, 180, 198,
232, 221, 116, 31, 75, 189, 139, 138,
112, 62, 181, 102, 72, 3, 246, 14,
97, 53, 87, 185, 134, 193, 29, 158,
225, 248, 152, 17, 105, 217, 142, 148,
155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104,
65, 153, 45, 15, 176, 84, 187, 22,
};
// The inverse S-box
private static readonly byte[] Si =
{
82, 9, 106, 213, 48, 54, 165, 56,
191, 64, 163, 158, 129, 243, 215, 251,
124, 227, 57, 130, 155, 47, 255, 135,
52, 142, 67, 68, 196, 222, 233, 203,
84, 123, 148, 50, 166, 194, 35, 61,
238, 76, 149, 11, 66, 250, 195, 78,
8, 46, 161, 102, 40, 217, 36, 178,
118, 91, 162, 73, 109, 139, 209, 37,
114, 248, 246, 100, 134, 104, 152, 22,
212, 164, 92, 204, 93, 101, 182, 146,
108, 112, 72, 80, 253, 237, 185, 218,
94, 21, 70, 87, 167, 141, 157, 132,
144, 216, 171, 0, 140, 188, 211, 10,
247, 228, 88, 5, 184, 179, 69, 6,
208, 44, 30, 143, 202, 63, 15, 2,
193, 175, 189, 3, 1, 19, 138, 107,
58, 145, 17, 65, 79, 103, 220, 234,
151, 242, 207, 206, 240, 180, 230, 115,
150, 172, 116, 34, 231, 173, 53, 133,
226, 249, 55, 232, 28, 117, 223, 110,
71, 241, 26, 113, 29, 41, 197, 137,
111, 183, 98, 14, 170, 24, 190, 27,
252, 86, 62, 75, 198, 210, 121, 32,
154, 219, 192, 254, 120, 205, 90, 244,
31, 221, 168, 51, 136, 7, 199, 49,
177, 18, 16, 89, 39, 128, 236, 95,
96, 81, 127, 169, 25, 181, 74, 13,
45, 229, 122, 159, 147, 201, 156, 239,
160, 224, 59, 77, 174, 42, 245, 176,
200, 235, 187, 60, 131, 83, 153, 97,
23, 43, 4, 126, 186, 119, 214, 38,
225, 105, 20, 99, 85, 33, 12, 125,
};
// vector used in calculating key schedule (powers of x in GF(256))
private static readonly byte[] rcon =
{
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91
};
// precomputation tables of calculations for rounds
private static readonly uint[] T0 =
{
0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff,
0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102,
0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d,
0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa,
0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41,
0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453,
0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d,
0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83,
0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2,
0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795,
0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a,
0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df,
0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912,
0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc,
0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7,
0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413,
0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040,
0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d,
0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0,
0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed,
0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a,
0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78,
0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080,
0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1,
0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020,
0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18,
0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488,
0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a,
0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0,
0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54,
0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b,
0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad,
0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992,
0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd,
0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3,
0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda,
0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8,
0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4,
0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a,
0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697,
0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96,
0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c,
0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7,
0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969,
0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9,
0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9,
0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715,
0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5,
0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65,
0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929,
0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d,
0x3a16162c
};
private static readonly uint[] T1 =
{
0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d,
0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203,
0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6,
0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87,
0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec,
0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7,
0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae,
0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f,
0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293,
0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552,
0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f,
0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d,
0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b,
0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2,
0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761,
0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397,
0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060,
0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46,
0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8,
0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16,
0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf,
0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844,
0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0,
0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104,
0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030,
0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814,
0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc,
0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47,
0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0,
0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e,
0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3,
0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76,
0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db,
0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e,
0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337,
0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7,
0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4,
0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e,
0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f,
0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751,
0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd,
0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42,
0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701,
0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0,
0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938,
0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970,
0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592,
0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a,
0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da,
0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0,
0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6,
0x16162c3a
};
private static readonly uint[] T2 =
{
0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2,
0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301,
0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab,
0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d,
0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad,
0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4,
0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93,
0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc,
0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371,
0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7,
0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05,
0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2,
0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09,
0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e,
0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6,
0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784,
0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020,
0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb,
0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858,
0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb,
0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45,
0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c,
0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040,
0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5,
0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010,
0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c,
0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44,
0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d,
0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060,
0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a,
0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8,
0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db,
0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49,
0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3,
0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4,
0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d,
0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c,
0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a,
0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25,
0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6,
0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b,
0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e,
0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6,
0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9,
0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1,
0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9,
0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287,
0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf,
0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf,
0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099,
0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb,
0x162c3a16
};
private static readonly uint[] T3 =
{
0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2,
0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101,
0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab,
0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d,
0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad,
0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4,
0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393,
0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc,
0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171,
0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7,
0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505,
0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2,
0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909,
0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e,
0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6,
0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484,
0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020,
0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb,
0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858,
0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb,
0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545,
0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c,
0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040,
0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5,
0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010,
0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c,
0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444,
0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d,
0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060,
0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a,
0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8,
0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb,
0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949,
0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3,
0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4,
0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d,
0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c,
0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a,
0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525,
0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6,
0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b,
0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e,
0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6,
0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9,
0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1,
0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9,
0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787,
0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf,
0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf,
0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999,
0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb,
0x2c3a1616
};
private static readonly uint[] Tinv0 =
{
0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b,
0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad,
0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526,
0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d,
0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03,
0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458,
0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899,
0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d,
0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1,
0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f,
0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3,
0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3,
0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a,
0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506,
0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05,
0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd,
0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491,
0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6,
0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7,
0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000,
0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd,
0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68,
0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4,
0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c,
0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e,
0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af,
0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644,
0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8,
0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85,
0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc,
0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411,
0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322,
0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6,
0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850,
0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e,
0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf,
0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd,
0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa,
0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea,
0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235,
0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1,
0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43,
0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1,
0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb,
0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a,
0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7,
0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418,
0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478,
0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16,
0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08,
0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48,
0x4257b8d0
};
private static readonly uint[] Tinv1 =
{
0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb,
0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6,
0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680,
0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1,
0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7,
0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3,
0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b,
0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4,
0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0,
0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19,
0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357,
0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5,
0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b,
0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5,
0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532,
0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51,
0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5,
0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697,
0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738,
0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000,
0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb,
0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821,
0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2,
0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16,
0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b,
0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c,
0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5,
0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863,
0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d,
0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3,
0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa,
0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef,
0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf,
0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d,
0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e,
0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3,
0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09,
0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e,
0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4,
0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0,
0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a,
0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d,
0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8,
0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e,
0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c,
0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735,
0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879,
0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886,
0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672,
0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de,
0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874,
0x57b8d042
};
private static readonly uint[] Tinv2 =
{
0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b,
0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d,
0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044,
0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0,
0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f,
0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321,
0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e,
0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a,
0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077,
0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd,
0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f,
0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508,
0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c,
0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be,
0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1,
0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110,
0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d,
0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9,
0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b,
0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000,
0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff,
0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6,
0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296,
0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a,
0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d,
0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07,
0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b,
0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1,
0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24,
0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330,
0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48,
0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90,
0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81,
0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92,
0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7,
0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312,
0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978,
0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6,
0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409,
0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066,
0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98,
0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0,
0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f,
0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41,
0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61,
0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9,
0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce,
0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db,
0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3,
0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3,
0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c,
0xb8d04257
};
private static readonly uint[] Tinv3 =
{
0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab,
0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76,
0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435,
0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe,
0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f,
0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174,
0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58,
0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace,
0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764,
0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45,
0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f,
0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837,
0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf,
0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05,
0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a,
0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e,
0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54,
0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd,
0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19,
0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000,
0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e,
0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c,
0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee,
0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12,
0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09,
0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775,
0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66,
0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4,
0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a,
0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2,
0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894,
0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033,
0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5,
0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278,
0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739,
0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225,
0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826,
0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff,
0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f,
0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2,
0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804,
0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef,
0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c,
0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b,
0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7,
0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961,
0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14,
0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44,
0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d,
0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c,
0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c,
0xd04257b8
};
private uint Shift(
uint r,
int shift)
{
return (r >> shift) | (r << (32 - shift));
}
/* multiply four bytes in GF(2^8) by 'x' {02} in parallel */
private const uint m1 = 0x80808080;
private const uint m2 = 0x7f7f7f7f;
private const uint m3 = 0x0000001b;
private uint FFmulX(
uint x)
{
return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3);
}
/*
The following defines provide alternative definitions of FFmulX that might
give improved performance if a fast 32-bit multiply is not available.
private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); }
private static final int m4 = 0x1b1b1b1b;
private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); }
*/
private uint Inv_Mcol(
uint x) {
uint f2 = FFmulX(x);
uint f4 = FFmulX(f2);
uint f8 = FFmulX(f4);
uint f9 = x ^ f8;
return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24);
}
private uint SubWord(
uint x)
{
return (uint)S[x&255]
| (((uint)S[(x>>8)&255]) << 8)
| (((uint)S[(x>>16)&255]) << 16)
| (((uint)S[(x>>24)&255]) << 24);
}
/**
* Calculate the necessary round keys
* The number of calculations depends on key size and block size
* AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
* This code is written assuming those are the only possible values
*/
private uint[,] GenerateWorkingKey(
byte[] key,
bool forEncryption)
{
int KC = key.Length / 4; // key length in words
if (((KC != 4) && (KC != 6) && (KC != 8)) || ((KC * 4) != key.Length))
throw new ArgumentException("Key length not 128/192/256 bits.");
ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes
uint[,] W = new uint[ROUNDS+1,4]; // 4 words in a block
//
// copy the key into the round key array
//
int t = 0;
for (int i = 0; i < key.Length; t++)
{
W[t >> 2,t & 3] = Pack.LE_To_UInt32(key, i);
i+=4;
}
//
// while not enough round key material calculated
// calculate new values
//
int k = (ROUNDS + 1) << 2;
for (int i = KC; (i < k); i++)
{
uint temp = W[(i-1)>>2,(i-1)&3];
if ((i % KC) == 0) {
temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC)-1];
} else if ((KC > 6) && ((i % KC) == 4)) {
temp = SubWord(temp);
}
W[i>>2,i&3] = W[(i - KC)>>2,(i-KC)&3] ^ temp;
}
if (!forEncryption)
{
for (int j = 1; j < ROUNDS; j++)
{
for (int i = 0; i < 4; i++)
{
W[j,i] = Inv_Mcol(W[j,i]);
}
}
}
return W;
}
private int ROUNDS;
private uint[,] WorkingKey;
private uint C0, C1, C2, C3;
private bool forEncryption;
private const int BLOCK_SIZE = 16;
/**
* default constructor - 128 bit block size.
*/
public AesFastEngine()
{
}
/**
* initialise an AES cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().ToString());
WorkingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey(), forEncryption);
this.forEncryption = forEncryption;
}
public string AlgorithmName
{
get { return "AES"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return BLOCK_SIZE;
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (WorkingKey == null)
{
throw new InvalidOperationException("AES engine not initialised");
}
if ((inOff + (32 / 2)) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + (32 / 2)) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
UnPackBlock(input, inOff);
if (forEncryption)
{
EncryptBlock(WorkingKey);
}
else
{
DecryptBlock(WorkingKey);
}
PackBlock(output, outOff);
return BLOCK_SIZE;
}
public void Reset()
{
}
private void UnPackBlock(
byte[] bytes,
int off)
{
C0 = Pack.LE_To_UInt32(bytes, off);
C1 = Pack.LE_To_UInt32(bytes, off + 4);
C2 = Pack.LE_To_UInt32(bytes, off + 8);
C3 = Pack.LE_To_UInt32(bytes, off + 12);
}
private void PackBlock(
byte[] bytes,
int off)
{
Pack.UInt32_To_LE(C0, bytes, off);
Pack.UInt32_To_LE(C1, bytes, off + 4);
Pack.UInt32_To_LE(C2, bytes, off + 8);
Pack.UInt32_To_LE(C3, bytes, off + 12);
}
private void EncryptBlock(
uint[,] KW)
{
int r;
uint r0, r1, r2, r3;
C0 ^= KW[0,0];
C1 ^= KW[0,1];
C2 ^= KW[0,2];
C3 ^= KW[0,3];
for (r = 1; r < ROUNDS - 1;)
{
r0 = T0[C0&255] ^ T1[(C1>>8)&255] ^ T2[(C2>>16)&255] ^ T3[C3>>24] ^ KW[r,0];
r1 = T0[C1&255] ^ T1[(C2>>8)&255] ^ T2[(C3>>16)&255] ^ T3[C0>>24] ^ KW[r,1];
r2 = T0[C2&255] ^ T1[(C3>>8)&255] ^ T2[(C0>>16)&255] ^ T3[C1>>24] ^ KW[r,2];
r3 = T0[C3&255] ^ T1[(C0>>8)&255] ^ T2[(C1>>16)&255] ^ T3[C2>>24] ^ KW[r++,3];
C0 = T0[r0&255] ^ T1[(r1>>8)&255] ^ T2[(r2>>16)&255] ^ T3[r3>>24] ^ KW[r,0];
C1 = T0[r1&255] ^ T1[(r2>>8)&255] ^ T2[(r3>>16)&255] ^ T3[r0>>24] ^ KW[r,1];
C2 = T0[r2&255] ^ T1[(r3>>8)&255] ^ T2[(r0>>16)&255] ^ T3[r1>>24] ^ KW[r,2];
C3 = T0[r3&255] ^ T1[(r0>>8)&255] ^ T2[(r1>>16)&255] ^ T3[r2>>24] ^ KW[r++,3];
}
r0 = T0[C0&255] ^ T1[(C1>>8)&255] ^ T2[(C2>>16)&255] ^ T3[C3>>24] ^ KW[r,0];
r1 = T0[C1&255] ^ T1[(C2>>8)&255] ^ T2[(C3>>16)&255] ^ T3[C0>>24] ^ KW[r,1];
r2 = T0[C2&255] ^ T1[(C3>>8)&255] ^ T2[(C0>>16)&255] ^ T3[C1>>24] ^ KW[r,2];
r3 = T0[C3&255] ^ T1[(C0>>8)&255] ^ T2[(C1>>16)&255] ^ T3[C2>>24] ^ KW[r++,3];
// the final round's table is a simple function of S so we don't use a whole other four tables for it
C0 = (uint)S[r0&255] ^ (((uint)S[(r1>>8)&255])<<8) ^ (((uint)S[(r2>>16)&255])<<16) ^ (((uint)S[r3>>24])<<24) ^ KW[r,0];
C1 = (uint)S[r1&255] ^ (((uint)S[(r2>>8)&255])<<8) ^ (((uint)S[(r3>>16)&255])<<16) ^ (((uint)S[r0>>24])<<24) ^ KW[r,1];
C2 = (uint)S[r2&255] ^ (((uint)S[(r3>>8)&255])<<8) ^ (((uint)S[(r0>>16)&255])<<16) ^ (((uint)S[r1>>24])<<24) ^ KW[r,2];
C3 = (uint)S[r3&255] ^ (((uint)S[(r0>>8)&255])<<8) ^ (((uint)S[(r1>>16)&255])<<16) ^ (((uint)S[r2>>24])<<24) ^ KW[r,3];
}
private void DecryptBlock(
uint[,] KW)
{
int r;
uint r0, r1, r2, r3;
C0 ^= KW[ROUNDS,0];
C1 ^= KW[ROUNDS,1];
C2 ^= KW[ROUNDS,2];
C3 ^= KW[ROUNDS,3];
for (r = ROUNDS-1; r>1;) {
r0 = Tinv0[C0&255] ^ Tinv1[(C3>>8)&255] ^ Tinv2[(C2>>16)&255] ^ Tinv3[C1>>24] ^ KW[r,0];
r1 = Tinv0[C1&255] ^ Tinv1[(C0>>8)&255] ^ Tinv2[(C3>>16)&255] ^ Tinv3[C2>>24] ^ KW[r,1];
r2 = Tinv0[C2&255] ^ Tinv1[(C1>>8)&255] ^ Tinv2[(C0>>16)&255] ^ Tinv3[C3>>24] ^ KW[r,2];
r3 = Tinv0[C3&255] ^ Tinv1[(C2>>8)&255] ^ Tinv2[(C1>>16)&255] ^ Tinv3[C0>>24] ^ KW[r--,3];
C0 = Tinv0[r0&255] ^ Tinv1[(r3>>8)&255] ^ Tinv2[(r2>>16)&255] ^ Tinv3[r1>>24] ^ KW[r,0];
C1 = Tinv0[r1&255] ^ Tinv1[(r0>>8)&255] ^ Tinv2[(r3>>16)&255] ^ Tinv3[r2>>24] ^ KW[r,1];
C2 = Tinv0[r2&255] ^ Tinv1[(r1>>8)&255] ^ Tinv2[(r0>>16)&255] ^ Tinv3[r3>>24] ^ KW[r,2];
C3 = Tinv0[r3&255] ^ Tinv1[(r2>>8)&255] ^ Tinv2[(r1>>16)&255] ^ Tinv3[r0>>24] ^ KW[r--,3];
}
r0 = Tinv0[C0&255] ^ Tinv1[(C3>>8)&255] ^ Tinv2[(C2>>16)&255] ^ Tinv3[C1>>24] ^ KW[r,0];
r1 = Tinv0[C1&255] ^ Tinv1[(C0>>8)&255] ^ Tinv2[(C3>>16)&255] ^ Tinv3[C2>>24] ^ KW[r,1];
r2 = Tinv0[C2&255] ^ Tinv1[(C1>>8)&255] ^ Tinv2[(C0>>16)&255] ^ Tinv3[C3>>24] ^ KW[r,2];
r3 = Tinv0[C3&255] ^ Tinv1[(C2>>8)&255] ^ Tinv2[(C1>>16)&255] ^ Tinv3[C0>>24] ^ KW[r,3];
// the final round's table is a simple function of Si so we don't use a whole other four tables for it
C0 = (uint)Si[r0&255] ^ (((uint)Si[(r3>>8)&255])<<8) ^ (((uint)Si[(r2>>16)&255])<<16) ^ (((uint)Si[r1>>24])<<24) ^ KW[0,0];
C1 = (uint)Si[r1&255] ^ (((uint)Si[(r0>>8)&255])<<8) ^ (((uint)Si[(r3>>16)&255])<<16) ^ (((uint)Si[r2>>24])<<24) ^ KW[0,1];
C2 = (uint)Si[r2&255] ^ (((uint)Si[(r1>>8)&255])<<8) ^ (((uint)Si[(r0>>16)&255])<<16) ^ (((uint)Si[r3>>24])<<24) ^ KW[0,2];
C3 = (uint)Si[r3&255] ^ (((uint)Si[(r2>>8)&255])<<8) ^ (((uint)Si[(r1>>16)&255])<<16) ^ (((uint)Si[r0>>24])<<24) ^ KW[0,3];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.