context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Collections.Immutable;
using System.Linq;
using System.Runtime.InteropServices;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.NetCore.Analyzers.InteropServices
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class PInvokeDiagnosticAnalyzer : DiagnosticAnalyzer
{
public const string RuleCA1401Id = "CA1401";
public const string RuleCA2101Id = "CA2101";
private static readonly LocalizableString s_localizableTitleCA1401 = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PInvokesShouldNotBeVisibleTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableMessageCA1401 = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PInvokesShouldNotBeVisibleMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableDescriptionCA1401 = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PInvokesShouldNotBeVisibleDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor RuleCA1401 = DiagnosticDescriptorHelper.Create(RuleCA1401Id,
s_localizableTitleCA1401,
s_localizableMessageCA1401,
DiagnosticCategory.Interoperability,
RuleLevel.IdeSuggestion,
description: s_localizableDescriptionCA1401,
isPortedFxCopRule: true,
isDataflowRule: false);
private static readonly LocalizableString s_localizableMessageAndTitleCA2101 = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.SpecifyMarshalingForPInvokeStringArgumentsTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableDescriptionCA2101 = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.SpecifyMarshalingForPInvokeStringArgumentsDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor RuleCA2101 = DiagnosticDescriptorHelper.Create(RuleCA2101Id,
s_localizableMessageAndTitleCA2101,
s_localizableMessageAndTitleCA2101,
DiagnosticCategory.Globalization,
RuleLevel.BuildWarningCandidate,
description: s_localizableDescriptionCA2101,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(RuleCA1401, RuleCA2101);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(
(context) =>
{
INamedTypeSymbol? dllImportType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute);
if (dllImportType == null)
{
return;
}
INamedTypeSymbol? marshalAsType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute);
if (marshalAsType == null)
{
return;
}
INamedTypeSymbol? stringBuilderType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextStringBuilder);
if (stringBuilderType == null)
{
return;
}
INamedTypeSymbol? unmanagedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesUnmanagedType);
if (unmanagedType == null)
{
return;
}
context.RegisterSymbolAction(new SymbolAnalyzer(dllImportType, marshalAsType, stringBuilderType, unmanagedType).AnalyzeSymbol, SymbolKind.Method);
});
}
private sealed class SymbolAnalyzer
{
private readonly INamedTypeSymbol _dllImportType;
private readonly INamedTypeSymbol _marshalAsType;
private readonly INamedTypeSymbol _stringBuilderType;
private readonly INamedTypeSymbol _unmanagedType;
public SymbolAnalyzer(
INamedTypeSymbol dllImportType,
INamedTypeSymbol marshalAsType,
INamedTypeSymbol stringBuilderType,
INamedTypeSymbol unmanagedType)
{
_dllImportType = dllImportType;
_marshalAsType = marshalAsType;
_stringBuilderType = stringBuilderType;
_unmanagedType = unmanagedType;
}
public void AnalyzeSymbol(SymbolAnalysisContext context)
{
var methodSymbol = (IMethodSymbol)context.Symbol;
if (methodSymbol == null)
{
return;
}
DllImportData dllImportData = methodSymbol.GetDllImportData();
if (dllImportData == null)
{
return;
}
AttributeData dllAttribute = methodSymbol.GetAttributes().FirstOrDefault(attr => attr.AttributeClass.Equals(_dllImportType));
Location defaultLocation = dllAttribute == null ? methodSymbol.Locations.FirstOrDefault() : GetAttributeLocation(dllAttribute);
// CA1401 - PInvoke methods should not be visible
if (methodSymbol.IsExternallyVisible())
{
context.ReportDiagnostic(context.Symbol.CreateDiagnostic(RuleCA1401, methodSymbol.Name));
}
// CA2101 - Specify marshalling for PInvoke string arguments
if (dllImportData.BestFitMapping != false)
{
bool appliedCA2101ToMethod = false;
foreach (IParameterSymbol parameter in methodSymbol.Parameters)
{
if (parameter.Type.SpecialType == SpecialType.System_String || parameter.Type.Equals(_stringBuilderType))
{
AttributeData marshalAsAttribute = parameter.GetAttributes().FirstOrDefault(attr => attr.AttributeClass.Equals(_marshalAsType));
CharSet? charSet = marshalAsAttribute == null
? dllImportData.CharacterSet
: MarshalingToCharSet(GetParameterMarshaling(marshalAsAttribute));
// only unicode marshaling is considered safe
if (charSet != CharSet.Unicode)
{
if (marshalAsAttribute != null)
{
// track the diagnostic on the [MarshalAs] attribute
Location marshalAsLocation = GetAttributeLocation(marshalAsAttribute);
context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, marshalAsLocation));
}
else if (!appliedCA2101ToMethod)
{
// track the diagnostic on the [DllImport] attribute
appliedCA2101ToMethod = true;
context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, defaultLocation));
}
}
}
}
// only unicode marshaling is considered safe, but only check this if we haven't already flagged the attribute
if (!appliedCA2101ToMethod && dllImportData.CharacterSet != CharSet.Unicode &&
(methodSymbol.ReturnType.SpecialType == SpecialType.System_String || methodSymbol.ReturnType.Equals(_stringBuilderType)))
{
context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, defaultLocation));
}
}
}
private UnmanagedType? GetParameterMarshaling(AttributeData attributeData)
{
if (!attributeData.ConstructorArguments.IsEmpty)
{
TypedConstant argument = attributeData.ConstructorArguments.First();
if (argument.Type.Equals(_unmanagedType))
{
return (UnmanagedType)argument.Value;
}
else if (argument.Type.SpecialType == SpecialType.System_Int16)
{
return (UnmanagedType)(short)argument.Value;
}
}
return null;
}
private static CharSet? MarshalingToCharSet(UnmanagedType? type)
{
if (type == null)
{
return null;
}
#pragma warning disable CS0618 // Type or member is obsolete
switch (type)
{
case UnmanagedType.AnsiBStr:
case UnmanagedType.LPStr:
case UnmanagedType.VBByRefStr:
return CharSet.Ansi;
case UnmanagedType.BStr:
case UnmanagedType.LPWStr:
return CharSet.Unicode;
case UnmanagedType.ByValTStr:
case UnmanagedType.LPTStr:
case UnmanagedType.TBStr:
default:
// CharSet.Auto and CharSet.None are not available in the portable
// profiles. We are not interested in those values for our analysis and so simply
// return null
return null;
}
#pragma warning restore CS0618 // Type or member is obsolete
}
private static Location GetAttributeLocation(AttributeData attributeData)
{
return attributeData.ApplicationSyntaxReference.SyntaxTree.GetLocation(attributeData.ApplicationSyntaxReference.Span);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection.Metadata
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public unsafe struct BlobReader
{
/// <summary>An array containing the '\0' character.</summary>
private static readonly char[] s_nullCharArray = new char[1] { '\0' };
internal const int InvalidCompressedInteger = int.MaxValue;
private readonly MemoryBlock _block;
// Points right behind the last byte of the block.
private readonly byte* _endPointer;
private byte* _currentPointer;
/// <summary>
/// Creates a reader of the specified memory block.
/// </summary>
/// <param name="buffer">Pointer to the start of the memory block.</param>
/// <param name="length">Length in bytes of the memory block.</param>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null and <paramref name="length"/> is greater than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is negative.</exception>
/// <exception cref="PlatformNotSupportedException">The current platform is not little-endian.</exception>
public BlobReader(byte* buffer, int length)
: this(MemoryBlock.CreateChecked(buffer, length))
{
}
internal BlobReader(MemoryBlock block)
{
Debug.Assert(block.Length >= 0 && (block.Pointer != null || block.Length == 0));
_block = block;
_currentPointer = block.Pointer;
_endPointer = block.Pointer + block.Length;
}
internal string GetDebuggerDisplay()
{
if (_block.Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = _block.GetDebuggerDisplay(out displayedBytes);
if (this.Offset < displayedBytes)
{
display = display.Insert(this.Offset * 3, "*");
}
else if (displayedBytes == _block.Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
#region Offset, Skipping, Marking, Alignment, Bounds Checking
/// <summary>
/// Pointer to the byte at the start of the underlying memory block.
/// </summary>
public byte* StartPointer => _block.Pointer;
/// <summary>
/// Pointer to the byte at the current position of the reader.
/// </summary>
public byte* CurrentPointer => _currentPointer;
/// <summary>
/// The total length of the underlying memory block.
/// </summary>
public int Length => _block.Length;
/// <summary>
/// Gets or sets the offset from start of the blob to the current position.
/// </summary>
/// <exception cref="BadImageFormatException">Offset is set outside the bounds of underlying reader.</exception>
public int Offset
{
get
{
return (int)(_currentPointer - _block.Pointer);
}
set
{
if (unchecked((uint)value) > (uint)_block.Length)
{
Throw.OutOfBounds();
}
_currentPointer = _block.Pointer + value;
}
}
/// <summary>
/// Bytes remaining from current position to end of underlying memory block.
/// </summary>
public int RemainingBytes => (int)(_endPointer - _currentPointer);
/// <summary>
/// Repositions the reader to the start of the underlying memory block.
/// </summary>
public void Reset()
{
_currentPointer = _block.Pointer;
}
/// <summary>
/// Repositions the reader forward by the number of bytes required to satisfy the given alignment.
/// </summary>
public void Align(byte alignment)
{
if (!TryAlign(alignment))
{
Throw.OutOfBounds();
}
}
internal bool TryAlign(byte alignment)
{
int remainder = this.Offset & (alignment - 1);
Debug.Assert((alignment & (alignment - 1)) == 0, "Alignment must be a power of two.");
Debug.Assert(remainder >= 0 && remainder < alignment);
if (remainder != 0)
{
int bytesToSkip = alignment - remainder;
if (bytesToSkip > RemainingBytes)
{
return false;
}
_currentPointer += bytesToSkip;
}
return true;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(_currentPointer + offset, length);
}
#endregion
#region Bounds Checking
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)(_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int byteCount)
{
if (unchecked((uint)byteCount) > (_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance(int length)
{
byte* p = _currentPointer;
if (unchecked((uint)length) > (uint)(_endPointer - p))
{
Throw.OutOfBounds();
}
_currentPointer = p + length;
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance1()
{
byte* p = _currentPointer;
if (p == _endPointer)
{
Throw.OutOfBounds();
}
_currentPointer = p + 1;
return p;
}
#endregion
#region Read Methods
public bool ReadBoolean()
{
// It's not clear from the ECMA spec what exactly is the encoding of Boolean.
// Some metadata writers encode "true" as 0xff, others as 1. So we treat all non-zero values as "true".
//
// We propose to clarify and relax the current wording in the spec as follows:
//
// Chapter II.16.2 "Field init metadata"
// ... bool '(' true | false ')' Boolean value stored in a single byte, 0 represents false, any non-zero value represents true ...
//
// Chapter 23.3 "Custom attributes"
// ... A bool is a single byte with value 0 representing false and any non-zero value representing true ...
return ReadByte() != 0;
}
public sbyte ReadSByte()
{
return *(sbyte*)GetCurrentPointerAndAdvance1();
}
public byte ReadByte()
{
return *(byte*)GetCurrentPointerAndAdvance1();
}
public char ReadChar()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(char));
return (char)(ptr[0] + (ptr[1] << 8));
}
}
public short ReadInt16()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(short));
return (short)(ptr[0] + (ptr[1] << 8));
}
}
public ushort ReadUInt16()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(ushort));
return (ushort)(ptr[0] + (ptr[1] << 8));
}
}
public int ReadInt32()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(int));
return (int)(ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24));
}
}
public uint ReadUInt32()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(uint));
return (uint)(ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24));
}
}
public long ReadInt64()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(long));
uint lo = (uint)(ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24));
uint hi = (uint)(ptr[4] + (ptr[5] << 8) + (ptr[6] << 16) + (ptr[7] << 24));
return (long)(lo + ((ulong)hi << 32));
}
}
public ulong ReadUInt64()
{
return unchecked((ulong)ReadInt64());
}
public float ReadSingle()
{
int val = ReadInt32();
return *(float*)&val;
}
public double ReadDouble()
{
long val = ReadInt64();
return *(double*)&val;
}
public Guid ReadGuid()
{
const int size = 16;
byte * ptr = GetCurrentPointerAndAdvance(size);
if (BitConverter.IsLittleEndian)
{
return *(Guid*)ptr;
}
else
{
unchecked
{
return new Guid(
(int)(ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24)),
(short)(ptr[4] | (ptr[5] << 8)),
(short)(ptr[6] | (ptr[7] << 8)),
ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]);
}
}
}
/// <summary>
/// Reads <see cref="decimal"/> number.
/// </summary>
/// <remarks>
/// Decimal number is encoded in 13 bytes as follows:
/// - byte 0: highest bit indicates sign (1 for negative, 0 for non-negative); the remaining 7 bits encode scale
/// - bytes 1..12: 96-bit unsigned integer in little endian encoding.
/// </remarks>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid <see cref="decimal"/> number.</exception>
public decimal ReadDecimal()
{
byte* ptr = GetCurrentPointerAndAdvance(13);
byte scale = (byte)(*ptr & 0x7f);
if (scale > 28)
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
unchecked
{
return new decimal(
(int)(ptr[1] | (ptr[2] << 8) | (ptr[3] << 16) | (ptr[4] << 24)),
(int)(ptr[5] | (ptr[6] << 8) | (ptr[7] << 16) | (ptr[8] << 24)),
(int)(ptr[9] | (ptr[10] << 8) | (ptr[11] << 16) | (ptr[12] << 24)),
isNegative: (*ptr & 0x80) != 0,
scale: scale);
}
}
public DateTime ReadDateTime()
{
return new DateTime(ReadInt64());
}
public SignatureHeader ReadSignatureHeader()
{
return new SignatureHeader(ReadByte());
}
/// <summary>
/// Finds specified byte in the blob following the current position.
/// </summary>
/// <returns>
/// Index relative to the current position, or -1 if the byte is not found in the blob following the current position.
/// </returns>
/// <remarks>
/// Doesn't change the current position.
/// </remarks>
public int IndexOf(byte value)
{
int start = Offset;
int absoluteIndex = _block.IndexOfUnchecked(value, start);
return (absoluteIndex >= 0) ? absoluteIndex - start : -1;
}
/// <summary>
/// Reads UTF8 encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF8(int byteCount)
{
string s = _block.PeekUtf8(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads UTF16 (little-endian) encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF16(int byteCount)
{
string s = _block.PeekUtf16(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads bytes starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The byte array.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public byte[] ReadBytes(int byteCount)
{
byte[] bytes = _block.PeekBytes(this.Offset, byteCount);
_currentPointer += byteCount;
return bytes;
}
/// <summary>
/// Reads bytes starting at the current position in to the given buffer at the given offset;
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <param name="buffer">The destination buffer the bytes read will be written.</param>
/// <param name="bufferOffset">The offset in the destination buffer where the bytes read will be written.</param>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public void ReadBytes(int byteCount, byte[] buffer, int bufferOffset)
{
Marshal.Copy((IntPtr)GetCurrentPointerAndAdvance(byteCount), buffer, bufferOffset, byteCount);
}
internal string ReadUtf8NullTerminated()
{
int bytesRead;
string value = _block.PeekUtf8NullTerminated(this.Offset, null, MetadataStringDecoder.DefaultUTF8, out bytesRead, '\0');
_currentPointer += bytesRead;
return value;
}
private int ReadCompressedIntegerOrInvalid()
{
int bytesRead;
int value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
_currentPointer += bytesRead;
return value;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedInteger(out int value)
{
value = ReadCompressedIntegerOrInvalid();
return value != InvalidCompressedInteger;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedInteger()
{
int value;
if (!TryReadCompressedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedSignedInteger(out int value)
{
int bytesRead;
value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
if (value == InvalidCompressedInteger)
{
return false;
}
bool signExtend = (value & 0x1) != 0;
value >>= 1;
if (signExtend)
{
switch (bytesRead)
{
case 1:
value |= unchecked((int)0xffffffc0);
break;
case 2:
value |= unchecked((int)0xffffe000);
break;
default:
Debug.Assert(bytesRead == 4);
value |= unchecked((int)0xf0000000);
break;
}
}
_currentPointer += bytesRead;
return true;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedSignedInteger()
{
int value;
if (!TryReadCompressedSignedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads type code encoded in a serialized custom attribute value.
/// </summary>
/// <returns><see cref="SerializationTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SerializationTypeCode ReadSerializationTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
if (value > byte.MaxValue)
{
return SerializationTypeCode.Invalid;
}
return unchecked((SerializationTypeCode)value);
}
/// <summary>
/// Reads type code encoded in a signature.
/// </summary>
/// <returns><see cref="SignatureTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SignatureTypeCode ReadSignatureTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
switch (value)
{
case (int)CorElementType.ELEMENT_TYPE_CLASS:
case (int)CorElementType.ELEMENT_TYPE_VALUETYPE:
return SignatureTypeCode.TypeHandle;
default:
if (value > byte.MaxValue)
{
return SignatureTypeCode.Invalid;
}
return unchecked((SignatureTypeCode)value);
}
}
/// <summary>
/// Reads a string encoded as a compressed integer containing its length followed by
/// its contents in UTF8. Null strings are encoded as a single 0xFF byte.
/// </summary>
/// <remarks>Defined as a 'SerString' in the ECMA CLI specification.</remarks>
/// <returns>String value or null.</returns>
/// <exception cref="BadImageFormatException">If the encoding is invalid.</exception>
public string ReadSerializedString()
{
int length;
if (TryReadCompressedInteger(out length))
{
// Removal of trailing '\0' is a departure from the spec, but required
// for compatibility with legacy compilers.
return ReadUTF8(length).TrimEnd(s_nullCharArray);
}
if (ReadByte() != 0xFF)
{
Throw.InvalidSerializedString();
}
return null;
}
/// <summary>
/// Reads a type handle encoded in a signature as TypeDefOrRefOrSpecEncoded (see ECMA-335 II.23.2.8).
/// </summary>
/// <returns>The handle or nil if the encoding is invalid.</returns>
public EntityHandle ReadTypeHandle()
{
uint value = (uint)ReadCompressedIntegerOrInvalid();
uint tokenType = s_corEncodeTokenArray[value & 0x3];
if (value == InvalidCompressedInteger || tokenType == 0)
{
return default(EntityHandle);
}
return new EntityHandle(tokenType | (value >> 2));
}
private static readonly uint[] s_corEncodeTokenArray = new uint[] { TokenTypeIds.TypeDef, TokenTypeIds.TypeRef, TokenTypeIds.TypeSpec, 0 };
/// <summary>
/// Reads a #Blob heap handle encoded as a compressed integer.
/// </summary>
/// <remarks>
/// Blobs that contain references to other blobs are used in Portable PDB format, for example <see cref="Document.Name"/>.
/// </remarks>
public BlobHandle ReadBlobHandle()
{
return BlobHandle.FromOffset(ReadCompressedInteger());
}
/// <summary>
/// Reads a constant value (see ECMA-335 Partition II section 22.9) from the current position.
/// </summary>
/// <exception cref="BadImageFormatException">Error while reading from the blob.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="typeCode"/> is not a valid <see cref="ConstantTypeCode"/>.</exception>
/// <returns>
/// Boxed constant value. To avoid allocating the object use Read* methods directly.
/// Constants of type <see cref="ConstantTypeCode.String"/> are encoded as UTF16 strings, use <see cref="ReadUTF16(int)"/> to read them.
/// </returns>
public object ReadConstant(ConstantTypeCode typeCode)
{
// Partition II section 22.9:
//
// Type shall be exactly one of: ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1,
// ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, ELEMENT_TYPE_U4,
// ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, or ELEMENT_TYPE_STRING;
// or ELEMENT_TYPE_CLASS with a Value of zero (23.1.16)
switch (typeCode)
{
case ConstantTypeCode.Boolean:
return ReadBoolean();
case ConstantTypeCode.Char:
return ReadChar();
case ConstantTypeCode.SByte:
return ReadSByte();
case ConstantTypeCode.Int16:
return ReadInt16();
case ConstantTypeCode.Int32:
return ReadInt32();
case ConstantTypeCode.Int64:
return ReadInt64();
case ConstantTypeCode.Byte:
return ReadByte();
case ConstantTypeCode.UInt16:
return ReadUInt16();
case ConstantTypeCode.UInt32:
return ReadUInt32();
case ConstantTypeCode.UInt64:
return ReadUInt64();
case ConstantTypeCode.Single:
return ReadSingle();
case ConstantTypeCode.Double:
return ReadDouble();
case ConstantTypeCode.String:
return ReadUTF16(RemainingBytes);
case ConstantTypeCode.NullReference:
// Partition II section 22.9:
// The encoding of Type for the nullref value is ELEMENT_TYPE_CLASS with a Value of a 4-byte zero.
// Unlike uses of ELEMENT_TYPE_CLASS in signatures, this one is not followed by a type token.
if (ReadUInt32() != 0)
{
throw new BadImageFormatException(SR.InvalidConstantValue);
}
return null;
default:
throw new ArgumentOutOfRangeException(nameof(typeCode));
}
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using UInt8 = System.Byte;
namespace Zutatensuppe.D2Reader.Struct.Skill
{
enum PetType
{
unknown0 = 0,
unknown1 = 1,
unknown2 = 2,
unknown3 = 3,
SKELETON_WARRIOR = 4,
unknown5 = 5,
unknown6 = 6,
unknown7 = 7,
unknown8 = 8,
unknown9 = 9,
unknown10 = 10,
unknown11 = 11,
unknown12 = 12,
unknown13 = 13,
unknown14 = 14,
unknown15 = 15,
unknown16 = 16,
TRAP_WAKE_OF_FIRE = 17, // 0x11
}
[Flags]
public enum SkillFlags : ulong
{
None = 0,
Decquant = (1UL << 0),
Lob = (1UL << 1),
Progressive = (1UL << 2),
Finishing = (1UL << 3),
Passive = (1UL << 4),
Aura = (1UL << 5),
Periodic = (1UL << 6),
PrgStack = (1UL << 7),
InTown = (1UL << 8),
Kick = (1UL << 9),
InGame = (1UL << 10),
Repeat = (1UL << 11),
StSuccessOnly = (1UL << 12),
StSoundDelay = (1UL << 13),
WeaponSnd = (1UL << 14),
Immediate = (1UL << 15),
NoAmmo = (1UL << 16),
Enhanceable = (1UL << 17),
Durability = (1UL << 18),
UseAttackRating = (1UL << 19),
TargetableOnly = (1UL << 20),
SearchEnemyXY = (1UL << 21),
SearchEnemyNear = (1UL << 22),
SearchOpenXY = (1UL << 23),
TargetCorpse = (1UL << 24),
TargetPet = (1UL << 25),
TargetAlly = (1UL << 26),
TargetItem = (1UL << 27),
AttackNoMana = (1UL << 28),
ItemTgtDo = (1UL << 29),
LeftSkill = (1UL << 30),
Interrupt = (1UL << 31),
TgtPlaceCheck = (1UL << 32),
ItemCheckStart = (1UL << 33),
ItemCltCheckStart = (1UL << 34),
General = (1UL << 35),
Scroll = (1UL << 36),
UseManaOnDo = (1UL << 37),
Warp = (1UL << 38),
}
[StructLayout(LayoutKind.Sequential, Pack = 1, Size = 0x23C)]
public class D2SkillData
{
[ExpectOffset(0x000)] public UInt32 SkillId; // 0x000
[ExpectOffset(0x004)] public SkillFlags Flags; // 0x004
[ExpectOffset(0x00C)] public UInt32 ClassId; // 0x00C
[ExpectOffset(0x010)] public UInt8 Anim; // 0x010
[ExpectOffset(0x011)] public UInt8 MonAnim; // 0x011
[ExpectOffset(0x012)] public UInt8 SeqTrans; // 0x012
[ExpectOffset(0x013)] public UInt8 SeqNum; // 0x013
[ExpectOffset(0x014)] public UInt8 Range; // 0x014
[ExpectOffset(0x015)] public UInt8 SelectProc; // 0x015
[ExpectOffset(0x016)] public UInt8 SeqInput; // 0x016
[ExpectOffset(0x017)] public UInt8 __Padding1; // 0x017
[ExpectOffset(0x018)] public UInt16 ITypeA1; // 0x018
[ExpectOffset(0x01A)] public UInt16 ITypeA2; // 0x01A
[ExpectOffset(0x01C)] public UInt16 ITypeA3; // 0x01C
[ExpectOffset(0x01E)] public UInt16 ITypeB1; // 0x01E
[ExpectOffset(0x020)] public UInt16 ITypeB2; // 0x020
[ExpectOffset(0x022)] public UInt16 ITypeB3; // 0x022
[ExpectOffset(0x024)] public UInt16 ETypeA1; // 0x024
[ExpectOffset(0x026)] public UInt16 ETypeA2; // 0x026
[ExpectOffset(0x028)] public UInt16 ETypeB1; // 0x028
[ExpectOffset(0x02A)] public UInt16 ETypeB2; // 0x02A
[ExpectOffset(0x02C)] public UInt16 SrvStartFunc; // 0x02C
[ExpectOffset(0x02E)] public UInt16 SrvDoFunc; // 0x02E
[ExpectOffset(0x030)] public UInt16 SrvPrgFunc1; // 0x030
[ExpectOffset(0x032)] public UInt16 SrvPrgFunc2; // 0x032
[ExpectOffset(0x034)] public UInt16 SrvPrgFunc3; // 0x034
[ExpectOffset(0x036)] public UInt16 __Padding2; // 0x036
[ExpectOffset(0x038)] public UInt32 PrgCalc1; // 0x038
[ExpectOffset(0x03C)] public UInt32 PrgCalc2; // 0x03C
[ExpectOffset(0x040)] public UInt32 PrgCalc3; // 0x040
[ExpectOffset(0x044)] public UInt16 PrgDamage; // 0x044
[ExpectOffset(0x046)] public UInt16 SrvMissile; // 0x046
[ExpectOffset(0x048)] public UInt16 SrvMissileA; // 0x048
[ExpectOffset(0x04A)] public UInt16 SrvMissileB; // 0x04A
[ExpectOffset(0x04C)] public UInt16 SrvMissileC; // 0x04C
[ExpectOffset(0x04E)] public UInt16 SrvOverlay; // 0x04E
[ExpectOffset(0x050)] public UInt32 AuraFilter; // 0x050
[ExpectOffset(0x054)] public UInt16 AuraStat1; // 0x054
[ExpectOffset(0x056)] public UInt16 AuraStat2; // 0x056
[ExpectOffset(0x058)] public UInt16 AuraStat3; // 0x058
[ExpectOffset(0x05A)] public UInt16 AuraStat4; // 0x05A
[ExpectOffset(0x05C)] public UInt16 AuraStat5; // 0x05C
[ExpectOffset(0x05E)] public UInt16 AuraStat6; // 0x05E
[ExpectOffset(0x060)] public UInt32 AuraLenCalc; // 0x060
[ExpectOffset(0x064)] public UInt32 AuraRangeCalc; // 0x064
[ExpectOffset(0x068)] public UInt32 AuraStatCalc1; // 0x068 ID
[ExpectOffset(0x06C)] public UInt32 AuraStatCalc2; // 0x06C ID
[ExpectOffset(0x070)] public UInt32 AuraStatCalc3; // 0x070 ID
[ExpectOffset(0x074)] public UInt32 AuraStatCalc4; // 0x074 ID
[ExpectOffset(0x078)] public UInt32 AuraStatCalc5; // 0x078 ID
[ExpectOffset(0x07C)] public UInt32 AuraStatCalc6; // 0x07C ID
[ExpectOffset(0x080)] public UInt16 AuraState; // 0x080
[ExpectOffset(0x082)] public UInt16 AuraTargetState; // 0x082
[ExpectOffset(0x084)] public UInt16 AuraEvent1; // 0x084
[ExpectOffset(0x086)] public UInt16 AuraEvent2; // 0x086
[ExpectOffset(0x088)] public UInt16 AuraEvent3; // 0x088
[ExpectOffset(0x08A)] public UInt16 AuraEventFunc1; // 0x08A
[ExpectOffset(0x08C)] public UInt16 AuraEventFunc2; // 0x08C
[ExpectOffset(0x08E)] public UInt16 AuraEventFunc3; // 0x08E
[ExpectOffset(0x090)] public UInt16 AuraTgtEvent; // 0x090
[ExpectOffset(0x092)] public UInt16 AuraTgtEventFunc; // 0x092
[ExpectOffset(0x094)] public UInt16 PassiveState; // 0x094 ....
[ExpectOffset(0x096)] public UInt16 PassiveiType; // 0x096
[ExpectOffset(0x098)] public UInt16 PassiveStat1; // 0x098
[ExpectOffset(0x09A)] public UInt16 PassiveStat2; // 0x09A
[ExpectOffset(0x09C)] public UInt16 PassiveStat3; // 0x09C
[ExpectOffset(0x09E)] public UInt16 PassiveStat4; // 0x09E
[ExpectOffset(0x0A0)] public UInt16 PassiveStat5; // 0x0A0
[ExpectOffset(0x0A2)] public UInt16 __Padding3; // 0x0A2
[ExpectOffset(0x0A4)] public UInt32 PassiveCalc1; // 0x0A4
[ExpectOffset(0x0A8)] public UInt32 PassiveCalc2; // 0x0A8
[ExpectOffset(0x0AC)] public UInt32 PassiveCalc3; // 0x0AC
[ExpectOffset(0x0B0)] public UInt32 PassiveCalc4; // 0x0B0
[ExpectOffset(0x0B4)] public UInt32 PassiveCalc5; // 0x0B4
[ExpectOffset(0x0B8)] public UInt16 PassiveEvent; // 0x0B8
[ExpectOffset(0x0BA)] public UInt16 PassiveEventFunc; // 0x0BA
[ExpectOffset(0x0BC)] public UInt16 Summon; // 0x0BC
[ExpectOffset(0x0BE)] public UInt8 PetType; // 0x0BE => see enum PetType
[ExpectOffset(0x0BF)] public UInt8 SumMode; // 0x0BF
[ExpectOffset(0x0C0)] public UInt32 PetMax; // 0x0C0
[ExpectOffset(0x0C4)] public UInt16 SumSkill1; // 0x0C4
[ExpectOffset(0x0C6)] public UInt16 SumSkill2; // 0x0C6
[ExpectOffset(0x0C8)] public UInt16 SumSkill3; // 0x0C8
[ExpectOffset(0x0CA)] public UInt16 SumSkill4; // 0x0CA
[ExpectOffset(0x0CC)] public UInt16 SumSkill5; // 0x0CC
[ExpectOffset(0x0CE)] public UInt16 __Padding4; // 0x0CE
[ExpectOffset(0x0D0)] public UInt32 SumSkCalc1; // 0x0D0
[ExpectOffset(0x0D4)] public UInt32 SumSkCalc2; // 0x0D4
[ExpectOffset(0x0D8)] public UInt32 SumSkCalc3; // 0x0D8
[ExpectOffset(0x0DC)] public UInt32 SumSkCalc4; // 0x0DC
[ExpectOffset(0x0E0)] public UInt32 SumSkCalc5; // 0x0E0
[ExpectOffset(0x0E4)] public UInt16 SumUMod; // 0x0E4
[ExpectOffset(0x0E6)] public UInt16 SumOverlay; // 0x0E6
[ExpectOffset(0x0E8)] public UInt16 CltMissile; // 0x0E8
[ExpectOffset(0x0EA)] public UInt16 CltMissileA; // 0x0EA
[ExpectOffset(0x0EC)] public UInt16 CltMissileB; // 0x0EC
[ExpectOffset(0x0EE)] public UInt16 CltMissileC; // 0x0EE
[ExpectOffset(0x0F0)] public UInt16 CltMissileD; // 0x0F0
[ExpectOffset(0x0F2)] public UInt16 CltStFunc; // 0x0F2
[ExpectOffset(0x0F4)] public UInt16 CltDoFunc; // 0x0F4
[ExpectOffset(0x0F6)] public UInt16 CltPrgFunc1; // 0x0F6
[ExpectOffset(0x0F8)] public UInt16 CltPrgFunc2; // 0x0F8
[ExpectOffset(0x0FA)] public UInt16 CltPrgFunc3; // 0x0FA
[ExpectOffset(0x0FC)] public UInt16 StSound; // 0x0FC
[ExpectOffset(0x0FE)] public UInt16 __Padding5; // 0x0FE
[ExpectOffset(0x100)] public UInt16 DoSound; // 0x100
[ExpectOffset(0x102)] public UInt16 DoSoundA; // 0x102
[ExpectOffset(0x104)] public UInt16 DoSoundB; // 0x104
[ExpectOffset(0x106)] public UInt16 CastOverlay; // 0x106
[ExpectOffset(0x108)] public UInt16 TgtOverlay; // 0x108
[ExpectOffset(0x10A)] public UInt16 TgtSound; // 0x10A
[ExpectOffset(0x10C)] public UInt16 PrgOverlay; // 0x10C
[ExpectOffset(0x10E)] public UInt16 PrgSound; // 0x10E
[ExpectOffset(0x110)] public UInt16 CltOverlayA; // 0x110
[ExpectOffset(0x112)] public UInt16 CltOverlayB; // 0x112
[ExpectOffset(0x114)] public UInt32 CltCalc1; // 0x114
[ExpectOffset(0x118)] public UInt32 CltCalc2; // 0x118
[ExpectOffset(0x11C)] public UInt32 CltCalc3; // 0x11C
[ExpectOffset(0x120)] public UInt16 ItemTarget; // 0x120
[ExpectOffset(0x122)] public UInt16 ItemCastSound; // 0x122
[ExpectOffset(0x124)] public UInt32 ItemCastOverlay; // 0x124
[ExpectOffset(0x128)] public UInt32 PerDelay; // 0x128
[ExpectOffset(0x12C)] public UInt16 MaxLvl; // 0x12C
[ExpectOffset(0x12E)] public UInt16 ResultFlags; // 0x12E
[ExpectOffset(0x130)] public UInt32 HitFlags; // 0x130
[ExpectOffset(0x134)] public UInt32 HitClass; // 0x134
[ExpectOffset(0x138)] public UInt32 Calc1; // 0x138
[ExpectOffset(0x13C)] public UInt32 Calc2; // 0x13C
[ExpectOffset(0x140)] public UInt32 Calc3; // 0x140
[ExpectOffset(0x144)] public UInt32 Calc4; // 0x144
[ExpectOffset(0x148)] public UInt32 Param1; // 0x148
[ExpectOffset(0x14C)] public UInt32 Param2; // 0x14C
[ExpectOffset(0x150)] public UInt32 Param3; // 0x150
[ExpectOffset(0x154)] public UInt32 Param4; // 0x154
[ExpectOffset(0x158)] public UInt32 Param5; // 0x158
[ExpectOffset(0x15C)] public UInt32 Param6; // 0x15C
[ExpectOffset(0x160)] public UInt32 Param7; // 0x160
[ExpectOffset(0x164)] public UInt32 Param8; // 0x164
[ExpectOffset(0x168)] public UInt16 WeapSel; // 0x168
[ExpectOffset(0x16A)] public UInt16 ItemEffect; // 0x16A
[ExpectOffset(0x16C)] public UInt32 ItemCltEffect; // 0x16C
[ExpectOffset(0x170)] public UInt32 SkPoints; // 0x170
[ExpectOffset(0x174)] public UInt16 ReqLevel; // 0x174
[ExpectOffset(0x176)] public UInt16 ReqStr; // 0x176
[ExpectOffset(0x178)] public UInt16 ReqDex; // 0x178
[ExpectOffset(0x17A)] public UInt16 ReqInt; // 0x17A
[ExpectOffset(0x17C)] public UInt16 ReqVit; // 0x17C
[ExpectOffset(0x17E)] public UInt16 ReqSkill1; // 0x17E
[ExpectOffset(0x180)] public UInt16 ReqSkill2; // 0x180
[ExpectOffset(0x182)] public UInt16 ReqSkill3; // 0x182
[ExpectOffset(0x184)] public UInt16 StartMana; // 0x184
[ExpectOffset(0x186)] public UInt16 MinMana; // 0x186
[ExpectOffset(0x188)] public UInt16 ManaShift; // 0x188
[ExpectOffset(0x18A)] public UInt16 Mana; // 0x18A
[ExpectOffset(0x18C)] public UInt16 LevelMana; // 0x18C
[ExpectOffset(0x18E)] public UInt8 AttackRank; // 0x18E
[ExpectOffset(0x18F)] public UInt8 LineOfSight; // 0x18F
[ExpectOffset(0x190)] public UInt32 Delay; // 0x190
[ExpectOffset(0x194)] public UInt32 SkillDescriptionId; // 0x194
[ExpectOffset(0x198)] public UInt32 ToHit; // 0x198
[ExpectOffset(0x19C)] public UInt32 LevToHit; // 0x19C
[ExpectOffset(0x1A0)] public UInt32 ToHitCalc; // 0x1A0
[ExpectOffset(0x1A4)] public UInt8 ToHitShift; // 0x1A4
[ExpectOffset(0x1A5)] public UInt8 SrcDam; // 0x1A5
[ExpectOffset(0x1A6)] public UInt16 __Padding6; // 0x1A6
[ExpectOffset(0x1A8)] public UInt32 MinDam; // 0x1A8
[ExpectOffset(0x1AC)] public UInt32 MaxDam; // 0x1AC
[ExpectOffset(0x1B0)] public UInt32 MinLvlDam1; // 0x1B0
[ExpectOffset(0x1B4)] public UInt32 MinLvlDam2; // 0x1B4
[ExpectOffset(0x1B8)] public UInt32 MinLvlDam3; // 0x1B8
[ExpectOffset(0x1BC)] public UInt32 MinLvlDam4; // 0x1BC
[ExpectOffset(0x1C0)] public UInt32 MinLvlDam5; // 0x1C0
[ExpectOffset(0x1C4)] public UInt32 MaxLvlDam1; // 0x1C4
[ExpectOffset(0x1C8)] public UInt32 MaxLvlDam2; // 0x1C8
[ExpectOffset(0x1CC)] public UInt32 MaxLvlDam3; // 0x1CC
[ExpectOffset(0x1D0)] public UInt32 MaxLvlDam4; // 0x1D0
[ExpectOffset(0x1D4)] public UInt32 MaxLvlDam5; // 0x1D4
[ExpectOffset(0x1D8)] public UInt32 DmgSymPerCalc; // 0x1D8
[ExpectOffset(0x1DC)] public UInt8 EType; // 0x1DC
[ExpectOffset(0x1DD)] public UInt8 __Padding5b; // 0x1DD
[ExpectOffset(0x1DE)] public UInt16 __Padding7; // 0x1DE
[ExpectOffset(0x1E0)] public UInt32 EMin; // 0x1E0
[ExpectOffset(0x1E4)] public UInt32 EMax; // 0x1E4
[ExpectOffset(0x1E8)] public UInt32 EMinLev1; // 0x1E8
[ExpectOffset(0x1EC)] public UInt32 EMinLev2; // 0x1EC
[ExpectOffset(0x1F0)] public UInt32 EMinLev3; // 0x1F0
[ExpectOffset(0x1F4)] public UInt32 EMinLev4; // 0x1F4
[ExpectOffset(0x1F8)] public UInt32 EMinLev5; // 0x1F8
[ExpectOffset(0x1FC)] public UInt32 EMaxLev1; // 0x1FC
[ExpectOffset(0x200)] public UInt32 EMaxLev2; // 0x200
[ExpectOffset(0x204)] public UInt32 EMaxLev3; // 0x204
[ExpectOffset(0x208)] public UInt32 EMaxLev4; // 0x208
[ExpectOffset(0x20C)] public UInt32 EMaxLev5; // 0x20C
[ExpectOffset(0x210)] public UInt32 EDmgSymPerCalc; // 0x210
[ExpectOffset(0x214)] public UInt32 ELen; // 0x214
[ExpectOffset(0x218)] public UInt32 ELevLen1; // 0x218
[ExpectOffset(0x21C)] public UInt32 ELevLen2; // 0x21C
[ExpectOffset(0x220)] public UInt32 ELevLen3; // 0x220
[ExpectOffset(0x224)] public UInt32 ELenSymPerCalc; // 0x224
[ExpectOffset(0x228)] public UInt16 Restrict; // 0x228
[ExpectOffset(0x22A)] public UInt16 State1; // 0x22A
[ExpectOffset(0x22C)] public UInt16 State2; // 0x22C
[ExpectOffset(0x22E)] public UInt16 State3; // 0x22E
[ExpectOffset(0x230)] public UInt16 AiType; // 0x230
[ExpectOffset(0x232)] public UInt16 AiBonus; // 0x232
[ExpectOffset(0x234)] public UInt32 CostMult; // 0x234
[ExpectOffset(0x238)] public UInt32 CostAdd; // 0x238
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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;
namespace Spine {
/// <summary>Stores the setup pose and all of the stateless data for a skeleton.</summary>
public class SkeletonData {
internal string name;
internal ExposedList<BoneData> bones = new ExposedList<BoneData>(); // Ordered parents first
internal ExposedList<SlotData> slots = new ExposedList<SlotData>(); // Setup pose draw order.
internal ExposedList<Skin> skins = new ExposedList<Skin>();
internal Skin defaultSkin;
internal ExposedList<EventData> events = new ExposedList<EventData>();
internal ExposedList<Animation> animations = new ExposedList<Animation>();
internal ExposedList<IkConstraintData> ikConstraints = new ExposedList<IkConstraintData>();
internal ExposedList<TransformConstraintData> transformConstraints = new ExposedList<TransformConstraintData>();
internal ExposedList<PathConstraintData> pathConstraints = new ExposedList<PathConstraintData>();
internal float width, height;
internal string version, hash;
// Nonessential.
internal float fps;
internal string imagesPath;
public string Name { get { return name; } set { name = value; } }
/// <summary>The skeleton's bones, sorted parent first. The root bone is always the first bone.</summary>
public ExposedList<BoneData> Bones { get { return bones; } }
public ExposedList<SlotData> Slots { get { return slots; } }
/// <summary>All skins, including the default skin.</summary>
public ExposedList<Skin> Skins { get { return skins; } set { skins = value; } }
/// <summary>
/// The skeleton's default skin.
/// By default this skin contains all attachments that were not in a skin in Spine.
/// </summary>
/// <return>May be null.</return>
public Skin DefaultSkin { get { return defaultSkin; } set { defaultSkin = value; } }
public ExposedList<EventData> Events { get { return events; } set { events = value; } }
public ExposedList<Animation> Animations { get { return animations; } set { animations = value; } }
public ExposedList<IkConstraintData> IkConstraints { get { return ikConstraints; } set { ikConstraints = value; } }
public ExposedList<TransformConstraintData> TransformConstraints { get { return transformConstraints; } set { transformConstraints = value; } }
public ExposedList<PathConstraintData> PathConstraints { get { return pathConstraints; } set { pathConstraints = value; } }
public float Width { get { return width; } set { width = value; } }
public float Height { get { return height; } set { height = value; } }
/// <summary>The Spine version used to export this data, or null.</summary>
public string Version { get { return version; } set { version = value; } }
public string Hash { get { return hash; } set { hash = value; } }
public string ImagesPath { get { return imagesPath; } set { imagesPath = value; } }
/// <summary>
/// The dopesheet FPS in Spine. Available only when nonessential data was exported.</summary>
public float Fps { get { return fps; } set { fps = value; } }
// --- Bones.
/// <summary>
/// Finds a bone by comparing each bone's name.
/// It is more efficient to cache the results of this method than to call it multiple times.</summary>
/// <returns>May be null.</returns>
public BoneData FindBone (string boneName) {
if (boneName == null) throw new ArgumentNullException("boneName", "boneName cannot be null.");
var bones = this.bones;
var bonesItems = bones.Items;
for (int i = 0, n = bones.Count; i < n; i++) {
BoneData bone = bonesItems[i];
if (bone.name == boneName) return bone;
}
return null;
}
/// <returns>-1 if the bone was not found.</returns>
public int FindBoneIndex (string boneName) {
if (boneName == null) throw new ArgumentNullException("boneName", "boneName cannot be null.");
var bones = this.bones;
var bonesItems = bones.Items;
for (int i = 0, n = bones.Count; i < n; i++)
if (bonesItems[i].name == boneName) return i;
return -1;
}
// --- Slots.
/// <returns>May be null.</returns>
public SlotData FindSlot (string slotName) {
if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null.");
ExposedList<SlotData> slots = this.slots;
for (int i = 0, n = slots.Count; i < n; i++) {
SlotData slot = slots.Items[i];
if (slot.name == slotName) return slot;
}
return null;
}
/// <returns>-1 if the slot was not found.</returns>
public int FindSlotIndex (string slotName) {
if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null.");
ExposedList<SlotData> slots = this.slots;
for (int i = 0, n = slots.Count; i < n; i++)
if (slots.Items[i].name == slotName) return i;
return -1;
}
// --- Skins.
/// <returns>May be null.</returns>
public Skin FindSkin (string skinName) {
if (skinName == null) throw new ArgumentNullException("skinName", "skinName cannot be null.");
foreach (Skin skin in skins)
if (skin.name == skinName) return skin;
return null;
}
// --- Events.
/// <returns>May be null.</returns>
public EventData FindEvent (string eventDataName) {
if (eventDataName == null) throw new ArgumentNullException("eventDataName", "eventDataName cannot be null.");
foreach (EventData eventData in events)
if (eventData.name == eventDataName) return eventData;
return null;
}
// --- Animations.
/// <returns>May be null.</returns>
public Animation FindAnimation (string animationName) {
if (animationName == null) throw new ArgumentNullException("animationName", "animationName cannot be null.");
ExposedList<Animation> animations = this.animations;
for (int i = 0, n = animations.Count; i < n; i++) {
Animation animation = animations.Items[i];
if (animation.name == animationName) return animation;
}
return null;
}
// --- IK constraints.
/// <returns>May be null.</returns>
public IkConstraintData FindIkConstraint (string constraintName) {
if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null.");
ExposedList<IkConstraintData> ikConstraints = this.ikConstraints;
for (int i = 0, n = ikConstraints.Count; i < n; i++) {
IkConstraintData ikConstraint = ikConstraints.Items[i];
if (ikConstraint.name == constraintName) return ikConstraint;
}
return null;
}
// --- Transform constraints.
/// <returns>May be null.</returns>
public TransformConstraintData FindTransformConstraint (string constraintName) {
if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null.");
ExposedList<TransformConstraintData> transformConstraints = this.transformConstraints;
for (int i = 0, n = transformConstraints.Count; i < n; i++) {
TransformConstraintData transformConstraint = transformConstraints.Items[i];
if (transformConstraint.name == constraintName) return transformConstraint;
}
return null;
}
// --- Path constraints.
/// <returns>May be null.</returns>
public PathConstraintData FindPathConstraint (string constraintName) {
if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null.");
ExposedList<PathConstraintData> pathConstraints = this.pathConstraints;
for (int i = 0, n = pathConstraints.Count; i < n; i++) {
PathConstraintData constraint = pathConstraints.Items[i];
if (constraint.name.Equals(constraintName)) return constraint;
}
return null;
}
/// <returns>-1 if the path constraint was not found.</returns>
public int FindPathConstraintIndex (string pathConstraintName) {
if (pathConstraintName == null) throw new ArgumentNullException("pathConstraintName", "pathConstraintName cannot be null.");
ExposedList<PathConstraintData> pathConstraints = this.pathConstraints;
for (int i = 0, n = pathConstraints.Count; i < n; i++)
if (pathConstraints.Items[i].name.Equals(pathConstraintName)) return i;
return -1;
}
// ---
override public string ToString () {
return name ?? base.ToString();
}
}
}
| |
// QuickGraph Library
//
// Copyright (c) 2004 Rohit Gadagkar
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// QuickGraph Library HomePage: http://www.mbunit.com
using System;
using System.Collections;
using QuickGraph.Algorithms;
using QuickGraph.Concepts;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Concepts.Algorithms;
using QuickGraph.Concepts.MutableTraversals;
using QuickGraph.Collections;
using QuickGraph.Concepts.Collections;
using QuickGraph.Collections.Sort;
namespace QuickGraph.Algorithms
{
/// <summary>
/// Creates a condensation graph transformation
/// </summary>
/// <author name="Rohit Gadogkar" email="rohit.gadagkar@gmail.com" />
public class CondensationGraphAlgorithm : IAlgorithm
{
private IVertexListGraph visitedGraph;
private VertexIntDictionary components;
private SortedList sccVertexMap;
/// <summary>
/// Condensation Graph constructor
/// </summary>
/// <param name="g">Input graph from
/// which condensation graph is created</param>
public CondensationGraphAlgorithm(IVertexListGraph g) {
if (g==null)
throw new ArgumentNullException("g");
this.visitedGraph = g;
this.components = null;
}
#region Properties
/// <summary>
/// Visited graph
/// </summary>
public IVertexListGraph VisitedGraph
{
get {
return this.visitedGraph;
}
}
Object IAlgorithm.VisitedGraph {
get {
return this.VisitedGraph;
}
}
/// <summary>
/// Maps a graph vertex to a strongly connected component
/// </summary>
/// <value>Map of IVertex to strongly connected component ID</value>
public VertexIntDictionary VertexToSCCMap {
get {
return this.components;
}
}
/// <summary>
/// Read only map of vertices within each strongly connected component
/// </summary>
/// <value>map with StronglyConnectedComponent ID as key and IList of vertices as value</value>
public SortedList SCCVerticesMap {
get {
return sccVertexMap;
}
}
#endregion
#region Events
/// <summary>
/// Raised when a new vertex is added in the condensation graph
/// </summary>
public event CondensationGraphVertexEventHandler InitCondensationGraphVertex;
/// <summary>
/// Raise the CondensationGraphVertex evt
/// </summary>
/// <param name="arg">Pack the CG vertex and a VertexCollection of it's constituent vertices</param>
protected void OnInitCondensationGraphVertex(CondensationGraphVertexEventArgs arg) {
if(InitCondensationGraphVertex != null)
InitCondensationGraphVertex(this, arg);
}
#endregion
/// <summary>
/// Clear the extracted strongly connected components
/// </summary>
public void ClearComponents()
{
this.components = null;
if(sccVertexMap != null)
sccVertexMap.Clear();
}
internal void ComputeComponents()
{
if( components == null )
components = new VertexIntDictionary();
// components is a MAP containing vertex number as key & component_id as value. It maps every vertex in input graph to SCC vertex ID which contains it
StrongComponentsAlgorithm algo = new StrongComponentsAlgorithm(
VisitedGraph,
this.components
);
algo.Compute();
}
private SortedList BuildSCCVertexMap( VertexIntDictionary vSccMap )
{
// Construct a map of SCC ID as key & IVertexCollection of vertices contained within the SCC as value
SortedList h = new SortedList();
VertexCollection vertices = null;
foreach( DictionaryEntry de in vSccMap )
{
IVertex v = (IVertex) de.Key;
int scc_id = (int) de.Value;
if( h.ContainsKey(scc_id) )
((VertexCollection) h[scc_id]).Add(v);
else
{
vertices = new VertexCollection();
vertices.Add(v);
h.Add(scc_id, vertices);
}
}
return h;
}
/// <summary>
/// Compute the condensation graph and store it in the supplied graph 'cg'
/// </summary>
/// <param name="cg">
/// Instance of mutable graph in which the condensation graph
/// transformation is stored
/// </param>
public void Create( IMutableVertexAndEdgeListGraph cg )
{
if (cg==null)
throw new ArgumentNullException("cg");
if (components==null)
ComputeComponents();
// components list contains collection of
// input graph Vertex for each SCC Vertex_ID
// (i.e Vector< Vector<Vertex> > )
// Key = SCC Vertex ID
sccVertexMap = BuildSCCVertexMap(components);
// Lsit of SCC vertices
VertexCollection toCgVertices = new VertexCollection();
IDictionaryEnumerator it = sccVertexMap.GetEnumerator();
while( it.MoveNext() )
// as scc_vertex_map is a sorted list, order of SCC IDs will match CG vertices
{
IVertex curr = cg.AddVertex();
OnInitCondensationGraphVertex(new CondensationGraphVertexEventArgs(curr, (IVertexCollection)it.Value));
toCgVertices.Add(curr);
}
for( int srcSccId=0; srcSccId<sccVertexMap.Keys.Count; srcSccId++ )
{
VertexCollection adj = new VertexCollection();
foreach( IVertex u in (IVertexCollection)sccVertexMap[srcSccId] )
{
foreach(IEdge e in VisitedGraph.OutEdges(u)) {
IVertex v = e.Target;
int targetSccId = components[v];
if (srcSccId != targetSccId)
{
// Avoid loops in the condensation graph
IVertex sccV = toCgVertices[targetSccId];
if( !adj.Contains(sccV) ) // Avoid parallel edges
adj.Add(sccV);
}
}
}
IVertex s = toCgVertices[srcSccId];
foreach( IVertex t in adj )
cg.AddEdge(s, t);
}
}
}
#region Condensation Graph Vertex Event
/// <summary>
/// Encapsulates a vertex in the original graph and it's corresponding
/// vertex in a transformation of the graph
/// </summary>
public class CondensationGraphVertexEventArgs : EventArgs
{
private IVertex vCG;
private IVertexCollection stronglyConnectedVertices;
/// <summary>
/// ctor()
/// </summary>
/// <param name="cgVertex">Vertex in the condensation graph</param>
/// <param name="stronglyConnectedVertices">strongly connected
/// components
/// in the original graph which are represented by the condensation
/// graph node</param>
public CondensationGraphVertexEventArgs(
IVertex cgVertex,
IVertexCollection stronglyConnectedVertices)
{
this.vCG = cgVertex;
this.stronglyConnectedVertices = stronglyConnectedVertices;
}
/// <summary>
/// Condensation graph vertex
/// </summary>
public IVertex CondensationGraphVertex
{
get
{
return vCG;
}
}
/// <summary>
/// Strongly connected vertices from original graph represented by the
/// condensation graph node
/// </summary>
public IVertexCollection StronglyConnectedVertices
{
get
{
return stronglyConnectedVertices;
}
}
}
/// <summary>
/// Delegate to handle the CondensationGraphVertexEvent
/// </summary>
public delegate void CondensationGraphVertexEventHandler(
Object sender,
CondensationGraphVertexEventArgs arg );
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Lab6.Areas.HelpPage.ModelDescriptions;
using Lab6.Areas.HelpPage.Models;
namespace Lab6.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Linq;
using Cassandra.Requests;
using Cassandra.Serialization;
namespace Cassandra
{
/// <summary>
/// A prepared statement with values bound to the bind variables. <p> Once a
/// BoundStatement has values for all the variables of the
/// <see cref="PreparedStatement"/> it has been created from, it can executed
/// (through <see cref="ISession.Execute(IStatement)"/>). </p><p> The values of a BoundStatement
/// can be set by either index or name. When setting them by name, names follow
/// the case insensitivity rules explained in <link>ColumnDefinitions</link>.
/// Note-worthily, if multiple bind variables correspond to the same column (as
/// would be the case if you prepare <c>SELECT * FROM t WHERE x > ? AND x < ?</c>),
/// you will have to set values by indexes (or the <c>PreparedStatement.Bind(object[])</c>
/// method) as the methods to set by name only allows to set the first prepared
/// occurrence of the column.</p>
/// <seealso cref="Cassandra.PreparedStatement"/>
/// </summary>
public class BoundStatement : Statement
{
private readonly PreparedStatement _preparedStatement;
private RoutingKey _routingKey;
private readonly Serializer _serializer;
private readonly string _keyspace;
/// <summary>
/// Gets the prepared statement on which this BoundStatement is based.
/// </summary>
public PreparedStatement PreparedStatement
{
get { return _preparedStatement; }
}
/// <summary>
/// Gets the routing key for this bound query. <p> This method will return a
/// non-<c>null</c> value if: <ul> <li>either all the TableColumns composing the
/// partition key are bound variables of this <c>BoundStatement</c>. The
/// routing key will then be built using the values provided for these partition
/// key TableColumns.</li> <li>or the routing key has been set through
/// <c>PreparedStatement.SetRoutingKey</c> for the
/// <see cref="PreparedStatement"/> this statement has been built from.</li> </ul>
/// Otherwise, <c>null</c> is returned.</p> <p> Note that if the routing key
/// has been set through <link>PreparedStatement.SetRoutingKey</link>, that value
/// takes precedence even if the partition key is part of the bound variables.</p>
/// </summary>
public override RoutingKey RoutingKey
{
get { return _routingKey; }
}
/// <summary>
/// Returns the keyspace this query operates on, based on the <see cref="PreparedStatement"/> metadata.
/// <para>
/// The keyspace returned is used as a hint for token-aware routing.
/// </para>
/// </summary>
public override string Keyspace
{
get { return _keyspace; }
}
/// <summary>
/// Initializes a new instance of the Cassandra.BoundStatement class
/// </summary>
public BoundStatement()
{
//Default constructor for client test and mocking frameworks
}
/// <summary>
/// Creates a new <c>BoundStatement</c> from the provided prepared
/// statement.
/// </summary>
/// <param name="statement"> the prepared statement from which to create a <c>BoundStatement</c>.</param>
public BoundStatement(PreparedStatement statement)
{
_preparedStatement = statement;
_routingKey = statement.RoutingKey;
if (statement.Metadata != null)
{
_keyspace = statement.Metadata.Keyspace;
}
SetConsistencyLevel(statement.ConsistencyLevel);
if (statement.IsIdempotent != null)
{
SetIdempotence(statement.IsIdempotent.Value);
}
}
internal BoundStatement(PreparedStatement statement, Serializer serializer) : this(statement)
{
_serializer = serializer;
}
/// <summary>
/// Set the routing key for this query. This method allows to manually
/// provide a routing key for this BoundStatement. It is thus optional since the routing
/// key is only an hint for token aware load balancing policy but is never
/// mandatory.
/// </summary>
/// <param name="routingKeyComponents"> the raw (binary) values to compose the routing key.</param>
public BoundStatement SetRoutingKey(params RoutingKey[] routingKeyComponents)
{
_routingKey = RoutingKey.Compose(routingKeyComponents);
return this;
}
internal override void SetValues(object[] values)
{
values = ValidateValues(values);
base.SetValues(values);
}
/// <summary>
/// Validate values using prepared statement metadata,
/// returning a new instance of values to be used as parameters.
/// </summary>
private object[] ValidateValues(object[] values)
{
if (_serializer == null)
{
throw new DriverInternalError("Serializer can not be null");
}
if (values == null)
{
return null;
}
if (PreparedStatement.Metadata == null || PreparedStatement.Metadata.Columns == null || PreparedStatement.Metadata.Columns.Length == 0)
{
return values;
}
var paramsMetadata = PreparedStatement.Metadata.Columns;
if (values.Length > paramsMetadata.Length)
{
throw new ArgumentException(
string.Format("Provided {0} parameters to bind, expected {1}", values.Length, paramsMetadata.Length));
}
for (var i = 0; i < values.Length; i++)
{
var p = paramsMetadata[i];
var value = values[i];
if (!_serializer.IsAssignableFrom(p, value))
{
throw new InvalidTypeException(
String.Format("It is not possible to encode a value of type {0} to a CQL type {1}", value.GetType(), p.TypeCode));
}
}
if (values.Length < paramsMetadata.Length && _serializer.ProtocolVersion.SupportsUnset())
{
//Set the result of the unspecified parameters to Unset
var completeValues = new object[paramsMetadata.Length];
values.CopyTo(completeValues, 0);
for (var i = values.Length; i < paramsMetadata.Length; i++)
{
completeValues[i] = Unset.Value;
}
values = completeValues;
}
return values;
}
internal override IQueryRequest CreateBatchRequest(ProtocolVersion protocolVersion)
{
// Use the default query options as the individual options of the query will be ignored
var options = QueryProtocolOptions.CreateForBatchItem(this);
return new ExecuteRequest(protocolVersion, PreparedStatement.Id, PreparedStatement.Metadata, IsTracing, options);
}
internal void CalculateRoutingKey(bool useNamedParameters, int[] routingIndexes, string[] routingNames, object[] valuesByPosition, object[] rawValues)
{
if (_routingKey != null)
{
//The routing key was specified by the user
return;
}
if (routingIndexes != null)
{
var keys = new RoutingKey[routingIndexes.Length];
for (var i = 0; i < routingIndexes.Length; i++)
{
var index = routingIndexes[i];
var key = _serializer.Serialize(valuesByPosition[index]);
if (key == null)
{
//The partition key can not be null
//Get out and let any node reply a Response Error
return;
}
keys[i] = new RoutingKey(key);
}
SetRoutingKey(keys);
return;
}
if (routingNames != null && useNamedParameters)
{
var keys = new RoutingKey[routingNames.Length];
var routingValues = Utils.GetValues(routingNames, rawValues[0]).ToArray();
if (routingValues.Length != keys.Length)
{
//The routing names are not valid
return;
}
for (var i = 0; i < routingValues.Length; i++)
{
var key = _serializer.Serialize(routingValues[i]);
if (key == null)
{
//The partition key can not be null
return;
}
keys[i] = new RoutingKey(key);
}
SetRoutingKey(keys);
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#if DEBUG
#define TRACK_REPRESENTATION_IDENTITY
#else
//#define TRACK_REPRESENTATION_IDENTITY
#endif
namespace Microsoft.Zelig.Runtime.TypeSystem
{
using System;
using System.Collections.Generic;
[DisableReferenceCounting]
public abstract class BaseRepresentation
{
//
// State
//
#if TRACK_REPRESENTATION_IDENTITY
protected static int s_identity;
#endif
public int m_identity;
//--//
protected CustomAttributeAssociationRepresentation[] m_customAttributes;
//--//
//
// Constructor Methods
//
protected BaseRepresentation()
{
#if TRACK_REPRESENTATION_IDENTITY
m_identity = s_identity++;
#endif
m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray;
}
//
// MetaDataEquality Methods
//
public abstract bool EqualsThroughEquivalence( object obj ,
EquivalenceSet set );
public static bool EqualsThroughEquivalence( BaseRepresentation left ,
BaseRepresentation right ,
EquivalenceSet set )
{
if(Object.ReferenceEquals( left, right ))
{
return true;
}
if(left != null && right != null)
{
return left.EqualsThroughEquivalence( right, set );
}
return false;
}
public static bool ArrayEqualsThroughEquivalence<T>( T[] s ,
T[] d ,
EquivalenceSet set ) where T : BaseRepresentation
{
return ArrayEqualsThroughEquivalence( s, d, 0, -1, set );
}
public static bool ArrayEqualsThroughEquivalence<T>( T[] s ,
T[] d ,
int offset ,
int count ,
EquivalenceSet set ) where T : BaseRepresentation
{
int sLen = s != null ? s.Length : 0;
int dLen = d != null ? d.Length : 0;
if(count < 0)
{
if(sLen != dLen)
{
return false;
}
count = sLen - offset;
}
else
{
if(sLen < count + offset ||
dLen < count + offset )
{
return false;
}
}
while(count > 0)
{
if(EqualsThroughEquivalence( s[offset], d[offset], set ) == false)
{
return false;
}
offset++;
count--;
}
return true;
}
//--//
//
// Helper Methods
//
public virtual void ApplyTransformation( TransformationContext context )
{
context.Push( this );
context.Transform( ref m_customAttributes );
context.Pop();
}
//--//
public void AddCustomAttribute( CustomAttributeAssociationRepresentation cca )
{
m_customAttributes = ArrayUtility.AddUniqueToNotNullArray( m_customAttributes, cca );
}
public void CopyCustomAttribute( CustomAttributeAssociationRepresentation caa )
{
AddCustomAttribute( new CustomAttributeAssociationRepresentation( caa.CustomAttribute, this, caa.ParameterIndex ) );
}
public void RemoveCustomAttribute( CustomAttributeAssociationRepresentation cca )
{
m_customAttributes = ArrayUtility.RemoveUniqueFromNotNullArray( m_customAttributes, cca );
}
public void RemoveCustomAttribute( CustomAttributeRepresentation ca )
{
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
if(caa.CustomAttribute == ca)
{
RemoveCustomAttribute( caa );
}
}
}
public bool HasCustomAttribute( TypeRepresentation target )
{
return FindCustomAttribute( target, -1 ) != null;
}
public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target )
{
return FindCustomAttribute( target, -1 );
}
public List<CustomAttributeRepresentation> FindCustomAttributes( TypeRepresentation target )
{
var lst = new List<CustomAttributeRepresentation>();
FindCustomAttributes( target, lst );
return lst;
}
public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target ,
int index )
{
return FindCustomAttribute( target, -1, index );
}
public virtual void EnumerateCustomAttributes( CustomAttributeAssociationEnumerationCallback callback )
{
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
callback( caa );
}
}
//--//
protected CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target ,
int paramIndex ,
int index )
{
int pos = index >= 0 ? 0 : index; // So we don't have the double check in the loop.
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
if(caa.CustomAttribute.Constructor.OwnerType == target &&
caa.ParameterIndex == paramIndex )
{
if(index == pos)
{
return caa.CustomAttribute;
}
pos++;
}
}
return null;
}
protected void FindCustomAttributes( TypeRepresentation target, List<CustomAttributeRepresentation> lst )
{
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
if(caa.CustomAttribute.Constructor.OwnerType == target)
{
lst.Add( caa.CustomAttribute );
}
}
}
//--//
internal virtual void ProhibitUse( TypeSystem.Reachability reachability ,
bool fApply )
{
reachability.ExpandProhibition( this );
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
reachability.ExpandProhibition( caa );
}
}
internal virtual void Reduce( TypeSystem.Reachability reachability ,
bool fApply )
{
for(int i = m_customAttributes.Length; --i >= 0; )
{
CustomAttributeAssociationRepresentation caa = m_customAttributes[i];
CHECKS.ASSERT( reachability.Contains( caa.Target ) == true, "{0} cannot be reachable since its owner is not in the Reachability set", caa );
if(reachability.Contains( caa.CustomAttribute.Constructor ) == false)
{
CHECKS.ASSERT( reachability.Contains( caa ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa );
CHECKS.ASSERT( reachability.Contains( caa.CustomAttribute ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa.CustomAttribute );
reachability.ExpandProhibition( caa );
reachability.ExpandProhibition( caa.CustomAttribute );
if(fApply)
{
if(m_customAttributes.Length == 1)
{
m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray;
return;
}
m_customAttributes = ArrayUtility.RemoveAtPositionFromNotNullArray( m_customAttributes, i );
}
}
}
}
//--//
//
// Access Methods
//
public CustomAttributeAssociationRepresentation[] CustomAttributes
{
get
{
return m_customAttributes;
}
}
//--//
//
// Debug Methods
//
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
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>
/// ServerConnectionPoliciesOperations operations.
/// </summary>
internal partial class ServerConnectionPoliciesOperations : IServiceOperations<SqlManagementClient>, IServerConnectionPoliciesOperations
{
/// <summary>
/// Initializes a new instance of the ServerConnectionPoliciesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ServerConnectionPoliciesOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates the server's connection policy.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The required parameters for updating a secure connection policy.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ServerConnectionPolicy>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, ServerConnectionPolicy parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
string apiVersion = "2014-04-01";
string connectionPolicyName = "default";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("connectionPolicyName", connectionPolicyName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/connectionPolicies/{connectionPolicyName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{connectionPolicyName}", System.Uri.EscapeDataString(connectionPolicyName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ServerConnectionPolicy>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServerConnectionPolicy>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServerConnectionPolicy>(_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>
/// Gets the server's secure connection policy.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ServerConnectionPolicy>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
string apiVersion = "2014-04-01";
string connectionPolicyName = "default";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("connectionPolicyName", connectionPolicyName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/connectionPolicies/{connectionPolicyName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{connectionPolicyName}", System.Uri.EscapeDataString(connectionPolicyName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ServerConnectionPolicy>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServerConnectionPolicy>(_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="TangoDeltaPoseController.cs" company="Google">
//
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using Tango;
using UnityEngine;
/// <summary>
/// An advanced movement controller which updates the position and rotation of a
/// GameObject's transform by applying deltas based on the poses returned from
/// Tango. This allows you to control movement using movement deltas; for
/// example, with a CharacterController or physics. The Tango Delta Camera
/// prefab uses this controller with an optional Character Controller to control
/// the Unity camera with a Tango device's movement.
/// </summary>
public class TangoDeltaPoseController : MonoBehaviour, ITangoPose
{
/// <summary>
/// The change in time since the last pose update.
/// </summary>
[HideInInspector]
public float m_poseDeltaTime;
/// <summary>
/// Total number of poses ever received by this controller.
/// </summary>
[HideInInspector]
public int m_poseCount;
/// <summary>
/// The status of the most recent pose used by this controller.
/// </summary>
[HideInInspector]
public TangoEnums.TangoPoseStatusType m_poseStatus;
/// <summary>
/// The timestamp of the most recent pose used by this controller.
/// </summary>
[HideInInspector]
public float m_poseTimestamp;
/// <summary>
/// The absolute target position for this controller. This is based on the
/// most recent pose received from the Tango service, and adjusted for any
/// offsets from calling <c>SetPose</c> or using the clutch feature.
/// </summary>
[HideInInspector]
public Vector3 m_tangoPosition;
/// <summary>
/// The absolute target rotation for this controller. This is based on the
/// most recent pose received from the Tango service, and adjusted for any
/// offsets from calling <c>SetPose()</c> or using the clutch feature.
/// </summary>
[HideInInspector]
public Quaternion m_tangoRotation;
/// <summary>
/// If set, use the Move function of the CharacterController attached to the
/// parent object to update the position.
/// </summary>
public bool m_characterMotion;
/// <summary>
/// If set, display a Clutch UI via OnGUI.
/// </summary>
public bool m_enableClutchUI;
/// <summary>
/// If set, the initial pose uses the Area Description base frame.
/// </summary>
public bool m_useAreaDescriptionPose;
/// <summary>
/// The previous target position for this controller. Used to calculate
/// movement deltas.
/// </summary>
private Vector3 m_prevTangoPosition;
/// <summary>
/// The previous target rotation for this controller. Used to calculate
/// movement deltas.
/// </summary>
private Quaternion m_prevTangoRotation;
/// <summary>
/// Internal data about the clutch.
/// </summary>
private bool m_clutchActive;
/// <summary>
/// Internal CharacterController used for motion.
/// </summary>
private CharacterController m_characterController;
/// <summary>
/// Matrix that transforms from the Unity Camera to the Unity World.
///
/// Needed to calculate offsets.
/// </summary>
private Matrix4x4 m_uwTuc;
/// <summary>
/// Matrix that transforms the Unity World taking into account offsets from calls
/// to <c>SetPose</c>.
/// </summary>
private Matrix4x4 m_uwOffsetTuw;
/// <summary>
/// Gets or sets a value indicating whether the clutch is active.
///
/// If the clutch is active, the controller ignores device movement and yaw,
/// but follows pitch and roll to keep the ground plane level.
/// </summary>
/// <value><c>true</c> if the clutch is active; <c>false</c> otherwise.</value>
public bool ClutchActive
{
get
{
return m_clutchActive;
}
set
{
if (m_clutchActive && !value)
{
SetPose(transform.position, transform.rotation);
}
m_clutchActive = value;
}
}
/// <summary>
/// Gets the TRS matrix for the offset between the pose returned by the
/// Tango service and the desired pose in the Unity world. If the only
/// source of movement are position and rotation updates from the Tango
/// service, there is no offset and this returns an identity matrix. If
/// other movement is applied (i.e. from activating the clutch or calling
/// <c>SetPose</c>), this returns a matrix which can be multiplied to a
/// transform to apply the offset.
/// </summary>
/// <value>The Unity world offset.</value>
public Matrix4x4 UnityWorldOffset
{
get
{
return m_uwOffsetTuw;
}
}
/// @cond
/// <summary>
/// Awake is called when the script instance is being loaded.
/// </summary>
public void Awake()
{
m_poseDeltaTime = -1.0f;
m_poseTimestamp = -1.0f;
m_poseCount = -1;
m_poseStatus = TangoEnums.TangoPoseStatusType.NA;
m_prevTangoRotation = m_tangoRotation = Quaternion.identity;
m_prevTangoPosition = m_tangoPosition = Vector3.zero;
m_uwTuc = Matrix4x4.identity;
m_uwOffsetTuw = Matrix4x4.identity;
}
/// <summary>
/// Start is called on the frame when a script is enabled.
/// </summary>
public void Start()
{
m_characterController = GetComponent<CharacterController>();
TangoApplication tangoApplication = FindObjectOfType<TangoApplication>();
if (tangoApplication != null)
{
tangoApplication.Register(this);
}
else
{
Debug.Log("No Tango Manager found in scene.");
}
SetPose(transform.position, transform.rotation);
}
/// <summary>
/// Unity callback when the component gets destroyed.
/// </summary>
public void OnDestroy()
{
TangoApplication tangoApplication = FindObjectOfType<TangoApplication>();
if (tangoApplication != null)
{
tangoApplication.Unregister(this);
}
}
/// <summary>
/// OnGUI is called for rendering and handling GUI events.
/// </summary>
public void OnGUI()
{
if (!m_enableClutchUI)
{
return;
}
bool buttonState = GUI.RepeatButton(new Rect(10, 500, 200, 200), "<size=40>CLUTCH</size>");
// OnGUI is called multiple times per frame. Make sure to only care about the last one.
if (Event.current.type == EventType.Repaint)
{
ClutchActive = buttonState;
}
}
/// <summary>
/// Unity callback when application is paused.
/// </summary>
/// <param name="pauseStatus">The pauseStatus as reported by Unity.</param>
public void OnApplicationPause(bool pauseStatus)
{
m_poseDeltaTime = -1.0f;
m_poseTimestamp = -1.0f;
m_poseCount = -1;
m_poseStatus = TangoEnums.TangoPoseStatusType.NA;
}
/// <summary>
/// OnTangoPoseAvailable is called from Tango when a new Pose is available.
/// </summary>
/// <param name="pose">The new Tango pose.</param>
public void OnTangoPoseAvailable(TangoPoseData pose)
{
// Get out of here if the pose is null
if (pose == null)
{
Debug.Log("TangoPoseDate is null.");
return;
}
// Only interested in pose updates relative to the start of service pose.
if (!m_useAreaDescriptionPose)
{
if (pose.framePair.baseFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE
&& pose.framePair.targetFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE)
{
_UpdateTransformationFromPose(pose);
}
}
else
{
if (pose.framePair.baseFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION
&& pose.framePair.targetFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE)
{
_UpdateTransformationFromPose(pose);
}
}
}
/// @endcond
/// <summary>
/// Sets the absolute position and yaw of the GameObject this controller is
/// attached to. Pitch and roll from the rotation are ignored. Future
/// movement will be relative to this new location.
/// </summary>
/// <param name="pos">New position.</param>
/// <param name="quat">New rotation.</param>
public void SetPose(Vector3 pos, Quaternion quat)
{
Quaternion uwQuc = Quaternion.LookRotation(m_uwTuc.GetColumn(2), m_uwTuc.GetColumn(1));
Vector3 eulerAngles = quat.eulerAngles;
eulerAngles.x = uwQuc.eulerAngles.x;
eulerAngles.z = uwQuc.eulerAngles.z;
quat.eulerAngles = eulerAngles;
m_uwOffsetTuw = Matrix4x4.TRS(pos, quat, Vector3.one) * m_uwTuc.inverse;
m_prevTangoPosition = m_tangoPosition = pos;
m_prevTangoRotation = m_tangoRotation = quat;
if (m_characterController != null)
{
m_characterController.transform.position = pos;
m_characterController.transform.rotation = quat;
}
}
/// <summary>
/// Set controller's transformation based on received pose.
/// </summary>
/// <param name="pose">Received Tango pose data.</param>
private void _UpdateTransformationFromPose(TangoPoseData pose)
{
// Remember the previous position, so you can do delta motion
m_prevTangoPosition = m_tangoPosition;
m_prevTangoRotation = m_tangoRotation;
// The callback pose is for device with respect to start of service pose.
if (pose.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID)
{
Vector3 position;
Quaternion rotation;
TangoSupport.TangoPoseToWorldTransform(pose, out position, out rotation);
m_uwTuc = Matrix4x4.TRS(position, rotation, Vector3.one);
Matrix4x4 uwOffsetTuc = m_uwOffsetTuw * m_uwTuc;
m_tangoPosition = uwOffsetTuc.GetColumn(3);
m_tangoRotation = Quaternion.LookRotation(uwOffsetTuc.GetColumn(2), uwOffsetTuc.GetColumn(1));
// Other pose data -- Pose count gets reset if pose status just became valid.
if (pose.status_code != m_poseStatus)
{
m_poseCount = 0;
}
m_poseCount++;
// Other pose data -- Pose delta time.
m_poseDeltaTime = (float)pose.timestamp - m_poseTimestamp;
m_poseTimestamp = (float)pose.timestamp;
}
m_poseStatus = pose.status_code;
if (m_clutchActive)
{
// When clutching, preserve position.
m_tangoPosition = m_prevTangoPosition;
// When clutching, preserve yaw, keep changes in pitch, roll.
Vector3 rotationAngles = m_tangoRotation.eulerAngles;
rotationAngles.y = m_prevTangoRotation.eulerAngles.y;
m_tangoRotation.eulerAngles = rotationAngles;
}
// Calculate final position and rotation deltas and apply them.
Vector3 deltaPosition = m_tangoPosition - m_prevTangoPosition;
Quaternion deltaRotation = m_tangoRotation * Quaternion.Inverse(m_prevTangoRotation);
if (m_characterMotion && m_characterController != null)
{
m_characterController.Move(deltaPosition);
transform.rotation = deltaRotation * transform.rotation;
}
else
{
transform.position = transform.position + deltaPosition;
transform.rotation = deltaRotation * transform.rotation;
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v2.0)
// [MaterialPreviewRenderer.cs]
// (c) 2012-2015, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS 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.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using Assimp;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using PixelFormat = OpenTK.Graphics.OpenGL.PixelFormat;
using TextureWrapMode = OpenTK.Graphics.OpenGL.TextureWrapMode;
namespace open3mod
{
/// <summary>
/// Renders off-screen preview images for materials, such as those being
/// shown in the materials tab. One MaterialPreviewRenderer is responsible
/// only for rendering one preview image for one material (it is "one use only").
///
/// Rendering preview images is interleaved with the actual visible scene drawing
/// and can thus not happen at any time. The MaterialPreviewRenderer offers the
/// PreviewAvailable event to let users know when the preview image is available.
/// </summary>
public class MaterialPreviewRenderer
{
private readonly Scene _scene;
private readonly Material _material;
private readonly uint _width;
private readonly uint _height;
public enum CompletionState
{
Pending, Failed, Done
}
public delegate void OnPreviewAvailableDelegate(MaterialPreviewRenderer me);
/// <summary>
/// This event is fired when the preview image is available or if generating
/// the image failed for some reason. It is only fired once for a
/// MaterialPreviewRenderer instance.
/// </summary>
public event OnPreviewAvailableDelegate PreviewAvailable;
private CompletionState _state;
private Image _previewImage;
// shared geometry data to draw a sphere
private static SphereGeometry.Vertex[] _sphereVertices;
private static ushort[] _sphereElements;
private const float SphereRadius = 0.9f;
private const int SphereSegments = 50;
/// <summary>
/// Constructs a MaterialPreviewRenderer to obtain a preview image
/// for one given material.
/// </summary>
/// <param name="window">Window instance that hosts the primary Gl context</param>
/// <param name="scene">Scene instance that the material belongs to</param>
/// <param name="material">Material to render a preview image for</param>
/// <param name="width">Requested width of the preview image, in pixels</param>
/// <param name="height">Requested height of the preview image, in pixels</param>
public MaterialPreviewRenderer(MainWindow window, Scene scene, Material material, uint width, uint height)
{
Debug.Assert(window != null);
Debug.Assert(material != null);
Debug.Assert(scene != null);
Debug.Assert(width >= 1);
Debug.Assert(height >= 1);
_scene = scene;
_material = material;
_width = width;
_height = height;
_state = CompletionState.Pending;
window.Renderer.GlExtraDrawJob += (sender) =>
{
_state = !RenderPreview() ? CompletionState.Failed : CompletionState.Done;
OnPreviewAvailable();
};
}
/// <summary>
/// Obtains the rendered preview image as a System.Drawing.Image.
/// The value is non-null iff State == CompletionState.Done
/// </summary>
public Image PreviewImage
{
get { return _previewImage; }
}
/// <summary>
/// Gives the current completion state of the preview rendering job.
/// </summary>
public CompletionState State
{
get { return _state; }
}
/// <summary>
/// Renders the preview. This performs Gl commands, so it must be called
/// from a context where this is allowed.
///
/// Upon success, true is returned and _previewImage gets assigned
/// the generated preview image.
/// </summary>
/// <returns>true in case the preview has been successfully generated</returns>
private bool RenderPreview()
{
// based on http://www.opentk.com/doc/graphics/frame-buffer-objects
// use a pow2 FBO even if the hardware supports arbitrary sizes
var fboWidth = (int)RoundToNextPowerOfTwo(_width);
var fboHeight = (int)RoundToNextPowerOfTwo(_height);
int fboHandle = -1;
int colorTexture = -1;
int depthRenderbuffer = -1;
// clear error flags
GL.GetError();
// Create Color Texture
GL.GenTextures(1, out colorTexture);
GL.BindTexture(TextureTarget.Texture2D, colorTexture);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.NearestMipmapNearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
// note! OpenTK.Graphics.OpenGL.TextureWrapMode clashes with Assimp.EmbeddedTextureWrapMode
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Clamp);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Clamp);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8,
fboWidth,
fboHeight,
0,
PixelFormat.Rgba,
PixelType.UnsignedByte,
IntPtr.Zero);
// test for GL Error here (might be unsupported format)
var error = GL.GetError();
if (error != ErrorCode.NoError)
{
EnsureTemporaryResourcesReleased(colorTexture,
depthRenderbuffer,
fboHandle);
return false;
}
GL.BindTexture(TextureTarget.Texture2D, 0); // prevent feedback, reading and writing to the same image is a bad idea
// Create Depth Renderbuffer
GL.Ext.GenRenderbuffers(1, out depthRenderbuffer);
GL.Ext.BindRenderbuffer(RenderbufferTarget.RenderbufferExt, depthRenderbuffer);
GL.Ext.RenderbufferStorage(RenderbufferTarget.RenderbufferExt,
(RenderbufferStorage)All.DepthComponent32, fboWidth, fboHeight);
// test for GL Error here (might be unsupported format)
error = GL.GetError();
if(error != ErrorCode.NoError)
{
EnsureTemporaryResourcesReleased(colorTexture,
depthRenderbuffer, fboHandle);
return false;
}
// Create a FBO and attach the textures
GL.Ext.GenFramebuffers(1, out fboHandle);
GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, fboHandle);
GL.Ext.FramebufferTexture2D(FramebufferTarget.FramebufferExt,
FramebufferAttachment.ColorAttachment0Ext,
TextureTarget.Texture2D,
colorTexture, 0);
GL.Ext.FramebufferRenderbuffer(FramebufferTarget.FramebufferExt,
FramebufferAttachment.DepthAttachmentExt,
RenderbufferTarget.RenderbufferExt,
depthRenderbuffer);
// verify the FBO is complete and ready to use
var status = GL.Ext.CheckFramebufferStatus(FramebufferTarget.FramebufferExt);
if (status != FramebufferErrorCode.FramebufferComplete)
{
EnsureTemporaryResourcesReleased(colorTexture,
depthRenderbuffer, fboHandle);
return false;
}
// since there's only 1 Color buffer attached this is not explicitly required
GL.DrawBuffer((DrawBufferMode)FramebufferAttachment.ColorAttachment0Ext);
GL.PushAttrib(AttribMask.ViewportBit); // stores GL.Viewport() parameters
GL.Viewport(0, 0, (int)_width, (int)_height);
Draw();
CopyToImage();
// restores GL.Viewport() parameters
GL.PopAttrib();
// return to visible framebuffer
GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);
GL.DrawBuffer(DrawBufferMode.Back);
EnsureTemporaryResourcesReleased(colorTexture,
depthRenderbuffer, fboHandle);
return true;
}
private void CopyToImage()
{
var bmp = new Bitmap((int)_width, (int)_height);
var data = bmp.LockBits(new Rectangle(0,0,(int)_width, (int)_height),
ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.ReadPixels(0,0,(int)_width,(int)_height,PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0 );
bmp.UnlockBits(data);
_previewImage = bmp;
}
private static void EnsureTemporaryResourcesReleased(int colorTexture, int depthRenderbuffer, int fboHandle)
{
try
{
if (colorTexture != -1)
{
GL.DeleteTexture(colorTexture);
}
if (depthRenderbuffer != -1)
{
GL.Ext.DeleteRenderbuffers(1, ref depthRenderbuffer);
}
if (fboHandle != -1)
{
GL.DeleteFramebuffers(1, ref fboHandle);
}
}
catch(Exception)
{
// On some older hardware I found that glDeleteRenderbuffers and glDeleteFramebuffers
// are not found even though the other APIs (i.e. creating fbs) are.
}
}
private void Draw()
{
GL.ClearColor(Color.Transparent);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
if (_sphereVertices == null)
{
_sphereVertices = SphereGeometry.CalculateVertices(SphereRadius, SphereRadius, SphereSegments, SphereSegments);
}
if (_sphereElements == null)
{
_sphereElements = SphereGeometry.CalculateElements(SphereSegments, SphereSegments);
}
// reset color and alpha blending
GL.Color4(Color.White);
GL.Disable(EnableCap.Blend);
_scene.MaterialMapper.ApplyMaterial(null, _material, true, true);
// always enable depth writes when rendering material previews
GL.DepthMask(true);
GL.MatrixMode(MatrixMode.Modelview);
var lookat = Matrix4.LookAt(0, 0, -2.5f, 0, 0, 0, 0, 1, 0);
GL.LoadMatrix(ref lookat);
Matrix4 perspective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 1.0f, 0.01f, 100.0f);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref perspective);
GL.Enable(EnableCap.DepthTest);
// set fixed-function lighting parameters
GL.ShadeModel(ShadingModel.Smooth);
GL.Enable(EnableCap.Light0);
GL.Light(LightName.Light0, LightParameter.Position, new float[] { 0.5f, -0.6f, -0.8f });
GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { 1, 1, 1, 1 });
GL.Light(LightName.Light0, LightParameter.Specular, new float[] { 1, 1, 1, 1 });
Debug.Assert(_sphereVertices != null);
Debug.Assert(_sphereElements != null);
SphereGeometry.Draw(_sphereVertices, _sphereElements);
}
private static uint RoundToNextPowerOfTwo(uint s)
{
return (uint)Math.Pow(2, Math.Ceiling(Math.Log(s, 2)));
}
private void OnPreviewAvailable()
{
OnPreviewAvailableDelegate handler = PreviewAvailable;
if (handler != null) handler(this);
}
}
}
/* vi: set shiftwidth=4 tabstop=4: */
| |
using System;
using System.Collections;
using System.Diagnostics;
using System.Windows.Input;
using Xamarin.Forms.Platform;
namespace Xamarin.Forms
{
[RenderWith(typeof(_ListViewRenderer))]
public class ListView : ItemsView<Cell>, IListViewController
{
public static readonly BindableProperty IsPullToRefreshEnabledProperty = BindableProperty.Create("IsPullToRefreshEnabled", typeof(bool), typeof(ListView), false);
public static readonly BindableProperty IsRefreshingProperty = BindableProperty.Create("IsRefreshing", typeof(bool), typeof(ListView), false, BindingMode.TwoWay);
public static readonly BindableProperty RefreshCommandProperty = BindableProperty.Create("RefreshCommand", typeof(ICommand), typeof(ListView), null, propertyChanged: OnRefreshCommandChanged);
public static readonly BindableProperty HeaderProperty = BindableProperty.Create("Header", typeof(object), typeof(ListView), null, propertyChanged: OnHeaderChanged);
public static readonly BindableProperty HeaderTemplateProperty = BindableProperty.Create("HeaderTemplate", typeof(DataTemplate), typeof(ListView), null, propertyChanged: OnHeaderTemplateChanged,
validateValue: ValidateHeaderFooterTemplate);
public static readonly BindableProperty FooterProperty = BindableProperty.Create("Footer", typeof(object), typeof(ListView), null, propertyChanged: OnFooterChanged);
public static readonly BindableProperty FooterTemplateProperty = BindableProperty.Create("FooterTemplate", typeof(DataTemplate), typeof(ListView), null, propertyChanged: OnFooterTemplateChanged,
validateValue: ValidateHeaderFooterTemplate);
public static readonly BindableProperty SelectedItemProperty = BindableProperty.Create("SelectedItem", typeof(object), typeof(ListView), null, BindingMode.OneWayToSource,
propertyChanged: OnSelectedItemChanged);
public static readonly BindableProperty HasUnevenRowsProperty = BindableProperty.Create("HasUnevenRows", typeof(bool), typeof(ListView), false);
public static readonly BindableProperty RowHeightProperty = BindableProperty.Create("RowHeight", typeof(int), typeof(ListView), -1);
public static readonly BindableProperty GroupHeaderTemplateProperty = BindableProperty.Create("GroupHeaderTemplate", typeof(DataTemplate), typeof(ListView), null,
propertyChanged: OnGroupHeaderTemplateChanged);
public static readonly BindableProperty IsGroupingEnabledProperty = BindableProperty.Create("IsGroupingEnabled", typeof(bool), typeof(ListView), false);
public static readonly BindableProperty SeparatorVisibilityProperty = BindableProperty.Create("SeparatorVisibility", typeof(SeparatorVisibility), typeof(ListView), SeparatorVisibility.Default);
public static readonly BindableProperty SeparatorColorProperty = BindableProperty.Create("SeparatorColor", typeof(Color), typeof(ListView), Color.Default);
BindingBase _groupDisplayBinding;
BindingBase _groupShortNameBinding;
Element _headerElement;
Element _footerElement;
ScrollToRequestedEventArgs _pendingScroll;
int _previousGroupSelected = -1;
int _previousRowSelected = -1;
/// <summary>
/// Controls whether anything happens in BeginRefresh(), is set based on RefreshCommand.CanExecute
/// </summary>
bool _refreshAllowed = true;
public ListView()
{
TakePerformanceHit = false;
VerticalOptions = HorizontalOptions = LayoutOptions.FillAndExpand;
TemplatedItems.IsGroupingEnabledProperty = IsGroupingEnabledProperty;
TemplatedItems.GroupHeaderTemplateProperty = GroupHeaderTemplateProperty;
}
public ListView([Parameter("CachingStrategy")] ListViewCachingStrategy cachingStrategy) : this()
{
if (Device.OS == TargetPlatform.Android || Device.OS == TargetPlatform.iOS)
CachingStrategy = cachingStrategy;
}
public object Footer
{
get { return GetValue(FooterProperty); }
set { SetValue(FooterProperty, value); }
}
public DataTemplate FooterTemplate
{
get { return (DataTemplate)GetValue(FooterTemplateProperty); }
set { SetValue(FooterTemplateProperty, value); }
}
public BindingBase GroupDisplayBinding
{
get { return _groupDisplayBinding; }
set
{
if (_groupDisplayBinding == value)
return;
OnPropertyChanging();
BindingBase oldValue = value;
_groupDisplayBinding = value;
OnGroupDisplayBindingChanged(this, oldValue, _groupDisplayBinding);
TemplatedItems.GroupDisplayBinding = value;
OnPropertyChanged();
}
}
public DataTemplate GroupHeaderTemplate
{
get { return (DataTemplate)GetValue(GroupHeaderTemplateProperty); }
set { SetValue(GroupHeaderTemplateProperty, value); }
}
public BindingBase GroupShortNameBinding
{
get { return _groupShortNameBinding; }
set
{
if (_groupShortNameBinding == value)
return;
OnPropertyChanging();
_groupShortNameBinding = value;
TemplatedItems.GroupShortNameBinding = value;
OnPropertyChanged();
}
}
public bool HasUnevenRows
{
get { return (bool)GetValue(HasUnevenRowsProperty); }
set { SetValue(HasUnevenRowsProperty, value); }
}
public object Header
{
get { return GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public DataTemplate HeaderTemplate
{
get { return (DataTemplate)GetValue(HeaderTemplateProperty); }
set { SetValue(HeaderTemplateProperty, value); }
}
public bool IsGroupingEnabled
{
get { return (bool)GetValue(IsGroupingEnabledProperty); }
set { SetValue(IsGroupingEnabledProperty, value); }
}
public bool IsPullToRefreshEnabled
{
get { return (bool)GetValue(IsPullToRefreshEnabledProperty); }
set { SetValue(IsPullToRefreshEnabledProperty, value); }
}
public bool IsRefreshing
{
get { return (bool)GetValue(IsRefreshingProperty); }
set { SetValue(IsRefreshingProperty, value); }
}
public ICommand RefreshCommand
{
get { return (ICommand)GetValue(RefreshCommandProperty); }
set { SetValue(RefreshCommandProperty, value); }
}
public int RowHeight
{
get { return (int)GetValue(RowHeightProperty); }
set { SetValue(RowHeightProperty, value); }
}
public object SelectedItem
{
get { return GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public Color SeparatorColor
{
get { return (Color)GetValue(SeparatorColorProperty); }
set { SetValue(SeparatorColorProperty, value); }
}
public SeparatorVisibility SeparatorVisibility
{
get { return (SeparatorVisibility)GetValue(SeparatorVisibilityProperty); }
set { SetValue(SeparatorVisibilityProperty, value); }
}
internal ListViewCachingStrategy CachingStrategy { get; private set; }
internal bool TakePerformanceHit { get; set; }
bool RefreshAllowed
{
set
{
if (_refreshAllowed == value)
return;
_refreshAllowed = value;
OnPropertyChanged();
}
get { return _refreshAllowed; }
}
Element IListViewController.FooterElement
{
get { return _footerElement; }
}
Element IListViewController.HeaderElement
{
get { return _headerElement; }
}
bool IListViewController.RefreshAllowed
{
get { return RefreshAllowed; }
}
void IListViewController.SendCellAppearing(Cell cell)
{
EventHandler<ItemVisibilityEventArgs> handler = ItemAppearing;
if (handler != null)
handler(this, new ItemVisibilityEventArgs(cell.BindingContext));
}
void IListViewController.SendCellDisappearing(Cell cell)
{
EventHandler<ItemVisibilityEventArgs> handler = ItemDisappearing;
if (handler != null)
handler(this, new ItemVisibilityEventArgs(cell.BindingContext));
}
void IListViewController.SendRefreshing()
{
BeginRefresh();
}
public void BeginRefresh()
{
if (!RefreshAllowed)
return;
SetValueCore(IsRefreshingProperty, true);
OnRefreshing(EventArgs.Empty);
ICommand command = RefreshCommand;
if (command != null)
command.Execute(null);
}
public void EndRefresh()
{
SetValueCore(IsRefreshingProperty, false);
}
public event EventHandler<ItemVisibilityEventArgs> ItemAppearing;
public event EventHandler<ItemVisibilityEventArgs> ItemDisappearing;
public event EventHandler<SelectedItemChangedEventArgs> ItemSelected;
public event EventHandler<ItemTappedEventArgs> ItemTapped;
public event EventHandler Refreshing;
public void ScrollTo(object item, ScrollToPosition position, bool animated)
{
if (!Enum.IsDefined(typeof(ScrollToPosition), position))
throw new ArgumentException("position is not a valid ScrollToPosition", "position");
var args = new ScrollToRequestedEventArgs(item, position, animated);
if (IsPlatformEnabled)
OnScrollToRequested(args);
else
_pendingScroll = args;
}
public void ScrollTo(object item, object group, ScrollToPosition position, bool animated)
{
if (!IsGroupingEnabled)
throw new InvalidOperationException("Grouping is not enabled");
if (!Enum.IsDefined(typeof(ScrollToPosition), position))
throw new ArgumentException("position is not a valid ScrollToPosition", "position");
var args = new ScrollToRequestedEventArgs(item, group, position, animated);
if (IsPlatformEnabled)
OnScrollToRequested(args);
else
_pendingScroll = args;
}
protected override Cell CreateDefault(object item)
{
string text = null;
if (item != null)
text = item.ToString();
return new TextCell { Text = text };
}
[Obsolete("Use OnMeasure")]
protected override SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
{
var minimumSize = new Size(40, 40);
Size request;
double width = Math.Min(Device.Info.ScaledScreenSize.Width, Device.Info.ScaledScreenSize.Height);
var list = ItemsSource as IList;
if (list != null && HasUnevenRows == false && RowHeight > 0 && !IsGroupingEnabled)
{
// we can calculate this
request = new Size(width, list.Count * RowHeight);
}
else
{
// probably not worth it
request = new Size(width, Math.Max(Device.Info.ScaledScreenSize.Width, Device.Info.ScaledScreenSize.Height));
}
return new SizeRequest(request, minimumSize);
}
protected override void SetupContent(Cell content, int index)
{
base.SetupContent(content, index);
content.Parent = this;
}
protected override void UnhookContent(Cell content)
{
base.UnhookContent(content);
content.Parent = null;
}
internal Cell CreateDefaultCell(object item)
{
return CreateDefault(item);
}
internal void NotifyRowTapped(int groupIndex, int inGroupIndex, Cell cell = null)
{
TemplatedItemsList<ItemsView<Cell>, Cell> group = TemplatedItems.GetGroup(groupIndex);
bool changed = _previousGroupSelected != groupIndex || _previousRowSelected != inGroupIndex;
_previousRowSelected = inGroupIndex;
_previousGroupSelected = groupIndex;
if (cell == null)
{
cell = group[inGroupIndex];
}
// Set SelectedItem before any events so we don't override any changes they may have made.
SetValueCore(SelectedItemProperty, cell.BindingContext, SetValueFlags.ClearOneWayBindings | SetValueFlags.ClearDynamicResource | (changed ? SetValueFlags.RaiseOnEqual : 0));
cell.OnTapped();
ItemTapped?.Invoke(this, new ItemTappedEventArgs(group, cell.BindingContext));
}
internal void NotifyRowTapped(int index, Cell cell = null)
{
if (IsGroupingEnabled)
{
int leftOver;
int groupIndex = TemplatedItems.GetGroupIndexFromGlobal(index, out leftOver);
NotifyRowTapped(groupIndex, leftOver - 1, cell);
}
else
NotifyRowTapped(0, index, cell);
}
internal override void OnIsPlatformEnabledChanged()
{
base.OnIsPlatformEnabledChanged();
if (IsPlatformEnabled && _pendingScroll != null)
{
OnScrollToRequested(_pendingScroll);
_pendingScroll = null;
}
}
internal event EventHandler<ScrollToRequestedEventArgs> ScrollToRequested;
void OnCommandCanExecuteChanged(object sender, EventArgs eventArgs)
{
RefreshAllowed = RefreshCommand.CanExecute(null);
}
static void OnFooterChanged(BindableObject bindable, object oldValue, object newValue)
{
var lv = (ListView)bindable;
lv.OnHeaderOrFooterChanged(ref lv._footerElement, "FooterElement", newValue, lv.FooterTemplate, false);
}
static void OnFooterTemplateChanged(BindableObject bindable, object oldValue, object newValue)
{
var lv = (ListView)bindable;
lv.OnHeaderOrFooterChanged(ref lv._footerElement, "FooterElement", lv.Footer, (DataTemplate)newValue, true);
}
static void OnGroupDisplayBindingChanged(BindableObject bindable, BindingBase oldValue, BindingBase newValue)
{
var lv = (ListView)bindable;
if (newValue != null && lv.GroupHeaderTemplate != null)
{
lv.GroupHeaderTemplate = null;
Log.Warning("ListView", "GroupHeaderTemplate and GroupDisplayBinding can not be set at the same time, setting GroupHeaderTemplate to null");
}
}
static void OnGroupHeaderTemplateChanged(BindableObject bindable, object oldvalue, object newValue)
{
var lv = (ListView)bindable;
if (newValue != null && lv.GroupDisplayBinding != null)
{
lv.GroupDisplayBinding = null;
Debug.WriteLine("GroupHeaderTemplate and GroupDisplayBinding can not be set at the same time, setting GroupDisplayBinding to null");
}
}
static void OnHeaderChanged(BindableObject bindable, object oldValue, object newValue)
{
var lv = (ListView)bindable;
lv.OnHeaderOrFooterChanged(ref lv._headerElement, "HeaderElement", newValue, lv.HeaderTemplate, false);
}
void OnHeaderOrFooterChanged(ref Element storage, string property, object dataObject, DataTemplate template, bool templateChanged)
{
if (dataObject == null)
{
if (!templateChanged)
{
OnPropertyChanging(property);
storage = null;
OnPropertyChanged(property);
}
return;
}
if (template == null)
{
var view = dataObject as Element;
if (view == null || view is Page)
view = new Label { Text = dataObject.ToString() };
view.Parent = this;
OnPropertyChanging(property);
storage = view;
OnPropertyChanged(property);
}
else if (storage == null || templateChanged)
{
OnPropertyChanging(property);
storage = template.CreateContent() as Element;
if (storage != null)
{
storage.BindingContext = dataObject;
storage.Parent = this;
}
OnPropertyChanged(property);
}
else
{
storage.BindingContext = dataObject;
}
}
static void OnHeaderTemplateChanged(BindableObject bindable, object oldValue, object newValue)
{
var lv = (ListView)bindable;
lv.OnHeaderOrFooterChanged(ref lv._headerElement, "HeaderElement", lv.Header, (DataTemplate)newValue, true);
}
static void OnRefreshCommandChanged(BindableObject bindable, object oldValue, object newValue)
{
var lv = (ListView)bindable;
var oldCommand = (ICommand)oldValue;
var command = (ICommand)newValue;
lv.OnRefreshCommandChanged(oldCommand, command);
}
void OnRefreshCommandChanged(ICommand oldCommand, ICommand newCommand)
{
if (oldCommand != null)
{
oldCommand.CanExecuteChanged -= OnCommandCanExecuteChanged;
}
if (newCommand != null)
{
newCommand.CanExecuteChanged += OnCommandCanExecuteChanged;
RefreshAllowed = newCommand.CanExecute(null);
}
else
{
RefreshAllowed = true;
}
}
void OnRefreshing(EventArgs e)
{
EventHandler handler = Refreshing;
if (handler != null)
handler(this, e);
}
void OnScrollToRequested(ScrollToRequestedEventArgs e)
{
EventHandler<ScrollToRequestedEventArgs> handler = ScrollToRequested;
if (handler != null)
handler(this, e);
}
static void OnSelectedItemChanged(BindableObject bindable, object oldValue, object newValue)
{
var list = (ListView)bindable;
if (list.ItemSelected != null)
list.ItemSelected(list, new SelectedItemChangedEventArgs(newValue));
}
static bool ValidateHeaderFooterTemplate(BindableObject bindable, object value)
{
if (value == null)
return true;
var template = (DataTemplate)value;
return template.CreateContent() is View;
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using DevExpress.Mvvm.Native;
#if !NETFX_CORE
using System.Windows.Data;
using System.Windows.Markup;
using System.Collections.Generic;
using DevExpress.Mvvm.UI.Native;
using System.Reflection;
using System.Collections;
#else
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Markup;
using CultureInfo = System.String;
#endif
namespace DevExpress.Mvvm.UI {
#if !NETFX_CORE && !FREE
public class ReflectionConverter : IValueConverter {
class TypeUnsetValue { }
Type convertBackMethodOwner = typeof(TypeUnsetValue);
class ConvertMethodSignature {
int valueIndex;
int targetTypeIndex;
int parameterIndex;
int cultureIndex;
public ConvertMethodSignature(Type[] parameterTypes, int valueIndex, int targetTypeIndex, int parameterIndex, int cultureIndex) {
ParameterTypes = parameterTypes;
this.valueIndex = valueIndex;
this.targetTypeIndex = targetTypeIndex;
this.parameterIndex = parameterIndex;
this.cultureIndex = cultureIndex;
}
public Type[] ParameterTypes { get; private set; }
public void AssignArgs(object[] args, object value, Type targetType, object parameter, CultureInfo culture) {
args[valueIndex] = value;
if(targetTypeIndex >= 0)
args[targetTypeIndex] = targetType;
if(parameterIndex >= 0)
args[parameterIndex] = parameter;
if(cultureIndex >= 0)
args[cultureIndex] = culture;
}
}
static readonly ConvertMethodSignature[] ConvertMethodSignatures = new ConvertMethodSignature[] {
new ConvertMethodSignature(new Type[] { null }, 0, -1, -1, -1),
new ConvertMethodSignature(new Type[] { null, typeof(CultureInfo) }, 0, -1, -1, 1),
new ConvertMethodSignature(new Type[] { null, typeof(Type) }, 0, 1, -1, -1),
new ConvertMethodSignature(new Type[] { null, null }, 0, -1, 1, -1),
new ConvertMethodSignature(new Type[] { null, typeof(Type), null }, 0, 1, 2, -1),
new ConvertMethodSignature(new Type[] { null, typeof(Type), typeof(CultureInfo) }, 0, 1, -1, 2),
new ConvertMethodSignature(new Type[] { null, null, typeof(CultureInfo) }, 0, -1, 1, 2),
new ConvertMethodSignature(new Type[] { null, typeof(Type), null, typeof(CultureInfo) }, 0, 1, 2, 3),
};
public Type ConvertMethodOwner { get; set; }
public string ConvertMethod { get; set; }
public Type ConvertBackMethodOwner {
get { return convertBackMethodOwner == typeof(TypeUnsetValue) ? ConvertMethodOwner : convertBackMethodOwner; }
set { convertBackMethodOwner = value; }
}
public string ConvertBackMethod { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return ConvertCore(value, targetType, parameter, culture, ConvertMethodOwner, ConvertMethod);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
return ConvertCore(value, targetType, parameter, culture, ConvertBackMethodOwner, ConvertBackMethod);
}
static object ConvertCore(object value, Type targetType, object parameter, CultureInfo culture, Type convertMethodOwner, string convertMethod) {
if(convertMethodOwner == null) {
if(convertMethod == null)
return targetType == null ? value : ConvertByTargetTypeConstructor(value, targetType, parameter, culture);
else
return value == null ? null : ConvertBySourceValueMethod(value, targetType, parameter, culture, convertMethod);
} else {
if(convertMethod == null)
return ConvertByConstructor(value, targetType, parameter, culture, convertMethodOwner);
else
return ConvertByStaticMethod(value, targetType, parameter, culture, convertMethodOwner, convertMethod);
}
}
static object ConvertByTargetTypeConstructor(object value, Type targetType, object parameter, CultureInfo culture) {
return ConvertByConstructor(value, targetType, parameter, culture, targetType.GetConstructors());
}
static object ConvertByConstructor(object value, Type targetType, object parameter, CultureInfo culture, Type convertMethodOwner) {
return ConvertByConstructor(value, targetType, parameter, culture, convertMethodOwner.GetConstructors());
}
static object ConvertByConstructor(object value, Type targetType, object parameter, CultureInfo culture, IEnumerable<ConstructorInfo> methods) {
ConstructorInfo convertMethod = methods.Where(c => c.GetParameters().Length == 1).FirstOrDefault();
if(convertMethod == null)
convertMethod = methods.Where(c => c.GetParameters().Length > 0 && !c.GetParameters().Skip(1).Any(p => !p.IsOptional)).FirstOrDefault();
if(convertMethod == null)
throw new InvalidOperationException();
ParameterInfo[] parameters = convertMethod.GetParameters();
object[] args = new object[parameters.Length];
args[0] = value;
parameters.Skip(1).Select(p => p.DefaultValue).ToArray().CopyTo(args, 1);
return convertMethod.Invoke(args);
}
static object ConvertBySourceValueMethod(object value, Type targetType, object parameter, CultureInfo culture, string convertMethodName) {
MethodInfo convertMethod = value.GetType().GetMethod(convertMethodName, new Type[] { });
if(convertMethod == null)
convertMethod = value.GetType().GetMethods().Where(c => c.Name == convertMethodName && c.GetParameters().Length > 0 && !c.GetParameters().Any(p => !p.IsOptional)).FirstOrDefault();
if(convertMethod == null)
throw new InvalidOperationException();
ParameterInfo[] parameters = convertMethod.GetParameters();
object[] args = parameters.Select(p => p.DefaultValue).ToArray();
return convertMethod.Invoke(value, args);
}
static object ConvertByStaticMethod(object value, Type targetType, object parameter, CultureInfo culture, Type convertMethodOwner, string convertMethodName) {
Tuple<MethodInfo, ConvertMethodSignature> convertMethod = GetMethod(convertMethodOwner.GetMethods(BindingFlags.Static | BindingFlags.Public).Where(m => m.Name == convertMethodName));
if(convertMethod == null)
throw new InvalidOperationException();
ParameterInfo[] parameters = convertMethod.Item1.GetParameters();
object[] args = new object[parameters.Length];
convertMethod.Item2.AssignArgs(args, value, targetType, parameter, culture);
for(int i = convertMethod.Item2.ParameterTypes.Length; i < args.Length; ++i)
args[i] = parameters[i].DefaultValue;
return convertMethod.Item1.Invoke(null, args);
}
static Tuple<MethodInfo, ConvertMethodSignature> GetMethod(IEnumerable<MethodInfo> methods) {
foreach(var method in methods) {
ParameterInfo[] parameters = method.GetParameters();
var variantMatch = ConvertMethodSignatures.Where(v => Match(parameters, v.ParameterTypes)).FirstOrDefault();
if(variantMatch != null) return new Tuple<MethodInfo, ConvertMethodSignature>(method, variantMatch);
}
return null;
}
static bool Match(ParameterInfo[] parameterInfo, Type[] parameterTypes) {
if(parameterTypes.Length > parameterInfo.Length) return false;
for(int i = parameterTypes.Length; i < parameterInfo.Length; ++i) {
if(!parameterInfo[i].IsOptional) return false;
}
for(int i = 0; i < parameterTypes.Length; ++i) {
if(!Match(parameterInfo[i].ParameterType, parameterTypes[i])) return false;
}
return true;
}
static bool Match(Type actual, Type expected) {
return expected == null || actual == expected;
}
}
public class EnumerableConverter : IValueConverter {
public Type TargetItemType { get; set; }
public IValueConverter ItemConverter { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
IEnumerable enumerable = value as IEnumerable;
if(enumerable == null) return null;
Type targetItemType = GetTargetItemType(targetType);
Func<object, object> convertItem = x => ItemConverter == null ? x : ItemConverter.Convert(x, targetItemType, parameter, culture);
IEnumerable convertedEnumerable = (IEnumerable)Activator.CreateInstance(typeof(EnumerableWrap<>).MakeGenericType(targetItemType), enumerable, convertItem);
if(targetType == null || targetType.IsAssignableFrom(convertedEnumerable.GetType()))
return convertedEnumerable;
else if(targetType.IsInterface)
return CreateList(targetType, targetItemType, convertedEnumerable);
else if(targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(ReadOnlyCollection<>))
return CreateReadOnlyCollection(targetType, targetItemType, convertedEnumerable);
else
return CreateCollection(targetType, targetItemType, convertedEnumerable);
}
Type GetTargetItemType(Type targetType) {
if(TargetItemType != null)
return TargetItemType;
if(targetType == null)
throw new InvalidOperationException();
var interfaces = new Type[] { targetType }.Where(t => t.IsInterface).Concat(targetType.GetInterfaces());
Type targetItemType = interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)).Select(i => i.GetGenericArguments()[0]).FirstOrDefault();
if(targetItemType == null)
throw new InvalidOperationException();
return targetItemType;
}
object CreateList(Type targetType, Type itemType, IEnumerable enumerable) {
if(targetType != null && (targetType == typeof(IEnumerable) || targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
return enumerable;
Type collectionType = typeof(List<>).MakeGenericType(itemType);
if(targetType != null && !targetType.IsAssignableFrom(collectionType))
throw new NotSupportedCollectionException(targetType);
return Activator.CreateInstance(collectionType, enumerable);
}
object CreateReadOnlyCollection(Type targetType, Type itemType, IEnumerable enumerable) {
object list = CreateList(null, itemType, enumerable);
return list.GetType().GetMethod("AsReadOnly").Invoke(list, new object[] { });
}
object CreateCollection(Type targetType, Type itemType, IEnumerable enumerable) {
ConstructorInfo constructor1 = targetType.GetConstructor(new Type[] { typeof(IEnumerable) });
if(constructor1 != null)
return constructor1.Invoke(new object[] { enumerable });
ConstructorInfo constructor2 = targetType.GetConstructor(new Type[] { typeof(IEnumerable<>).MakeGenericType(itemType) });
if(constructor2 != null)
return constructor2.Invoke(new object[] { enumerable });
return CreateCollectionWithDefaultConstructor(targetType, itemType, enumerable);
}
object CreateCollectionWithDefaultConstructor(Type targetType, Type itemType, IEnumerable enumerable) {
object collection;
try {
collection = Activator.CreateInstance(targetType);
} catch (MissingMethodException e) {
throw new NotSupportedCollectionException(targetType, null, e);
}
IList list = collection as IList;
if(list != null) {
foreach(var item in enumerable)
list.Add(item);
return list;
}
MethodInfo addMethod;
Type genericListType = typeof(IList<>).MakeGenericType(itemType);
if(targetType.GetInterfaces().Any(t => t == genericListType)) {
addMethod = genericListType.GetMethod("Add", new Type[] { itemType });
} else {
addMethod = targetType.GetMethod("Add", new Type[] { itemType });
if(addMethod == null)
addMethod = targetType.GetMethods().Where(m => m.GetParameters().Length == 1).Where(m => m.GetParameters()[0].ParameterType.IsAssignableFrom(itemType)).FirstOrDefault();
}
if(addMethod == null)
throw new NotSupportedCollectionException(targetType);
foreach(var item in enumerable)
addMethod.Invoke(collection, new object[] { item });
return collection;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotSupportedException();
}
}
public class NotSupportedCollectionException : Exception {
public NotSupportedCollectionException(Type collectionType, string message = null, Exception innerException = null) : base(message, innerException) {
CollectionType = collectionType;
}
public Type CollectionType { get; private set; }
}
public class CriteriaOperatorConverter : IValueConverter {
public string Expression { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if(value == null) return null;
var criteriaOperator = DevExpress.Data.Filtering.CriteriaOperator.Parse(Expression);
var evaluator = new DevExpress.Data.Filtering.Helpers.ExpressionEvaluator(TypeDescriptor.GetProperties(value), criteriaOperator);
return evaluator.Evaluate(value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotSupportedException();
}
}
#endif
public class TypeCastConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return TypeCastHelper.TryCast(value, targetType);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
return TypeCastHelper.TryCast(value, targetType);
}
}
public class NumericToBooleanConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return ConverterHelper.NumericToBoolean(value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; }
}
public class StringToBooleanConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if(!(value is string))
return false;
return !String.IsNullOrEmpty((string)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; }
}
public class ObjectToBooleanConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return value != null ^ Inverse;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; }
public bool Inverse { get; set; }
}
public class MapItem {
public MapItem() { }
public MapItem(object source, object target) {
Source = source;
Target = target;
}
public object Source { get; set; }
public object Target { get; set; }
}
#if !NETFX_CORE
[ContentProperty("Map")]
#else
[ContentProperty(Name="Map")]
#endif
public class ObjectToObjectConverter : IValueConverter {
public object DefaultSource { get; set; }
public object DefaultTarget { get; set; }
public ObservableCollection<MapItem> Map { get; set; }
public ObjectToObjectConverter() {
Map = new ObservableCollection<MapItem>();
}
object Coerce(object value, Type targetType) {
if(value == null || targetType == value.GetType()) {
return value;
}
if(targetType == typeof(string)) {
return value.ToString();
}
#if !NETFX_CORE
if(targetType.IsEnum && value is string) {
#else
if(targetType.IsEnum() && value is string) {
#endif
return Enum.Parse(targetType, (string)value, false);
}
try {
return System.Convert.ChangeType(value, targetType, System.Globalization.CultureInfo.InvariantCulture);
} catch {
return value;
}
}
public static bool SafeCompare(object left, object right) {
if(left == null) {
if(right == null)
return true;
return right.Equals(left);
}
return left.Equals(right);
}
Func<MapItem, bool> MakeMapPredicate(Func<MapItem, object> selector, object value) {
return mapItem => {
object source = Coerce(selector(mapItem), (value ?? string.Empty).GetType());
return SafeCompare(source, value);
};
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
MapItem entry = Map.FirstOrDefault(MakeMapPredicate(item => item.Source, value));
return entry == null ? DefaultTarget : entry.Target;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
MapItem entry = Map.FirstOrDefault(MakeMapPredicate(item => item.Target, value));
return entry == null ? DefaultSource : entry.Source;
}
}
public class BooleanToVisibilityConverter : IValueConverter {
bool hiddenInsteadOfCollapsed;
public bool Inverse { get; set; }
#if !NETFX_CORE
[Obsolete, Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public bool HiddenInsteadCollapsed { get { return hiddenInsteadOfCollapsed; } set { hiddenInsteadOfCollapsed = value; } }
#endif
public bool HiddenInsteadOfCollapsed { get { return hiddenInsteadOfCollapsed; } set { hiddenInsteadOfCollapsed = value; } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
bool booleanValue = ConverterHelper.GetBooleanValue(value);
return ConverterHelper.BooleanToVisibility(booleanValue, Inverse, HiddenInsteadOfCollapsed);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
bool booleanValue = (value is Visibility && (Visibility)value == Visibility.Visible) ^ Inverse;
return booleanValue;
}
}
public class NumericToVisibilityConverter : IValueConverter {
bool hiddenInsteadOfCollapsed;
public bool Inverse { get; set; }
public bool HiddenInsteadOfCollapsed { get { return hiddenInsteadOfCollapsed; } set { hiddenInsteadOfCollapsed = value; } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
bool boolean = ConverterHelper.NumericToBoolean(value);
return ConverterHelper.BooleanToVisibility(boolean, Inverse, HiddenInsteadOfCollapsed);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; }
}
public class DefaultBooleanToBooleanConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
bool? booleanValue = ConverterHelper.GetNullableBooleanValue(value);
if(targetType == typeof(bool)) return booleanValue ?? false;
return booleanValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
bool? booleanValue = ConverterHelper.GetNullableBooleanValue(value);
if(targetType == typeof(bool)) return booleanValue ?? false;
return booleanValue;
}
}
public class BooleanNegationConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
bool? booleanValue = ConverterHelper.GetNullableBooleanValue(value);
if(booleanValue != null)
booleanValue = !booleanValue.Value;
if(targetType == typeof(bool)) return booleanValue ?? true;
return booleanValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
return Convert(value, targetType, parameter, culture);
}
}
public class FormatStringConverter : IValueConverter {
public string FormatString { get; set; }
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return GetFormattedValue(FormatString, value, System.Globalization.CultureInfo.CurrentUICulture);
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotSupportedException();
}
public static object GetFormattedValue(string formatString, object value, System.Globalization.CultureInfo culture) {
string displayFormat = GetDisplayFormat(formatString);
return string.IsNullOrEmpty(displayFormat) ? value : string.Format(culture, displayFormat, value);
}
static string GetDisplayFormat(string displayFormat) {
if(string.IsNullOrEmpty(displayFormat))
return string.Empty;
string res = displayFormat;
if(res.Contains("{"))
return res;
return string.Format("{{0:{0}}}", res);
}
}
public class BooleanToObjectConverter : IValueConverter {
public object TrueValue { get; set; }
public object FalseValue { get; set; }
public object NullValue { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if(value is bool?) {
value = (bool?)value == true;
}
if(value == null) {
return NullValue;
}
if(!(value is bool))
return null;
bool asBool = (bool)value;
return asBool ? TrueValue : FalseValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
static class ConverterHelper {
public static string[] GetParameters(object parameter) {
string param = parameter as string;
if(string.IsNullOrEmpty(param))
return new string[0];
return param.Split(';');
}
public static bool GetBooleanParameter(string[] parameters, string name) {
foreach(string parameter in parameters) {
if(string.Equals(parameter, name, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
public static bool GetBooleanValue(object value) {
if(value is bool)
return (bool)value;
if(value is bool?) {
bool? nullable = (bool?)value;
return nullable.HasValue ? nullable.Value : false;
}
return false;
}
public static bool? GetNullableBooleanValue(object value) {
if(value is bool) return (bool)value;
if(value is bool?) return (bool?)value;
return null;
}
public static bool NumericToBoolean(object value) {
if(value == null)
return false;
try {
var d = (double)System.Convert.ChangeType(value, typeof(double), null);
return d != 0d;
} catch (Exception) { }
return false;
}
public static Visibility BooleanToVisibility(bool booleanValue, bool inverse, bool hiddenInsteadOfCollapsed) {
return (booleanValue ^ inverse) ?
Visibility.Visible :
#if !SILVERLIGHT && !NETFX_CORE
(hiddenInsteadOfCollapsed ? Visibility.Hidden : Visibility.Collapsed);
#else
Visibility.Collapsed;
#endif
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false)]
[ComVisible(true)]
public class FolderNode : HierarchyNode
{
#region ctors
/// <summary>
/// Constructor for the FolderNode
/// </summary>
/// <param name="root">Root node of the hierarchy</param>
/// <param name="relativePath">relative path from root i.e.: "NewFolder1\\NewFolder2\\NewFolder3</param>
/// <param name="element">Associated project element</param>
public FolderNode(ProjectNode root, string relativePath, ProjectElement element)
: base(root, element)
{
if (relativePath == null)
{
throw new ArgumentNullException("relativePath");
}
this.VirtualNodeName = relativePath.TrimEnd('\\');
}
#endregion
#region overridden properties
public override int SortPriority
{
get { return DefaultSortOrderNode.FolderNode; }
}
/// <summary>
/// This relates to the SCC glyph
/// </summary>
public override VsStateIcon StateIconIndex
{
get
{
// The SCC manager does not support being asked for the state icon of a folder (result of the operation is undefined)
return VsStateIcon.STATEICON_NOSTATEICON;
}
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject()
{
return new FolderNodeProperties(this);
}
protected internal override void DeleteFromStorage(string path)
{
this.DeleteFolder(path);
}
/// <summary>
/// Get the automation object for the FolderNode
/// </summary>
/// <returns>An instance of the Automation.OAFolderNode type if succeeded</returns>
public override object GetAutomationObject()
{
if(this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OAFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
public override object GetIconHandle(bool open)
{
return this.ProjectMgr.ImageHandler.GetIconHandle(open ? (int)ProjectNode.ImageName.OpenFolder : (int)ProjectNode.ImageName.Folder);
}
/// <summary>
/// Rename Folder
/// </summary>
/// <param name="label">new Name of Folder</param>
/// <returns>VSConstants.S_OK, if succeeded</returns>
public override int SetEditLabel(string label)
{
if(String.Compare(Path.GetFileName(this.Url.TrimEnd('\\')), label, StringComparison.Ordinal) == 0)
{
// Label matches current Name
return VSConstants.S_OK;
}
string newPath = Path.Combine(new DirectoryInfo(this.Url).Parent.FullName, label);
// Verify that No Directory/file already exists with the new name among current children
for(HierarchyNode n = Parent.FirstChild; n != null; n = n.NextSibling)
{
if(n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0)
{
return ShowFileOrFolderAlreadExistsErrorMessage(newPath);
}
}
// Verify that No Directory/file already exists with the new name on disk
if(Directory.Exists(newPath) || File.Exists(newPath))
{
return ShowFileOrFolderAlreadExistsErrorMessage(newPath);
}
try
{
RenameFolder(label);
//Refresh the properties in the properties window
IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
// Notify the listeners that the name of this folder is changed. This will
// also force a refresh of the SolutionExplorer's node.
this.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);
}
catch(Exception e)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.RenameFolder, CultureInfo.CurrentUICulture), e.Message));
}
return VSConstants.S_OK;
}
public override int MenuCommandId
{
get { return VsMenus.IDM_VS_CTXT_FOLDERNODE; }
}
public override Guid ItemTypeGuid
{
get
{
return VSConstants.GUID_ItemType_PhysicalFolder;
}
}
public override string Url
{
get
{
return Path.Combine(Path.GetDirectoryName(this.ProjectMgr.Url), this.VirtualNodeName) + "\\";
}
}
public override string Caption
{
get
{
// it might have a backslash at the end...
// and it might consist of Grandparent\parent\this\
string caption = this.VirtualNodeName;
string[] parts;
parts = caption.Split(Path.DirectorySeparatorChar);
caption = parts[parts.GetUpperBound(0)];
return caption;
}
}
public override string GetMkDocument()
{
Debug.Assert(this.Url != null, "No url sepcified for this node");
return this.Url;
}
/// <summary>
/// Enumerate the files associated with this node.
/// A folder node is not a file and as such no file to enumerate.
/// </summary>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
protected internal override void GetSccFiles(System.Collections.Generic.IList<string> files, System.Collections.Generic.IList<tagVsSccFilesFlags> flags)
{
return;
}
/// <summary>
/// This method should be overridden to provide the list of special files and associated flags for source control.
/// </summary>
/// <param name="sccFile">One of the file associated to the node.</param>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "scc")]
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags)
{
if(this.ExcludeNodeFromScc)
{
return;
}
if(files == null)
{
throw new ArgumentNullException("files");
}
if(flags == null)
{
throw new ArgumentNullException("flags");
}
if(string.IsNullOrEmpty(sccFile))
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "sccFile");
}
// Get the file node for the file passed in.
FileNode node = this.FindChild(sccFile) as FileNode;
// Dependents do not participate directly in scc.
if(node != null && !(node is DependentFileNode))
{
node.GetSccSpecialFiles(sccFile, files, flags);
}
}
/// <summary>
/// Recursevily walks the folder nodes and redraws the state icons
/// </summary>
protected internal override void UpdateSccStateIcons()
{
for(HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling)
{
child.UpdateSccStateIcons();
}
}
protected override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
if(cmdGroup == VsMenus.guidStandardCommandSet97)
{
switch((VsCommands)cmd)
{
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.NewFolder:
case VsCommands.AddNewItem:
case VsCommands.AddExistingItem:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else if(cmdGroup == VsMenus.guidStandardCommandSet2K)
{
if((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT)
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else
{
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
protected override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
if(deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage)
{
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
#endregion
#region virtual methods
/// <summary>
/// Override if your node is not a file system folder so that
/// it does nothing or it deletes it from your storage location.
/// </summary>
/// <param name="path">Path to the folder to delete</param>
public virtual void DeleteFolder(string path)
{
if(Directory.Exists(path))
Directory.Delete(path, true);
}
/// <summary>
/// creates the physical directory for a folder node
/// Override if your node does not use file system folder
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "e")]
public virtual void CreateDirectory()
{
try
{
if(Directory.Exists(this.Url) == false)
{
Directory.CreateDirectory(this.Url);
}
}
//TODO - this should not digest all exceptions.
catch(System.Exception e)
{
CCITracing.Trace(e);
throw;
}
}
/// <summary>
/// Creates a folder nodes physical directory
/// Override if your node does not use file system folder
/// </summary>
/// <param name="newName"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "e")]
public virtual void CreateDirectory(string newName)
{
if(String.IsNullOrEmpty(newName))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newName");
}
try
{
// on a new dir && enter, we get called with the same name (so do nothing if name is the same
char[] dummy = new char[1];
dummy[0] = Path.DirectorySeparatorChar;
string oldDir = this.Url;
oldDir = oldDir.TrimEnd(dummy);
string strNewDir = Path.Combine(Path.GetDirectoryName(oldDir), newName);
if(String.Compare(strNewDir, oldDir, StringComparison.OrdinalIgnoreCase) != 0)
{
if(Directory.Exists(strNewDir))
{
throw new InvalidOperationException(SR.GetString(SR.DirectoryExistError, CultureInfo.CurrentUICulture));
}
Directory.CreateDirectory(strNewDir);
}
}
//TODO - this should not digest all exceptions.
catch(System.Exception e)
{
CCITracing.Trace(e);
throw;
}
}
/// <summary>
/// Rename the physical directory for a folder node
/// Override if your node does not use file system folder
/// </summary>
/// <returns></returns>
public virtual void RenameDirectory(string newPath)
{
if(Directory.Exists(this.Url))
{
if(Directory.Exists(newPath))
{
ShowFileOrFolderAlreadExistsErrorMessage(newPath);
}
Directory.Move(this.Url, newPath);
}
}
#endregion
#region helper methods
// Made public for IronStudio directory based projects:
public void RenameFolder(string newName)
{
// Do the rename (note that we only do the physical rename if the leaf name changed)
string newPath = Path.Combine(this.Parent.VirtualNodeName, newName);
if(String.Compare(Path.GetFileName(VirtualNodeName), newName, StringComparison.Ordinal) != 0)
{
this.RenameDirectory(Path.Combine(this.ProjectMgr.ProjectFolder, newPath));
}
this.VirtualNodeName = newPath;
this.ItemNode.Rename(VirtualNodeName);
// Let all children know of the new path
for(HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling)
{
FolderNode node = child as FolderNode;
if(node == null)
{
child.SetEditLabel(child.Caption);
}
else
{
node.RenameFolder(node.Caption);
}
}
// Some of the previous operation may have changed the selection so set it back to us
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
ErrorHandler.ThrowOnFailure(uiWindow.ExpandItem(this.ProjectMgr, this.ID, EXPANDFLAGS.EXPF_SelectItem));
}
/// <summary>
/// Show error message if not in automation mode, otherwise throw exception
/// </summary>
/// <param name="newPath">path of file or folder already existing on disk</param>
/// <returns>S_OK</returns>
private int ShowFileOrFolderAlreadExistsErrorMessage(string newPath)
{
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
//If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu.
string errorMessage = (String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileOrFolderAlreadyExists, CultureInfo.CurrentUICulture), newPath));
if(!Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
string title = null;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton);
return VSConstants.S_OK;
}
else
{
throw new InvalidOperationException(errorMessage);
}
}
#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 Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for RouteFilterRulesOperations.
/// </summary>
public static partial class RouteFilterRulesOperationsExtensions
{
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
public static void Delete(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName)
{
operations.DeleteAsync(resourceGroupName, routeFilterName, ruleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified rule from a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
public static RouteFilterRule Get(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName)
{
return operations.GetAsync(resourceGroupName, routeFilterName, ruleName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified rule from a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilterRule> GetAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule operation.
/// </param>
public static RouteFilterRule CreateOrUpdate(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilterRule> CreateOrUpdateAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule operation.
/// </param>
public static RouteFilterRule Update(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters)
{
return operations.UpdateAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilterRule> UpdateAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
public static IPage<RouteFilterRule> ListByRouteFilter(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName)
{
return operations.ListByRouteFilterAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilterRule>> ListByRouteFilterAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByRouteFilterWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
public static void BeginDelete(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName)
{
operations.BeginDeleteAsync(resourceGroupName, routeFilterName, ruleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule operation.
/// </param>
public static RouteFilterRule BeginCreateOrUpdate(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilterRule> BeginCreateOrUpdateAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule operation.
/// </param>
public static RouteFilterRule BeginUpdate(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters)
{
return operations.BeginUpdateAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilterRule> BeginUpdateAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteFilterRule> ListByRouteFilterNext(this IRouteFilterRulesOperations operations, string nextPageLink)
{
return operations.ListByRouteFilterNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilterRule>> ListByRouteFilterNextAsync(this IRouteFilterRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByRouteFilterNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// -----
// Copyright 2010 Deyan Timnev
// This file is part of the Matrix Platform (www.matrixplatform.com).
// The Matrix Platform 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 3 of the License, or (at your option) any later version. The Matrix Platform 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 the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html
// -----
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Threading;
using Matrix.Common.Core;
using Matrix.Common.Core.Collections;
using Matrix.Common.Extended;
using Matrix.Framework.MessageBus.Core;
using Matrix.Framework.SuperPool.Call;
using Matrix.Framework.SuperPool.Clients;
using Matrix.Framework.SuperPool.DynamicProxy;
using Matrix.Framework.SuperPool.Subscription;
#if Matrix_Diagnostics
using Matrix.Common.Diagnostics.TracerCore.Items;
#endif
namespace Matrix.Framework.SuperPool.Core
{
/// <summary>
/// Extend super pool with subscriptions and event management.
/// </summary>
public abstract class SuperPoolSubscription : SuperPoolCallbacks, ISuperPoolIntercom
{
object _syncRoot = new object();
/// <summary>
/// Client id (vs) subscription information for this client.
/// </summary>
Dictionary<ClientId, ClientEventsHandler> _clients = new Dictionary<ClientId, ClientEventsHandler>();
/// <summary>
/// Exteded event name (vs) method subscription information.
/// </summary>
HotSwapDictionary<string, EventSubscriptionInfo> _eventSubscriptions = new HotSwapDictionary<string, EventSubscriptionInfo>();
/// <summary>
/// Constructor.
/// </summary>
public SuperPoolSubscription()
{
}
/// <summary>
/// Dispose.
/// </summary>
public override void Dispose()
{
List<ClientEventsHandler> clients;
List<EventSubscriptionInfo> subscriptions;
lock (_syncRoot)
{
subscriptions = GeneralHelper.EnumerableToList<EventSubscriptionInfo>(_eventSubscriptions.Values);
// Clear methods first, thus removing clients is faster.
_eventSubscriptions.Clear();
// Take care to do an optimized hot swap teardown.
clients = GeneralHelper.EnumerableToList(_clients.Values);
_clients.Clear();
}
foreach (EventSubscriptionInfo methodSubscription in subscriptions)
{
methodSubscription.Dispose();
}
foreach (ClientEventsHandler clientInfo in clients)
{
clientInfo.Dispose();
}
base.Dispose();
}
protected override bool HandleClientAdded(IMessageBus messageBus, ClientId clientId)
{
// Make sure to have this done first, since it will send notifications of clients, and we
// may need those for the establishment of events.
if (base.HandleClientAdded(messageBus, clientId) == false || messageBus == null || clientId == null)
{
return false;
}
MessageBusClient clientInstance = messageBus.GetLocalClientInstance(clientId);
// Will only work for local AND MessageSuperPoolClient typed clients.
if (clientInstance is SuperPoolClient)
{
lock (_syncRoot)
{
if (_clients.ContainsKey(clientInstance.Id))
{// Already added.
return false;
}
ClientEventsHandler subscription = new ClientEventsHandler(this, (SuperPoolClient)clientInstance);
_clients.Add(clientInstance.Id, subscription);
}
}
else
{
List<string> sourceTypeNames = messageBus.GetClientSourceTypes(clientId);
if (sourceTypeNames == null)
{
#if Matrix_Diagnostics
InstanceMonitor.Error("Failed to obtain client [" + clientId.ToString() + "] source type.");
#endif
return false;
}
SuperPoolClient intercomClient = IntercomClient;
if (intercomClient == null)
{
#if Matrix_Diagnostics
InstanceMonitor.Error("Failed to obtain super pool main intercom client, so new client handling has failed.");
#endif
return false;
}
List<EventSubscriptionRequest> totalRequests = new List<EventSubscriptionRequest>();
if (clientId.IsLocalClientId == false)
{
// Gather all the Super Pool related interfaces and their events, and send global updates for those
// so that any pending subscriptions may be restored.
// This is only done where the client is a remote client instance, since local ones we already know
// of them. This eventing information must be at the local pool for the client, since it is the one
// handling the event and sending it to all interested parties.
foreach (Type interfaceType in ReflectionHelper.GetKnownTypes(sourceTypeNames))
{
if (interfaceType.IsInterface
&& ReflectionHelper.TypeHasCustomAttribute(interfaceType, typeof(SuperPoolInterfaceAttribute), false) == false)
{// Interface type not marked as super pool.
continue;
}
foreach (EventInfo info in interfaceType.GetEvents())
{
string eventName = GeneralHelper.GetEventMethodExtendedName(info, false);
EventSubscriptionInfo eventInfo;
if (_eventSubscriptions.TryGetValue(eventName, out eventInfo))
{
totalRequests.AddRange(eventInfo.GatherSourceRelatedUpdates(clientId));
}
}
}
}
// Send updates for the newly connected client, so that it can obtain any subscription information
// regarding it, it case it has missed some.
foreach (EventSubscriptionRequest request in totalRequests)
{
// Notify other connected super pools of this subcription,
// since the subscribee(s) may be attached on them.
// *pendingCall swap done here, make sure to not use it on or after this line*
intercomClient.CallAll<ISuperPoolIntercom>().ProcessSubscriptionUpdate(request);
}
}
return true;
}
/// <summary>
/// Remove all subscription references for this client.
/// </summary>
/// <returns></returns>
protected override bool HandleClientRemoved(IMessageBus messageBus, ClientId clientId, bool isPermanent)
{
if (base.HandleClientRemoved(messageBus, clientId, isPermanent) == false)
{
return false;
}
if (isPermanent)
{// Only cleanup subscriptions in case remove was permanent.
foreach (EventSubscriptionInfo subscription in _eventSubscriptions.Values)
{
subscription.RemoveClientSubscriptions(clientId);
}
}
ClientEventsHandler clientInfo = null;
lock (_syncRoot)
{
if (_clients.TryGetValue(clientId, out clientInfo) == false)
{// Client not added, possibly not a local client.
return true;
}
if (_clients.Remove(clientId) == false)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to remove client from subscription lists.");
#endif
}
}
if (clientInfo != null)
{
clientInfo.Dispose();
}
return true;
}
#region Public Invocation
#endregion
/// <summary>
/// Perform event subscription (Subscribe), always asynchronous.
/// </summary>
public bool Subscribe<TType>(SuperPoolClient subscriber,
EventSubscriptionRequest request, out TType resultValue)
where TType : class
{
SuperPoolProxyCall call;
bool result = Call<TType>(subscriber, out resultValue, out call);
call.SubscriptionRequest = request;
return result;
}
/// <summary>
/// Handle event subscription (Proxy.Event.Subscribe)
/// </summary>
protected override void ProcessReceiveEventSubscription(int methodId, Delegate delegateInstance, bool isAdd)
{
SuperPoolProxyCall pendingCall = null;
if (_pendingThreadsCalls.TryGetValue(Thread.CurrentThread.ManagedThreadId, out pendingCall) == false)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to find corresponding thread proxy call information.");
#endif
return;
}
EventSubscriptionRequest subscriptionRequest = pendingCall.SubscriptionRequest;
if (subscriptionRequest == null)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to find corresponding subscription requests, event subscription failed.");
#endif
return;
}
if (pendingCall.Sender == null || pendingCall.Sender.Id == null)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to establish subscription sender information, subscription failed.");
#endif
return;
}
if (delegateInstance.Target != pendingCall.Sender.Source)
{
#if Matrix_Diagnostics
InstanceMonitor.Error("Only a message super pool client source can subscribe to events.");
#endif
return;
}
ProxyTypeBuilder builder = ProxyTypeBuilder;
if (builder == null)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to find proxy type builder, event subscription failed.");
#endif
return;
}
GeneratedMethodInfo generatedMethodInfo = builder.GetMethodInfoById(methodId);
if (generatedMethodInfo == null)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to find method [id, " + methodId + "] info, event subscription failed.");
#endif
return;
}
if (string.IsNullOrEmpty(generatedMethodInfo.EventName))
{
generatedMethodInfo.EventName = GeneralHelper.GetEventExtendedNameByMethod(generatedMethodInfo.GetMethodInfo(), false, true);
}
// generatedMethodInfo.GetMethodInfo() >> I2.add_AEVent
string extendedEventName = generatedMethodInfo.EventName;
MethodInfo eventAddMethodInfo = generatedMethodInfo.GetMethodInfo();
// *IMPORTANT* the Call<> will cause the currently used pendingCall to be repopulated with information,
// so we ned to extract the *sender id* BEFORE calling the actual Call(), since it will change the
// pendingCall instance immediately.
subscriptionRequest.SenderId = pendingCall.Sender.Id;
subscriptionRequest.ExtendedEventName = extendedEventName;
subscriptionRequest.IsAdd = isAdd;
//subscriptionRequest.EventAddMethodInfo = eventAddMethodInfo;
subscriptionRequest.DelegateInstanceMethodInfo = delegateInstance.Method;
// Process locally.
((ISuperPoolIntercom)this).ProcessSubscriptionUpdate(subscriptionRequest);
SuperPoolClient mainClient = IntercomClient;
if (mainClient == null)
{
#if Matrix_Diagnostics
InstanceMonitor.Error("Failed to obtain super pool main intercom client, so new client handling has failed.");
#endif
}
else
{
// Notify other connected super pools of this subcription,
// since the subscribee(s) may be attached on them.
// *pendingCall swap done here, make sure to not use it on or after this line*
mainClient.CallAll<ISuperPoolIntercom>().ProcessSubscriptionUpdate(subscriptionRequest);
}
}
void ISuperPoolIntercom.ProcessSubscriptionUpdate(EventSubscriptionRequest subscriptionRequest)
{
// Filter request, since it may not be related at all to this super pool.
bool clientFound = false;
ReadOnlyCollection<ClientId> sources = subscriptionRequest.EventsSources;
if (sources == null)
{// Null value indicates a subscirption to all possible sources.
clientFound = true;
}
else
{
foreach (ClientId id in sources)
{
if (_clients.ContainsKey(id))
{
clientFound = true;
break;
}
}
}
// Check the sources and the SenderId, before dumping event.
if (clientFound == false && subscriptionRequest.SenderId.IsLocalClientId == false)
{
#if Matrix_Diagnostics
InstanceMonitor.Info("Subscription request received [" + subscriptionRequest.ToString() + "], ignored since not related.");
#endif
return;
}
else
{
#if Matrix_Diagnostics
InstanceMonitor.Info("Subscription request received [" + subscriptionRequest.ToString() + "] and processing...");
#endif
}
EventSubscriptionInfo methodSubscription = null;
if (_eventSubscriptions.TryGetValue(subscriptionRequest.ExtendedEventName, out methodSubscription) == false)
{
lock (_syncRoot)
{
if (_eventSubscriptions.TryGetValue(subscriptionRequest.ExtendedEventName, out methodSubscription) == false)
{// Add a new method subscription info.
methodSubscription = new EventSubscriptionInfo(subscriptionRequest.ExtendedEventName);
_eventSubscriptions.Add(subscriptionRequest.ExtendedEventName, methodSubscription);
}
}
}
if (methodSubscription == null)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to find method subscription, subscription failed.");
#endif
return;
}
// Apply the requests locally.
methodSubscription.SubscriptionUpdate(subscriptionRequest);
}
/// <summary>
/// Client source has raised an event, process it.
/// </summary>
internal object ProcessEventRaised(ClientEventsHandler client,
ClientEventsHandler.EventHandlingInformation eventSubscriptionInfo, Type returnType, object[] parameters)
{
if (string.IsNullOrEmpty(eventSubscriptionInfo.GeneratedMethodInfo.EventName))
{
// Establish the name of the event.
eventSubscriptionInfo.GeneratedMethodInfo.EventName =
GeneralHelper.GetEventMethodExtendedName(eventSubscriptionInfo.EventInfo, false);
}
EventSubscriptionInfo eventSubscription = null;
if (string.IsNullOrEmpty(eventSubscriptionInfo.GeneratedMethodInfo.EventName) == false &&
_eventSubscriptions.TryGetValue(eventSubscriptionInfo.GeneratedMethodInfo.EventName, out eventSubscription))
{// OK, to perform the calls.
// Process specific subscribers
foreach (KeyValuePair<ClientId, EventSubscriptionInfo.ClientEventSubscriptionInfo> pair
in eventSubscription.GetReceivers(client.Client.Id, true))
{
foreach(KeyValuePair<MethodInfo, int> subPair in pair.Value.Data)
{
for (int i = 0; i < subPair.Value; i++)
{// May need to raise multiple times.
if (client.Client.Id != pair.Key)
{// Filter out subscriptions by the one that raised it.
ProcessEventCall(client.Client.Id, pair.Key, subPair.Key, parameters);
}
}
}
}
// Process subscribe to all.
foreach (KeyValuePair<ClientId, EventSubscriptionInfo.ClientEventSubscriptionInfo> pair
in eventSubscription.GetReceivers(client.Client.Id, false))
{
foreach (KeyValuePair<MethodInfo, int> subPair in pair.Value.Data)
{
for (int i = 0; i < subPair.Value; i++)
{// May need to raise multiple times.
if (client.Client.Id != pair.Key)
{// Filter out subscriptions by the one that raised it.
ProcessEventCall(client.Client.Id, pair.Key, subPair.Key, parameters);
}
}
}
}
}
else
{// No subscription(s) for this event.
#if Matrix_Diagnostics
InstanceMonitor.Info(string.Format("Event raised [{0}] had no subscribers.", eventSubscriptionInfo.GeneratedMethodInfo.EventName), TracerItem.PriorityEnum.Trivial);
#endif
}
// Return a default value.
return ProxyTypeManager.GetTypeDefaultValue(returnType);
}
/// <summary>
/// Process an event call.
/// </summary>
void ProcessEventCall(ClientId senderId, ClientId receiverId,
MethodInfo targetMethodInfo, object[] parameters)
{
if (receiverId == null)
{
#if Matrix_Diagnostics
InstanceMonitor.Error("Proxy call receiver not received.");
#endif
return;
}
IMessageBus messageBus = MessageBus;
if (messageBus == null)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to find message bus (possible dispose).");
#endif
return;
}
SuperPoolCall call = new SuperPoolCall(GetUniqueCallId());
call.Parameters = parameters;
call.MethodInfoLocal = targetMethodInfo;
call.State = SuperPoolCall.StateEnum.EventRaise;
if (messageBus.Send(senderId, receiverId,
new Envelope(call) { DuplicationMode = Envelope.DuplicationModeEnum.None }, null, false) != Outcomes.Success)
{
#if Matrix_Diagnostics
InstanceMonitor.OperationError("Failed to send event proxy call.");
#endif
}
}
}
}
| |
#region License
/* SDL2# - C# Wrapper for SDL2
*
* Copyright (c) 2013-2016 Ethan Lee.
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in a
* product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
* Ethan "flibitijibibo" Lee <flibitijibibo@flibitijibibo.com>
*
*/
#endregion
#region Using Statements
using System;
using System.Runtime.InteropServices;
#endregion
namespace SDL2
{
public static class SDL_ttf
{
#region SDL2# Variables
/* Used by DllImport to load the native library. */
private const string nativeLibName = "SDL2_ttf.dll";
#endregion
#region SDL_ttf.h
/* Similar to the headers, this is the version we're expecting to be
* running with. You will likely want to check this somewhere in your
* program!
*/
public const int SDL_TTF_MAJOR_VERSION = 2;
public const int SDL_TTF_MINOR_VERSION = 0;
public const int SDL_TTF_PATCHLEVEL = 12;
public const int UNICODE_BOM_NATIVE = 0xFEFF;
public const int UNICODE_BOM_SWAPPED = 0xFFFE;
public const int TTF_STYLE_NORMAL = 0x00;
public const int TTF_STYLE_BOLD = 0x01;
public const int TTF_STYLE_ITALIC = 0x02;
public const int TTF_STYLE_UNDERLINE = 0x04;
public const int TTF_STYLE_STRIKETHROUGH = 0x08;
public const int TTF_HINTING_NORMAL = 0;
public const int TTF_HINTING_LIGHT = 1;
public const int TTF_HINTING_MONO = 2;
public const int TTF_HINTING_NONE = 3;
public static void SDL_TTF_VERSION(out SDL.SDL_version X)
{
X.major = SDL_TTF_MAJOR_VERSION;
X.minor = SDL_TTF_MINOR_VERSION;
X.patch = SDL_TTF_PATCHLEVEL;
}
[DllImport(nativeLibName, EntryPoint = "TTF_LinkedVersion", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr INTERNAL_TTF_LinkedVersion();
public static SDL.SDL_version TTF_LinkedVersion()
{
SDL.SDL_version result;
IntPtr result_ptr = INTERNAL_TTF_LinkedVersion();
result = (SDL.SDL_version) Marshal.PtrToStructure(
result_ptr,
typeof(SDL.SDL_version)
);
return result;
}
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void TTF_ByteSwappedUNICODE(int swapped);
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_Init();
/* IntPtr refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_OpenFont(
[In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))]
string file,
int ptsize
);
/* src refers to an SDL_RWops*, IntPtr to a TTF_Font* */
/* THIS IS A PUBLIC RWops FUNCTION! */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_OpenFontRW(
IntPtr src,
int freesrc,
int ptsize
);
/* IntPtr refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_OpenFontIndex(
[In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))]
string file,
int ptsize,
long index
);
/* src refers to an SDL_RWops*, IntPtr to a TTF_Font* */
/* THIS IS A PUBLIC RWops FUNCTION! */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_OpenFontIndexRW(
IntPtr src,
int freesrc,
int ptsize,
long index
);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_GetFontStyle(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void TTF_SetFontStyle(IntPtr font, int style);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_GetFontOutline(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void TTF_SetFontOutline(IntPtr font, int outline);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_GetFontHinting(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void TTF_SetFontHinting(IntPtr font, int hinting);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_FontHeight(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_FontAscent(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_FontDescent(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_FontLineSkip(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_GetFontKerning(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void TTF_SetFontKerning(IntPtr font, int allowed);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern long TTF_FontFaces(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_FontFaceIsFixedWidth(IntPtr font);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
[return : MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler), MarshalCookie = LPUtf8StrMarshaler.LeaveAllocated)]
public static extern string TTF_FontFaceFamilyName(
IntPtr font
);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
[return : MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler), MarshalCookie = LPUtf8StrMarshaler.LeaveAllocated)]
public static extern string TTF_FontFaceStyleName(
IntPtr font
);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_GlyphIsProvided(IntPtr font, ushort ch);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_GlyphMetrics(
IntPtr font,
ushort ch,
out int minx,
out int maxx,
out int miny,
out int maxy,
out int advance
);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_SizeText(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))]
string text,
out int w,
out int h
);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_SizeUTF8(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))]
string text,
out int w,
out int h
);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_SizeUNICODE(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPWStr)]
string text,
out int w,
out int h
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderText_Solid(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPStr)]
string text,
SDL.SDL_Color fg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderUTF8_Solid(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))]
string text,
SDL.SDL_Color fg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderUNICODE_Solid(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPWStr)]
string text,
SDL.SDL_Color fg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderGlyph_Solid(
IntPtr font,
ushort ch,
SDL.SDL_Color fg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderText_Shaded(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPStr)]
string text,
SDL.SDL_Color fg,
SDL.SDL_Color bg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderUTF8_Shaded(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))]
string text,
SDL.SDL_Color fg,
SDL.SDL_Color bg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderUNICODE_Shaded(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPWStr)]
string text,
SDL.SDL_Color fg,
SDL.SDL_Color bg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderGlyph_Shaded(
IntPtr font,
ushort ch,
SDL.SDL_Color fg,
SDL.SDL_Color bg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderText_Blended(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPStr)]
string text,
SDL.SDL_Color fg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderUTF8_Blended(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))]
string text,
SDL.SDL_Color fg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderUNICODE_Blended(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPWStr)]
string text,
SDL.SDL_Color fg
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderText_Blended_Wrapped(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPStr)]
string text,
SDL.SDL_Color fg,
uint wrapped
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderUTF8_Blended_Wrapped(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))]
string text,
SDL.SDL_Color fg,
uint wrapped
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderUNICODE_Blended_Wrapped(
IntPtr font,
[In()] [MarshalAs(UnmanagedType.LPWStr)]
string text,
SDL.SDL_Color fg,
uint wrapped
);
/* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr TTF_RenderGlyph_Blended(
IntPtr font,
ushort ch,
SDL.SDL_Color fg
);
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void TTF_CloseFont(IntPtr font);
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void TTF_Quit();
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int TTF_WasInit();
/* font refers to a TTF_Font* */
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int SDL_GetFontKerningSize(
IntPtr font,
int prev_index,
int index
);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FluentNHibernate.Automapping.TestFixtures;
using FluentNHibernate.Conventions.Helpers.Builders;
using FluentNHibernate.Conventions.Instances;
using FluentNHibernate.Mapping;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.Collections;
using FluentNHibernate.Testing.FluentInterfaceTests;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionsTests.ApplyingToModel
{
[TestFixture]
public class HasManyToManyConventionTests
{
private PersistenceModel model;
[SetUp]
public void CreatePersistenceModel()
{
model = new PersistenceModel();
}
[Test]
public void ShouldSetAccessProperty()
{
Convention(x => x.Access.Property());
VerifyModel(x => x.Access.ShouldEqual("property"));
}
[Test]
public void ShouldSetBatchSizeProperty()
{
Convention(x => x.BatchSize(100));
VerifyModel(x => x.BatchSize.ShouldEqual(100));
}
[Test]
public void ShouldSetCacheProperty()
{
Convention(x => x.Cache.ReadWrite());
VerifyModel(x => x.Cache.Usage.ShouldEqual("read-write"));
}
[Test]
public void ShouldSetCascadeProperty()
{
Convention(x => x.Cascade.None());
VerifyModel(x => x.Cascade.ShouldEqual("none"));
}
[Test]
public void ShouldSetCheckConstraintProperty()
{
Convention(x => x.Check("constraint = 0"));
VerifyModel(x => x.Check.ShouldEqual("constraint = 0"));
}
[Test]
public void ShouldSetCollectionTypeProperty()
{
Convention(x => x.CollectionType<string>());
VerifyModel(x => x.CollectionType.GetUnderlyingSystemType().ShouldEqual(typeof(string)));
}
[Test]
public void ShouldSetFetchProperty()
{
Convention(x => x.Fetch.Select());
VerifyModel(x => x.Fetch.ShouldEqual("select"));
}
[Test]
public void ShouldSetGenericProperty()
{
Convention(x => x.Generic());
VerifyModel(x => x.Generic.ShouldBeTrue());
}
[Test]
public void ShouldSetInverseProperty()
{
Convention(x => x.Inverse());
VerifyModel(x => x.Inverse.ShouldBeTrue());
}
[Test]
public void ShouldSetParentKeyColumnNameProperty()
{
Convention(x => x.Key.Column("xxx"));
VerifyModel(x => x.Key.Columns.First().Name.ShouldEqual("xxx"));
}
[Test]
public void ShouldSetElementColumnNameProperty()
{
Convention(x => x.Element.Column("xxx"));
VerifyModel(x => x.Element.Columns.First().Name.ShouldEqual("xxx"));
}
[Test]
public void ShouldSetElementTypePropertyUsingGeneric()
{
Convention(x => x.Element.Type<string>());
VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string)));
}
[Test]
public void ShouldSetElementTypePropertyUsingTypeOf()
{
Convention(x => x.Element.Type(typeof(string)));
VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string)));
}
[Test]
public void ShouldSetElementTypePropertyUsingString() {
Convention(x => x.Element.Type(typeof(string).AssemblyQualifiedName));
VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string)));
}
[Test]
public void ShouldSetChildKeyColumnNameProperty()
{
Convention(x => x.Relationship.Column("xxx"));
VerifyModel(x => ((ManyToManyMapping)x.Relationship).Columns.First().Name.ShouldEqual("xxx"));
}
[Test]
public void ShouldSetLazyProperty()
{
Convention(x => x.LazyLoad());
VerifyModel(x => x.Lazy.ShouldEqual(Lazy.True));
}
[Test]
public void ShouldSetOptimisticLockProperty()
{
Convention(x => x.OptimisticLock());
VerifyModel(x => x.OptimisticLock.ShouldEqual(true));
}
[Test]
public void ShouldSetPersisterProperty()
{
Convention(x => x.Persister<SecondCustomPersister>());
VerifyModel(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(SecondCustomPersister)));
}
[Test]
public void ShouldSetSchemaProperty()
{
Convention(x => x.Schema("test"));
VerifyModel(x => x.Schema.ShouldEqual("test"));
}
[Test]
public void ShouldSetWhereProperty()
{
Convention(x => x.Where("y = 2"));
VerifyModel(x => x.Where.ShouldEqual("y = 2"));
}
[Test]
public void ShouldSetTableNameProperty()
{
Convention(x => x.Table("xxx"));
VerifyModel(x => x.TableName.ShouldEqual("xxx"));
}
[Test]
public void ShouldSetParentForeignKeyProperty()
{
Convention(x => x.Key.ForeignKey("xxx"));
VerifyModel(x => x.Key.ForeignKey.ShouldEqual("xxx"));
}
[Test]
public void ShouldSetParentPropertyRefProperty()
{
Convention(x => x.Key.PropertyRef("xxx"));
VerifyModel(x => x.Key.PropertyRef.ShouldEqual("xxx"));
}
[Test]
public void ShouldSetChildForeignKeyProperty()
{
Convention(x => x.Relationship.ForeignKey("xxx"));
VerifyModel(x => ((ManyToManyMapping)x.Relationship).ForeignKey.ShouldEqual("xxx"));
}
[Test]
public void ShouldSetRelationshipWhereProperty()
{
Convention(x => x.Relationship.Where("where clause"));
VerifyModel(x => ((ManyToManyMapping)x.Relationship).Where.ShouldEqual("where clause"));
}
[Test]
public void ShouldSetOrderByProperty()
{
Convention(x => x.Relationship.OrderBy("order clause"));
VerifyModel(x => ((ManyToManyMapping)x.Relationship).OrderBy.ShouldEqual("order clause"));
}
#region Helpers
private void Convention(Action<IManyToManyCollectionInstance> convention)
{
model.Conventions.Add(new ManyToManyCollectionConventionBuilder().Always(convention));
}
private void VerifyModel(Action<CollectionMapping> modelVerification)
{
var classMap = new ClassMap<ExampleInheritedClass>();
classMap.Id(x => x.Id);
var map = classMap.HasManyToMany(x => x.Children);
model.Add(classMap);
var generatedModels = model.BuildMappings();
var modelInstance = generatedModels
.First(x => x.Classes.FirstOrDefault(c => c.Type == typeof(ExampleInheritedClass)) != null)
.Classes.First()
.Collections.First();
modelVerification(modelInstance);
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Content.Client.Arcade.UI;
using Content.Client.Resources;
using Content.Shared.Arcade;
using Content.Shared.Input;
using Robust.Client.Graphics;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
using static Robust.Client.UserInterface.Controls.BoxContainer;
namespace Content.Client.Arcade
{
public sealed class BlockGameMenu : DefaultWindow
{
private static readonly Color OverlayBackgroundColor = new(74,74,81,180);
private static readonly Color OverlayShadowColor = new(0,0,0,83);
private static readonly Vector2 BlockSize = new(15,15);
private readonly BlockGameBoundUserInterface _owner;
private readonly PanelContainer _mainPanel;
private BoxContainer _gameRootContainer;
private GridContainer _gameGrid = default!;
private GridContainer _nextBlockGrid = default!;
private GridContainer _holdBlockGrid = default!;
private readonly Label _pointsLabel;
private readonly Label _levelLabel;
private readonly Button _pauseButton;
private readonly PanelContainer _menuRootContainer;
private readonly Button _unpauseButton;
private readonly Control _unpauseButtonMargin;
private readonly Button _newGameButton;
private readonly Button _scoreBoardButton;
private readonly PanelContainer _gameOverRootContainer;
private readonly Label _finalScoreLabel;
private readonly Button _finalNewGameButton;
private readonly PanelContainer _highscoresRootContainer;
private readonly Label _localHighscoresLabel;
private readonly Label _globalHighscoresLabel;
private readonly Button _highscoreBackButton;
private bool _isPlayer = false;
private bool _gameOver = false;
public BlockGameMenu(BlockGameBoundUserInterface owner)
{
Title = Loc.GetString("blockgame-menu-title");
_owner = owner;
MinSize = SetSize = (410, 490);
var resourceCache = IoCManager.Resolve<IResourceCache>();
var backgroundTexture = resourceCache.GetTexture("/Textures/Interface/Nano/button.svg.96dpi.png");
_mainPanel = new PanelContainer();
#region Game Menu
// building the game container
_gameRootContainer = new BoxContainer
{
Orientation = LayoutOrientation.Vertical
};
_levelLabel = new Label
{
Align = Label.AlignMode.Center,
HorizontalExpand = true
};
_gameRootContainer.AddChild(_levelLabel);
_gameRootContainer.AddChild(new Control
{
MinSize = new Vector2(1,5)
});
_pointsLabel = new Label
{
Align = Label.AlignMode.Center,
HorizontalExpand = true
};
_gameRootContainer.AddChild(_pointsLabel);
_gameRootContainer.AddChild(new Control
{
MinSize = new Vector2(1,10)
});
var gameBox = new BoxContainer
{
Orientation = LayoutOrientation.Horizontal
};
gameBox.AddChild(SetupHoldBox(backgroundTexture));
gameBox.AddChild(new Control
{
MinSize = new Vector2(10,1)
});
gameBox.AddChild(SetupGameGrid(backgroundTexture));
gameBox.AddChild(new Control
{
MinSize = new Vector2(10,1)
});
gameBox.AddChild(SetupNextBox(backgroundTexture));
_gameRootContainer.AddChild(gameBox);
_gameRootContainer.AddChild(new Control
{
MinSize = new Vector2(1,10)
});
_pauseButton = new Button
{
Text = Loc.GetString("blockgame-menu-button-pause"),
TextAlign = Label.AlignMode.Center
};
_pauseButton.OnPressed += (e) => TryPause();
_gameRootContainer.AddChild(_pauseButton);
#endregion
_mainPanel.AddChild(_gameRootContainer);
#region Pause Menu
var pauseRootBack = new StyleBoxTexture
{
Texture = backgroundTexture,
Modulate = OverlayShadowColor
};
pauseRootBack.SetPatchMargin(StyleBox.Margin.All, 10);
_menuRootContainer = new PanelContainer
{
PanelOverride = pauseRootBack,
VerticalAlignment = VAlignment.Center,
HorizontalAlignment = HAlignment.Center
};
var pauseInnerBack = new StyleBoxTexture
{
Texture = backgroundTexture,
Modulate = OverlayBackgroundColor
};
pauseInnerBack.SetPatchMargin(StyleBox.Margin.All, 10);
var pauseMenuInnerPanel = new PanelContainer
{
PanelOverride = pauseInnerBack,
VerticalAlignment = VAlignment.Center,
HorizontalAlignment = HAlignment.Center
};
_menuRootContainer.AddChild(pauseMenuInnerPanel);
var pauseMenuContainer = new BoxContainer
{
Orientation = LayoutOrientation.Vertical,
HorizontalAlignment = HAlignment.Center,
VerticalAlignment = VAlignment.Center
};
_newGameButton = new Button
{
Text = Loc.GetString("blockgame-menu-button-new-game"),
TextAlign = Label.AlignMode.Center
};
_newGameButton.OnPressed += (e) =>
{
_owner.SendAction(BlockGamePlayerAction.NewGame);
};
pauseMenuContainer.AddChild(_newGameButton);
pauseMenuContainer.AddChild(new Control{MinSize = new Vector2(1,10)});
_scoreBoardButton = new Button
{
Text = Loc.GetString("blockgame-menu-button-scoreboard"),
TextAlign = Label.AlignMode.Center
};
_scoreBoardButton.OnPressed += (e) => _owner.SendAction(BlockGamePlayerAction.ShowHighscores);
pauseMenuContainer.AddChild(_scoreBoardButton);
_unpauseButtonMargin = new Control {MinSize = new Vector2(1, 10), Visible = false};
pauseMenuContainer.AddChild(_unpauseButtonMargin);
_unpauseButton = new Button
{
Text = Loc.GetString("blockgame-menu-button-unpause"),
TextAlign = Label.AlignMode.Center,
Visible = false
};
_unpauseButton.OnPressed += (e) =>
{
_owner.SendAction(BlockGamePlayerAction.Unpause);
};
pauseMenuContainer.AddChild(_unpauseButton);
pauseMenuInnerPanel.AddChild(pauseMenuContainer);
#endregion
#region Gameover Screen
var gameOverRootBack = new StyleBoxTexture
{
Texture = backgroundTexture,
Modulate = OverlayShadowColor
};
gameOverRootBack.SetPatchMargin(StyleBox.Margin.All, 10);
_gameOverRootContainer = new PanelContainer
{
PanelOverride = gameOverRootBack,
VerticalAlignment = VAlignment.Center,
HorizontalAlignment = HAlignment.Center
};
var gameOverInnerBack = new StyleBoxTexture
{
Texture = backgroundTexture,
Modulate = OverlayBackgroundColor
};
gameOverInnerBack.SetPatchMargin(StyleBox.Margin.All, 10);
var gameOverMenuInnerPanel = new PanelContainer
{
PanelOverride = gameOverInnerBack,
VerticalAlignment = VAlignment.Center,
HorizontalAlignment = HAlignment.Center
};
_gameOverRootContainer.AddChild(gameOverMenuInnerPanel);
var gameOverMenuContainer = new BoxContainer
{
Orientation = LayoutOrientation.Vertical,
HorizontalAlignment = HAlignment.Center,
VerticalAlignment = VAlignment.Center
};
gameOverMenuContainer.AddChild(new Label{Text = Loc.GetString("blockgame-menu-msg-game-over"),Align = Label.AlignMode.Center});
gameOverMenuContainer.AddChild(new Control{MinSize = new Vector2(1,10)});
_finalScoreLabel = new Label{Align = Label.AlignMode.Center};
gameOverMenuContainer.AddChild(_finalScoreLabel);
gameOverMenuContainer.AddChild(new Control{MinSize = new Vector2(1,10)});
_finalNewGameButton = new Button
{
Text = Loc.GetString("blockgame-menu-button-new-game"),
TextAlign = Label.AlignMode.Center
};
_finalNewGameButton.OnPressed += (e) =>
{
_owner.SendAction(BlockGamePlayerAction.NewGame);
};
gameOverMenuContainer.AddChild(_finalNewGameButton);
gameOverMenuInnerPanel.AddChild(gameOverMenuContainer);
#endregion
#region High Score Screen
var rootBack = new StyleBoxTexture
{
Texture = backgroundTexture,
Modulate = OverlayShadowColor
};
rootBack.SetPatchMargin(StyleBox.Margin.All, 10);
_highscoresRootContainer = new PanelContainer
{
PanelOverride = rootBack,
VerticalAlignment = VAlignment.Center,
HorizontalAlignment = HAlignment.Center
};
var c = new Color(OverlayBackgroundColor.R,OverlayBackgroundColor.G,OverlayBackgroundColor.B,220);
var innerBack = new StyleBoxTexture
{
Texture = backgroundTexture,
Modulate = c
};
innerBack.SetPatchMargin(StyleBox.Margin.All, 10);
var menuInnerPanel = new PanelContainer
{
PanelOverride = innerBack,
VerticalAlignment = VAlignment.Center,
HorizontalAlignment = HAlignment.Center
};
_highscoresRootContainer.AddChild(menuInnerPanel);
var menuContainer = new BoxContainer
{
Orientation = LayoutOrientation.Vertical,
HorizontalAlignment = HAlignment.Center,
VerticalAlignment = VAlignment.Center
};
menuContainer.AddChild(new Label{Text = Loc.GetString("blockgame-menu-label-highscores")});
menuContainer.AddChild(new Control{MinSize = new Vector2(1,10)});
var highScoreBox = new BoxContainer
{
Orientation = LayoutOrientation.Horizontal
};
_localHighscoresLabel = new Label
{
Align = Label.AlignMode.Center
};
highScoreBox.AddChild(_localHighscoresLabel);
highScoreBox.AddChild(new Control{MinSize = new Vector2(40,1)});
_globalHighscoresLabel = new Label
{
Align = Label.AlignMode.Center
};
highScoreBox.AddChild(_globalHighscoresLabel);
menuContainer.AddChild(highScoreBox);
menuContainer.AddChild(new Control{MinSize = new Vector2(1,10)});
_highscoreBackButton = new Button
{
Text = Loc.GetString("blockgame-menu-button-back"),
TextAlign = Label.AlignMode.Center
};
_highscoreBackButton.OnPressed += (e) => _owner.SendAction(BlockGamePlayerAction.Pause);
menuContainer.AddChild(_highscoreBackButton);
menuInnerPanel.AddChild(menuContainer);
#endregion
Contents.AddChild(_mainPanel);
CanKeyboardFocus = true;
}
public void SetUsability(bool isPlayer)
{
_isPlayer = isPlayer;
UpdateUsability();
}
private void UpdateUsability()
{
_pauseButton.Disabled = !_isPlayer;
_newGameButton.Disabled = !_isPlayer;
_scoreBoardButton.Disabled = !_isPlayer;
_unpauseButton.Disabled = !_isPlayer;
_finalNewGameButton.Disabled = !_isPlayer;
_highscoreBackButton.Disabled = !_isPlayer;
}
private Control SetupGameGrid(Texture panelTex)
{
_gameGrid = new GridContainer
{
Columns = 10,
HSeparationOverride = 1,
VSeparationOverride = 1
};
UpdateBlocks(new BlockGameBlock[0]);
var back = new StyleBoxTexture
{
Texture = panelTex,
Modulate = Color.FromHex("#4a4a51"),
};
back.SetPatchMargin(StyleBox.Margin.All, 10);
var gamePanel = new PanelContainer
{
PanelOverride = back,
HorizontalExpand = true,
SizeFlagsStretchRatio = 60
};
var backgroundPanel = new PanelContainer
{
PanelOverride = new StyleBoxFlat{BackgroundColor = Color.FromHex("#86868d")}
};
backgroundPanel.AddChild(_gameGrid);
gamePanel.AddChild(backgroundPanel);
return gamePanel;
}
private Control SetupNextBox(Texture panelTex)
{
var previewBack = new StyleBoxTexture
{
Texture = panelTex,
Modulate = Color.FromHex("#4a4a51")
};
previewBack.SetPatchMargin(StyleBox.Margin.All, 10);
var grid = new GridContainer
{
Columns = 1,
HorizontalExpand = true,
SizeFlagsStretchRatio = 20
};
var nextBlockPanel = new PanelContainer
{
PanelOverride = previewBack,
MinSize = BlockSize * 6.5f,
HorizontalAlignment = HAlignment.Left,
VerticalAlignment = VAlignment.Top
};
var nextCenterContainer = new CenterContainer();
_nextBlockGrid = new GridContainer
{
HSeparationOverride = 1,
VSeparationOverride = 1
};
nextCenterContainer.AddChild(_nextBlockGrid);
nextBlockPanel.AddChild(nextCenterContainer);
grid.AddChild(nextBlockPanel);
grid.AddChild(new Label{Text = Loc.GetString("blockgame-menu-label-next"), Align = Label.AlignMode.Center});
return grid;
}
private Control SetupHoldBox(Texture panelTex)
{
var previewBack = new StyleBoxTexture
{
Texture = panelTex,
Modulate = Color.FromHex("#4a4a51")
};
previewBack.SetPatchMargin(StyleBox.Margin.All, 10);
var grid = new GridContainer
{
Columns = 1,
HorizontalExpand = true,
SizeFlagsStretchRatio = 20
};
var holdBlockPanel = new PanelContainer
{
PanelOverride = previewBack,
MinSize = BlockSize * 6.5f,
HorizontalAlignment = HAlignment.Left,
VerticalAlignment = VAlignment.Top
};
var holdCenterContainer = new CenterContainer();
_holdBlockGrid = new GridContainer
{
HSeparationOverride = 1,
VSeparationOverride = 1
};
holdCenterContainer.AddChild(_holdBlockGrid);
holdBlockPanel.AddChild(holdCenterContainer);
grid.AddChild(holdBlockPanel);
grid.AddChild(new Label{Text = Loc.GetString("blockgame-menu-label-hold"), Align = Label.AlignMode.Center});
return grid;
}
protected override void KeyboardFocusExited()
{
if (!IsOpen) return;
if(_gameOver) return;
TryPause();
}
private void TryPause()
{
_owner.SendAction(BlockGamePlayerAction.Pause);
}
public void SetStarted()
{
_gameOver = false;
_unpauseButton.Visible = true;
_unpauseButtonMargin.Visible = true;
}
public void SetScreen(BlockGameMessages.BlockGameScreen screen)
{
if (_gameOver) return;
switch (screen)
{
case BlockGameMessages.BlockGameScreen.Game:
GrabKeyboardFocus();
CloseMenus();
_pauseButton.Disabled = !_isPlayer;
break;
case BlockGameMessages.BlockGameScreen.Pause:
//ReleaseKeyboardFocus();
CloseMenus();
_mainPanel.AddChild(_menuRootContainer);
_pauseButton.Disabled = true;
break;
case BlockGameMessages.BlockGameScreen.Gameover:
_gameOver = true;
_pauseButton.Disabled = true;
//ReleaseKeyboardFocus();
CloseMenus();
_mainPanel.AddChild(_gameOverRootContainer);
break;
case BlockGameMessages.BlockGameScreen.Highscores:
//ReleaseKeyboardFocus();
CloseMenus();
_mainPanel.AddChild(_highscoresRootContainer);
break;
}
}
private void CloseMenus()
{
if(_mainPanel.Children.Contains(_menuRootContainer)) _mainPanel.RemoveChild(_menuRootContainer);
if(_mainPanel.Children.Contains(_gameOverRootContainer)) _mainPanel.RemoveChild(_gameOverRootContainer);
if(_mainPanel.Children.Contains(_highscoresRootContainer)) _mainPanel.RemoveChild(_highscoresRootContainer);
}
public void SetGameoverInfo(int amount, int? localPlacement, int? globalPlacement)
{
var globalPlacementText = globalPlacement == null ? "-" : $"#{globalPlacement}";
var localPlacementText = localPlacement == null ? "-" : $"#{localPlacement}";
_finalScoreLabel.Text =
Loc.GetString("blockgame-menu-gameover-info",
("global", globalPlacementText),
("local", localPlacementText),
("points", amount));
}
public void UpdatePoints(int points)
{
_pointsLabel.Text = Loc.GetString("blockgame-menu-label-points", ("points", points));
}
public void UpdateLevel(int level)
{
_levelLabel.Text = Loc.GetString("blockgame-menu-label-level", ("level", level + 1));
}
public void UpdateHighscores(List<BlockGameMessages.HighScoreEntry> localHighscores,
List<BlockGameMessages.HighScoreEntry> globalHighscores)
{
var localHighscoreText = new StringBuilder(Loc.GetString("blockgame-menu-text-station") + "\n");
var globalHighscoreText = new StringBuilder(Loc.GetString("blockgame-menu-text-nanotrasen") + "\n");
for (var i = 0; i < 5; i++)
{
localHighscoreText.AppendLine(localHighscores.Count > i
? $"#{i + 1}: {localHighscores[i].Name} - {localHighscores[i].Score}"
: $"#{i + 1}: ??? - 0");
globalHighscoreText.AppendLine(globalHighscores.Count > i
? $"#{i + 1}: {globalHighscores[i].Name} - {globalHighscores[i].Score}"
: $"#{i + 1}: ??? - 0");
}
_localHighscoresLabel.Text = localHighscoreText.ToString();
_globalHighscoresLabel.Text = globalHighscoreText.ToString();
}
protected override void KeyBindDown(GUIBoundKeyEventArgs args)
{
base.KeyBindDown(args);
if(!_isPlayer || args.Handled) return;
if (args.Function == ContentKeyFunctions.ArcadeLeft)
{
_owner.SendAction(BlockGamePlayerAction.StartLeft);
}
else if (args.Function == ContentKeyFunctions.ArcadeRight)
{
_owner.SendAction(BlockGamePlayerAction.StartRight);
}
else if (args.Function == ContentKeyFunctions.ArcadeUp)
{
_owner.SendAction(BlockGamePlayerAction.Rotate);
}
else if (args.Function == ContentKeyFunctions.Arcade3)
{
_owner.SendAction(BlockGamePlayerAction.CounterRotate);
}
else if (args.Function == ContentKeyFunctions.ArcadeDown)
{
_owner.SendAction(BlockGamePlayerAction.SoftdropStart);
}
else if (args.Function == ContentKeyFunctions.Arcade2)
{
_owner.SendAction(BlockGamePlayerAction.Hold);
}
else if (args.Function == ContentKeyFunctions.Arcade1)
{
_owner.SendAction(BlockGamePlayerAction.Harddrop);
}
}
protected override void KeyBindUp(GUIBoundKeyEventArgs args)
{
base.KeyBindUp(args);
if(!_isPlayer || args.Handled) return;
if (args.Function == ContentKeyFunctions.ArcadeLeft)
{
_owner.SendAction(BlockGamePlayerAction.EndLeft);
}
else if (args.Function == ContentKeyFunctions.ArcadeRight)
{
_owner.SendAction(BlockGamePlayerAction.EndRight);
}else if (args.Function == ContentKeyFunctions.ArcadeDown)
{
_owner.SendAction(BlockGamePlayerAction.SoftdropEnd);
}
}
public void UpdateNextBlock(BlockGameBlock[] blocks)
{
_nextBlockGrid.RemoveAllChildren();
if (blocks.Length == 0) return;
var columnCount = blocks.Max(b => b.Position.X) + 1;
var rowCount = blocks.Max(b => b.Position.Y) + 1;
_nextBlockGrid.Columns = columnCount;
for (int y = 0; y < rowCount; y++)
{
for (int x = 0; x < columnCount; x++)
{
var c = GetColorForPosition(blocks, x, y);
_nextBlockGrid.AddChild(new PanelContainer
{
PanelOverride = new StyleBoxFlat {BackgroundColor = c},
MinSize = BlockSize,
RectDrawClipMargin = 0
});
}
}
}
public void UpdateHeldBlock(BlockGameBlock[] blocks)
{
_holdBlockGrid.RemoveAllChildren();
if (blocks.Length == 0) return;
var columnCount = blocks.Max(b => b.Position.X) + 1;
var rowCount = blocks.Max(b => b.Position.Y) + 1;
_holdBlockGrid.Columns = columnCount;
for (int y = 0; y < rowCount; y++)
{
for (int x = 0; x < columnCount; x++)
{
var c = GetColorForPosition(blocks, x, y);
_holdBlockGrid.AddChild(new PanelContainer
{
PanelOverride = new StyleBoxFlat {BackgroundColor = c},
MinSize = BlockSize,
RectDrawClipMargin = 0
});
}
}
}
public void UpdateBlocks(BlockGameBlock[] blocks)
{
_gameGrid.RemoveAllChildren();
for (int y = 0; y < 20; y++)
{
for (int x = 0; x < 10; x++)
{
var c = GetColorForPosition(blocks, x, y);
_gameGrid.AddChild(new PanelContainer
{
PanelOverride = new StyleBoxFlat {BackgroundColor = c},
MinSize = BlockSize,
RectDrawClipMargin = 0
});
}
}
}
private Color GetColorForPosition(BlockGameBlock[] blocks, int x, int y)
{
Color c = Color.Transparent;
var matchingBlock = blocks.FirstOrNull(b => b.Position.X == x && b.Position.Y == y);
if (matchingBlock.HasValue)
{
c = BlockGameBlock.ToColor(matchingBlock.Value.GameBlockColor);
}
return c;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache.Affinity;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Log;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Impl.Unmanaged.Jni;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Resource;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// This class defines a factory for the main Ignite API.
/// <p/>
/// Use <see cref="Start()"/> method to start Ignite with default configuration.
/// <para/>
/// All members are thread-safe and may be used concurrently from multiple threads.
/// </summary>
public static class Ignition
{
/// <summary>
/// Default configuration section name.
/// </summary>
public const string ConfigurationSectionName = "igniteConfiguration";
/** */
private static readonly object SyncRoot = new object();
/** GC warning flag. */
private static int _gcWarn;
/** */
private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>();
/** Current DLL name. */
private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
/** Startup info. */
[ThreadStatic]
private static Startup _startup;
/** Client mode flag. */
[ThreadStatic]
private static bool _clientMode;
/// <summary>
/// Static initializer.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static Ignition()
{
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
}
/// <summary>
/// Gets or sets a value indicating whether Ignite should be started in client mode.
/// Client nodes cannot hold data in caches.
/// </summary>
public static bool ClientMode
{
get { return _clientMode; }
set { _clientMode = value; }
}
/// <summary>
/// Starts Ignite with default configuration. By default this method will
/// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c>
/// configuration file. If such file is not found, then all system defaults will be used.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite Start()
{
return Start(new IgniteConfiguration());
}
/// <summary>
/// Starts all grids specified within given Spring XML configuration file. If Ignite with given name
/// is already started, then exception is thrown. In this case all instances that may
/// have been started so far will be stopped too.
/// </summary>
/// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be
/// absolute or relative to IGNITE_HOME.</param>
/// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st
/// found instance is returned.</returns>
public static IIgnite Start(string springCfgPath)
{
return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath});
}
/// <summary>
/// Reads <see cref="IgniteConfiguration"/> from application configuration
/// <see cref="IgniteConfigurationSection"/> with <see cref="ConfigurationSectionName"/>
/// name and starts Ignite.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration()
{
// ReSharper disable once IntroduceOptionalParameters.Global
return StartFromApplicationConfiguration(ConfigurationSectionName);
}
/// <summary>
/// Reads <see cref="IgniteConfiguration"/> from application configuration
/// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration(string sectionName)
{
IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName");
var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection;
if (section == null)
throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'",
typeof(IgniteConfigurationSection).Name, sectionName));
if (section.IgniteConfiguration == null)
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteConfigurationSection).Name, sectionName));
return Start(section.IgniteConfiguration);
}
/// <summary>
/// Reads <see cref="IgniteConfiguration" /> from application configuration
/// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <param name="configPath">Path to the configuration file.</param>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration(string sectionName, string configPath)
{
IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName");
IgniteArgumentCheck.NotNullOrEmpty(configPath, "configPath");
var fileMap = GetConfigMap(configPath);
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var section = config.GetSection(sectionName) as IgniteConfigurationSection;
if (section == null)
throw new ConfigurationErrorsException(
string.Format("Could not find {0} with name '{1}' in file '{2}'",
typeof(IgniteConfigurationSection).Name, sectionName, configPath));
if (section.IgniteConfiguration == null)
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteConfigurationSection).Name, sectionName, configPath));
return Start(section.IgniteConfiguration);
}
/// <summary>
/// Gets the configuration file map.
/// </summary>
private static ExeConfigurationFileMap GetConfigMap(string fileName)
{
var fullFileName = Path.GetFullPath(fileName);
if (!File.Exists(fullFileName))
throw new ConfigurationErrorsException("Specified config file does not exist: " + fileName);
return new ExeConfigurationFileMap { ExeConfigFilename = fullFileName };
}
/// <summary>
/// Starts Ignite with given configuration.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite Start(IgniteConfiguration cfg)
{
IgniteArgumentCheck.NotNull(cfg, "cfg");
cfg = new IgniteConfiguration(cfg); // Create a copy so that config can be modified and reused.
lock (SyncRoot)
{
// 0. Init logger
var log = cfg.Logger ?? new JavaLogger();
log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version);
// 1. Check GC settings.
CheckServerGc(cfg, log);
// 2. Create context.
JvmDll.Load(cfg.JvmDllPath, log);
var cbs = IgniteManager.CreateJvmContext(cfg, log);
var env = cbs.Jvm.AttachCurrentThread();
log.Debug("JVM started.");
var gridName = cfg.IgniteInstanceName;
if (cfg.AutoGenerateIgniteInstanceName)
{
gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid();
}
// 3. Create startup object which will guide us through the rest of the process.
_startup = new Startup(cfg, cbs);
PlatformJniTarget interopProc = null;
try
{
// 4. Initiate Ignite start.
UU.IgnitionStart(env, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null, cbs.IgniteId,
cfg.RedirectJavaConsoleOutput);
// 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
var node = _startup.Ignite;
interopProc = (PlatformJniTarget)node.InteropProcessor;
var javaLogger = log as JavaLogger;
if (javaLogger != null)
{
javaLogger.SetIgnite(node);
}
// 6. On-start callback (notify lifecycle components).
node.OnStart();
Nodes[new NodeKey(_startup.Name)] = node;
return node;
}
catch (Exception ex)
{
// 1. Perform keys cleanup.
string name = _startup.Name;
if (name != null)
{
NodeKey key = new NodeKey(name);
if (Nodes.ContainsKey(key))
Nodes.Remove(key);
}
// 2. Stop Ignite node if it was started.
if (interopProc != null)
UU.IgnitionStop(gridName, true);
// 3. Throw error further (use startup error if exists because it is more precise).
if (_startup.Error != null)
{
// Wrap in a new exception to preserve original stack trace.
throw new IgniteException("Failed to start Ignite.NET, check inner exception for details",
_startup.Error);
}
var jex = ex as JavaException;
if (jex == null)
{
throw;
}
throw ExceptionUtils.GetException(null, jex);
}
finally
{
var ignite = _startup.Ignite;
_startup = null;
if (ignite != null)
{
ignite.ProcessorReleaseStart();
}
}
}
}
/// <summary>
/// Check whether GC is set to server mode.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="log">Log.</param>
private static void CheckServerGc(IgniteConfiguration cfg, ILogger log)
{
if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0)
log.Warn("GC server mode is not enabled, this could lead to less " +
"than optimal performance on multi-core machines (to enable see " +
"http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx).");
}
/// <summary>
/// Prepare callback invoked from Java.
/// </summary>
/// <param name="inStream">Input stream with data.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="handleRegistry">Handle registry.</param>
/// <param name="log">Log.</param>
internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream,
HandleRegistry handleRegistry, ILogger log)
{
try
{
BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream);
PrepareConfiguration(reader, outStream, log);
PrepareLifecycleHandlers(reader, outStream, handleRegistry);
PrepareAffinityFunctions(reader, outStream);
outStream.SynchronizeOutput();
}
catch (Exception e)
{
_startup.Error = e;
throw;
}
}
/// <summary>
/// Prepare configuration.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="outStream">Response stream.</param>
/// <param name="log">Log.</param>
private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream, ILogger log)
{
// 1. Load assemblies.
IgniteConfiguration cfg = _startup.Configuration;
LoadAssemblies(cfg.Assemblies);
ICollection<string> cfgAssembllies;
BinaryConfiguration binaryCfg;
BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg);
LoadAssemblies(cfgAssembllies);
// 2. Create marshaller only after assemblies are loaded.
if (cfg.BinaryConfiguration == null)
cfg.BinaryConfiguration = binaryCfg;
_startup.Marshaller = new Marshaller(cfg.BinaryConfiguration, log);
// 3. Send configuration details to Java
cfg.Validate(log);
cfg.Write(BinaryUtils.Marshaller.StartMarshal(outStream)); // Use system marshaller.
}
/// <summary>
/// Prepare lifecycle handlers.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="handleRegistry">Handle registry.</param>
private static void PrepareLifecycleHandlers(IBinaryRawReader reader, IBinaryStream outStream,
HandleRegistry handleRegistry)
{
IList<LifecycleHandlerHolder> beans = new List<LifecycleHandlerHolder>
{
new LifecycleHandlerHolder(new InternalLifecycleHandler()) // add internal bean for events
};
// 1. Read beans defined in Java.
int cnt = reader.ReadInt();
for (int i = 0; i < cnt; i++)
beans.Add(new LifecycleHandlerHolder(CreateObject<ILifecycleHandler>(reader)));
// 2. Append beans defined in local configuration.
ICollection<ILifecycleHandler> nativeBeans = _startup.Configuration.LifecycleHandlers;
if (nativeBeans != null)
{
foreach (ILifecycleHandler nativeBean in nativeBeans)
beans.Add(new LifecycleHandlerHolder(nativeBean));
}
// 3. Write bean pointers to Java stream.
outStream.WriteInt(beans.Count);
foreach (LifecycleHandlerHolder bean in beans)
outStream.WriteLong(handleRegistry.AllocateCritical(bean));
// 4. Set beans to STARTUP object.
_startup.LifecycleHandlers = beans;
}
/// <summary>
/// Prepares the affinity functions.
/// </summary>
private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream)
{
var cnt = reader.ReadInt();
var writer = reader.Marshaller.StartMarshal(outStream);
for (var i = 0; i < cnt; i++)
{
var objHolder = new ObjectInfoHolder(reader);
AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder);
}
}
/// <summary>
/// Creates an object and sets the properties.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Resulting object.</returns>
private static T CreateObject<T>(IBinaryRawReader reader)
{
return IgniteUtils.CreateInstance<T>(reader.ReadString(),
reader.ReadDictionaryAsGeneric<string, object>());
}
/// <summary>
/// Kernal start callback.
/// </summary>
/// <param name="interopProc">Interop processor.</param>
/// <param name="stream">Stream.</param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "PlatformJniTarget is passed further")]
internal static void OnStart(GlobalRef interopProc, IBinaryStream stream)
{
try
{
// 1. Read data and leave critical state ASAP.
BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream);
// ReSharper disable once PossibleInvalidOperationException
var name = reader.ReadString();
// 2. Set ID and name so that Start() method can use them later.
_startup.Name = name;
if (Nodes.ContainsKey(new NodeKey(name)))
throw new IgniteException("Ignite with the same name already started: " + name);
_startup.Ignite = new Ignite(_startup.Configuration, _startup.Name,
new PlatformJniTarget(interopProc, _startup.Marshaller), _startup.Marshaller,
_startup.LifecycleHandlers, _startup.Callbacks);
}
catch (Exception e)
{
// 5. Preserve exception to throw it later in the "Start" method and throw it further
// to abort startup in Java.
_startup.Error = e;
throw;
}
}
/// <summary>
/// Load assemblies.
/// </summary>
/// <param name="assemblies">Assemblies.</param>
private static void LoadAssemblies(IEnumerable<string> assemblies)
{
if (assemblies != null)
{
foreach (string s in assemblies)
{
// 1. Try loading as directory.
if (Directory.Exists(s))
{
string[] files = Directory.GetFiles(s, "*.dll");
#pragma warning disable 0168
foreach (string dllPath in files)
{
if (!SelfAssembly(dllPath))
{
try
{
Assembly.LoadFile(dllPath);
}
catch (BadImageFormatException)
{
// No-op.
}
}
}
#pragma warning restore 0168
continue;
}
// 2. Try loading using full-name.
try
{
Assembly assembly = Assembly.Load(s);
if (assembly != null)
continue;
}
catch (Exception e)
{
if (!(e is FileNotFoundException || e is FileLoadException))
throw new IgniteException("Failed to load assembly: " + s, e);
}
// 3. Try loading using file path.
try
{
Assembly assembly = Assembly.LoadFrom(s);
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (assembly != null)
continue;
}
catch (Exception e)
{
if (!(e is FileNotFoundException || e is FileLoadException))
throw new IgniteException("Failed to load assembly: " + s, e);
}
// 4. Not found, exception.
throw new IgniteException("Failed to load assembly: " + s);
}
}
}
/// <summary>
/// Whether assembly points to Ignite binary.
/// </summary>
/// <param name="assembly">Assembly to check..</param>
/// <returns><c>True</c> if this is one of GG assemblies.</returns>
private static bool SelfAssembly(string assembly)
{
return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string,
/// then default no-name Ignite will be returned. Note that caller of this method
/// should not assume that it will return the same instance every time.
/// <p />
/// Note that single process can run multiple Ignite instances and every Ignite instance (and its
/// node) can belong to a different grid. Ignite name defines what grid a particular Ignite
/// instance (and correspondingly its node) belongs to.
/// </summary>
/// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>,
/// then Ignite instance belonging to a default no-name Ignite will be returned.</param>
/// <returns>
/// An instance of named grid.
/// </returns>
/// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception>
public static IIgnite GetIgnite(string name)
{
var ignite = TryGetIgnite(name);
if (ignite == null)
throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name);
return ignite;
}
/// <summary>
/// Gets the default Ignite instance with null name, or an instance with any name when there is only one.
/// <para />
/// Note that caller of this method should not assume that it will return the same instance every time.
/// </summary>
/// <returns>Default Ignite instance.</returns>
/// <exception cref="IgniteException">When there is no matching Ignite instance.</exception>
public static IIgnite GetIgnite()
{
lock (SyncRoot)
{
if (Nodes.Count == 0)
{
throw new IgniteException("Failed to get default Ignite instance: " +
"there are no instances started.");
}
if (Nodes.Count == 1)
{
return Nodes.Single().Value;
}
Ignite result;
if (Nodes.TryGetValue(new NodeKey(null), out result))
{
return result;
}
throw new IgniteException(string.Format("Failed to get default Ignite instance: " +
"there are {0} instances started, and none of them has null name.", Nodes.Count));
}
}
/// <summary>
/// Gets all started Ignite instances.
/// </summary>
/// <returns>All Ignite instances.</returns>
public static ICollection<IIgnite> GetAll()
{
lock (SyncRoot)
{
return Nodes.Values.ToArray();
}
}
/// <summary>
/// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string,
/// then default no-name Ignite will be returned. Note that caller of this method
/// should not assume that it will return the same instance every time.
/// <p/>
/// Note that single process can run multiple Ignite instances and every Ignite instance (and its
/// node) can belong to a different grid. Ignite name defines what grid a particular Ignite
/// instance (and correspondingly its node) belongs to.
/// </summary>
/// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>,
/// then Ignite instance belonging to a default no-name Ignite will be returned.
/// </param>
/// <returns>An instance of named grid, or null.</returns>
public static IIgnite TryGetIgnite(string name)
{
lock (SyncRoot)
{
Ignite result;
return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result;
}
}
/// <summary>
/// Gets the default Ignite instance with null name, or an instance with any name when there is only one.
/// Returns null when there are no Ignite instances started, or when there are more than one,
/// and none of them has null name.
/// </summary>
/// <returns>An instance of default no-name grid, or null.</returns>
public static IIgnite TryGetIgnite()
{
lock (SyncRoot)
{
if (Nodes.Count == 1)
{
return Nodes.Single().Value;
}
return TryGetIgnite(null);
}
}
/// <summary>
/// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then
/// all jobs currently executing on local node will be interrupted. If
/// grid name is <c>null</c>, then default no-name Ignite will be stopped.
/// </summary>
/// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param>
/// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled
/// by calling <c>ComputeJob.cancel</c>method.</param>
/// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c>
/// othwerwise (the instance with given <c>name</c> was not found).</returns>
public static bool Stop(string name, bool cancel)
{
lock (SyncRoot)
{
NodeKey key = new NodeKey(name);
Ignite node;
if (!Nodes.TryGetValue(key, out node))
return false;
node.Stop(cancel);
Nodes.Remove(key);
GC.Collect();
return true;
}
}
/// <summary>
/// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then
/// all jobs currently executing on local node will be interrupted.
/// </summary>
/// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled
/// by calling <c>ComputeJob.Cancel()</c> method.</param>
public static void StopAll(bool cancel)
{
lock (SyncRoot)
{
while (Nodes.Count > 0)
{
var entry = Nodes.First();
entry.Value.Stop(cancel);
Nodes.Remove(entry.Key);
}
}
GC.Collect();
}
/// <summary>
/// Connects Ignite lightweight (thin) client to an Ignite node.
/// <para />
/// Thin client connects to an existing Ignite node with a socket and does not start JVM in process.
/// </summary>
/// <param name="clientConfiguration">The client configuration.</param>
/// <returns>Ignite instance.</returns>
public static IIgniteClient StartClient(IgniteClientConfiguration clientConfiguration)
{
IgniteArgumentCheck.NotNull(clientConfiguration, "clientConfiguration");
IgniteArgumentCheck.NotNull(clientConfiguration.Host, "clientConfiguration.Host");
return new IgniteClient(clientConfiguration);
}
/// <summary>
/// Handles the DomainUnload event of the CurrentDomain control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
// If we don't stop Ignite.NET on domain unload,
// we end up with broken instances in Java (invalid callbacks, etc).
// IIS, in particular, is known to unload and reload domains within the same process.
StopAll(true);
}
/// <summary>
/// Grid key. Workaround for non-null key requirement in Dictionary.
/// </summary>
private class NodeKey
{
/** */
private readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="NodeKey"/> class.
/// </summary>
/// <param name="name">The name.</param>
internal NodeKey(string name)
{
_name = name;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
var other = obj as NodeKey;
return other != null && Equals(_name, other._name);
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return _name == null ? 0 : _name.GetHashCode();
}
}
/// <summary>
/// Value object to pass data between .Net methods during startup bypassing Java.
/// </summary>
private class Startup
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="cbs"></param>
internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs)
{
Configuration = cfg;
Callbacks = cbs;
}
/// <summary>
/// Configuration.
/// </summary>
internal IgniteConfiguration Configuration { get; private set; }
/// <summary>
/// Gets unmanaged callbacks.
/// </summary>
internal UnmanagedCallbacks Callbacks { get; private set; }
/// <summary>
/// Lifecycle handlers.
/// </summary>
internal IList<LifecycleHandlerHolder> LifecycleHandlers { get; set; }
/// <summary>
/// Node name.
/// </summary>
internal string Name { get; set; }
/// <summary>
/// Marshaller.
/// </summary>
internal Marshaller Marshaller { get; set; }
/// <summary>
/// Start error.
/// </summary>
internal Exception Error { get; set; }
/// <summary>
/// Gets or sets the ignite.
/// </summary>
internal Ignite Ignite { get; set; }
}
/// <summary>
/// Internal handler for event notification.
/// </summary>
private class InternalLifecycleHandler : ILifecycleHandler
{
/** */
#pragma warning disable 649 // unused field
[InstanceResource] private readonly IIgnite _ignite;
/** <inheritdoc /> */
public void OnLifecycleEvent(LifecycleEventType evt)
{
if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null)
((Ignite) _ignite).BeforeNodeStop();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Assets.Scripts.Common;
using Assets.Sources.Graphics.Movie;
using Memoria;
using Memoria.Scripts;
using SimpleJSON;
using UnityEngine;
using Object = System.Object;
public class MBG : HonoBehavior
{
public static MBG Instance
{
get
{
if (MBG.instance == (UnityEngine.Object)null)
{
MBG.instance = UnityEngine.Object.Instantiate<GameObject>(AssetManager.Load<GameObject>("CommonAsset/MBGData/MBG", out _, false)).GetComponent<MBG>();
}
return MBG.instance;
}
}
public static Boolean IsNull
{
get
{
return MBG.instance == (UnityEngine.Object)null;
}
}
public static Boolean IsSkip
{
set
{
if (!MBG.IsNull)
{
MBG.instance.isSkip = value;
}
}
}
public override void HonoAwake()
{
base.HonoAwake();
this.MBGInitialized = 1;
this.mbgCamera = this.cameraObject.GetComponent<Camera>();
this.process = this.cameraObject.GetComponent<MovieMaterialProcessor>();
this.movieMaterial = MovieMaterial.New(this.process);
this.moviePlane.GetComponent<Renderer>().material = this.movieMaterial.Material;
this.moviePlane.transform.localScale = Vector3.Scale(new Vector3(32f, 1f, 22.4f), MovieMaterial.ScaleVector);
this.mbgCamera.depth = -4096f;
this.movieMaterial.FastForward = (MovieMaterial.FastForwardMode)((!FF9StateSystem.Settings.IsFastForward) ? MovieMaterial.FastForwardMode.Normal : MovieMaterial.FastForwardMode.HighSpeed);
this.shader = ShadersLoader.Find("PSX/FieldMapActorMBGMask");
this.SetFastForward(HonoBehaviorSystem.Instance.IsFastForwardModeActive());
this.isFastForwardOnBeforePlayingMBG = false;
this.played = false;
}
public override void HonoOnDestroy()
{
MBG.MarkCharacterDepth = false;
QualitySettings.vSyncCount = 0;
this.movieMaterial.Destroy();
base.HonoOnDestroy();
}
public void SetFinishCallback(Action callback)
{
this.movieMaterial.OnFinished = callback;
}
public void Seek(Int32 discNo, Int32 fmvNo)
{
this.played = false;
MBG.MarkCharacterDepth = false;
this.fadeDuration = 0f;
MBG_DEF mbg_DEF = MBG.MBGDiscTable[discNo][fmvNo];
this.MBGType = mbg_DEF.type;
MBG.MBGParms.pauseRequest = false;
MBG.MBGParms.firstCall = true;
MBG.MBGParms.soundCallCount = 0;
String name = MBG.MBGDiscTable[discNo][fmvNo].name;
String binaryName = name;
if (discNo == 4 && fmvNo == 3)
{
this.isFMV55D = true;
}
else
{
this.isFMV55D = false;
}
if (discNo == 4 && fmvNo == 9)
{
this.isMBG116 = true;
}
else
{
this.isMBG116 = false;
}
if (discNo == 3 && fmvNo == 13)
{
this.isFMV045 = true;
}
else
{
this.isFMV045 = false;
}
if (discNo == 4 && fmvNo == 0)
{
this.isFMV055A = true;
}
else
{
this.isFMV055A = false;
}
MBGDataReader mbgdataReader = MBGDataReader.Load(binaryName);
if (mbgdataReader != null)
{
this.audioDef = mbgdataReader.audioRefList;
}
this.LoadMaskData(name.ToUpper());
this.LoadMovie(name);
}
private void LoadMaskData(String fileName)
{
this.maskSheet.Clear();
this.maskData.Clear();
this.haveMask = false;
this.currentMaskID = -1;
this.loadedMask = 0;
this.maskCount = 0;
if (this.maskSheetData.ContainsKey(fileName))
{
this.haveMask = true;
this.maskName = fileName;
this.maskCount = this.maskSheetData[this.maskName];
for (Int32 i = 0; i < this.maskCount; i++)
{
String name = String.Concat(new Object[]
{
"EmbeddedAsset/Movie/Mask/",
this.maskName,
"/",
this.maskName,
"_",
i,
".txt"
});
String[] mbgInfo;
String textAsset = AssetManager.LoadString(name, out mbgInfo);
JSONNode jsonnode = JSONNode.Parse(textAsset);
JSONClass asObject = jsonnode["frames"].AsObject;
foreach (Object obj in asObject)
{
String key = ((KeyValuePair<String, JSONNode>)obj).Key;
Int32 key2 = Int32.Parse(key);
MaskFrame maskFrame = new MaskFrame();
JSONClass asObject2 = asObject[key].AsObject;
JSONClass asObject3 = asObject2["frame"].AsObject;
Vector4 frame = new Vector4((Single)asObject3["x"].AsInt, (Single)asObject3["y"].AsInt, (Single)asObject3["w"].AsInt, (Single)asObject3["h"].AsInt);
JSONClass asObject4 = asObject2["spriteSourceSize"].AsObject;
Vector4 sourceSize = new Vector4((Single)asObject4["x"].AsInt, (Single)asObject4["y"].AsInt, (Single)asObject4["w"].AsInt, (Single)asObject4["h"].AsInt);
maskFrame.frame = frame;
maskFrame.sourceSize = sourceSize;
maskFrame.sheetID = i;
this.maskData.Add(key2, maskFrame);
}
}
if (this.maskCount > 0)
{
this.UpdateMarkSheet();
}
}
}
public void LoadMovie(String fileName)
{
this.MBGInitialized = (SByte)(this.MBGInitialized + 1);
this.movieMaterial.Load(fileName);
SoundLib.UnloadMovieResources();
SoundLib.LoadMovieResources("MovieAudio/", new String[]
{
fileName
});
}
public void SetFieldMap(FieldMap fieldMap)
{
this.mbgCamera.depth = -4096f;
this.currentFieldMap = fieldMap;
MBG.MBGParms.oldBGCamNdx = this.currentFieldMap.GetCurrentCameraIndex();
Camera mainCamera = fieldMap.GetMainCamera();
this.SetMovieCamera(mainCamera);
}
public void Play()
{
this.tempTargetFrameRate = Application.targetFrameRate;
this.tempVirtualAnalogStatus = VirtualAnalog.IsEnable;
PersistenSingleton<HonoInputManager>.Instance.SetVirtualAnalogEnable(false);
this.isSkip = false;
this.MBGInitialized = (SByte)(this.MBGInitialized + 1);
if (PersistenSingleton<FF9StateSystem>.Instance.mode == 1 || PersistenSingleton<FF9StateSystem>.Instance.mode == 5)
{
MBG.MBGParms.oldCharOTOffset = FF9StateSystem.Field.FF9Field.loc.map.charOTOffset;
FF9StateSystem.Field.FF9Field.loc.map.charOTOffset = 0;
Shader.SetGlobalFloat("_DepthOffset", (Single)FF9StateSystem.Field.FF9Field.loc.map.charOTOffset);
this.background = GameObject.Find("Background");
this.enableBackground = false;
}
PersistenSingleton<UIManager>.Instance.Booster.CloseBoosterPanel();
if (this.MBGType != 1 && !this.isEnding && !this.isTitle && !this.isMovieGallery)
{
UIManager.Field.MovieHitArea.SetActive(true);
}
if (this.MBGType == 1 && FF9StateSystem.Settings.IsFastForward)
{
this.isFastForwardOnBeforePlayingMBG = true;
FF9StateSystem.Settings.CallBoosterButtonFuntion(BoosterType.HighSpeedMode, false);
PersistenSingleton<UIManager>.Instance.Booster.SetBoosterHudIcon(BoosterType.HighSpeedMode, false);
}
this.isWaitForPause = false;
this.played = true;
Application.targetFrameRate = Mathf.RoundToInt((Single) this.movieMaterial.FPS);
PlayerWindow.Instance.SetTitle($"FPS: {Application.targetFrameRate}");
this.movieMaterial.Play();
}
public void Pause(Boolean doPause)
{
if (this.movieMaterial.PlayPosition < this.movieMaterial.Duration && this.played)
{
if (doPause)
{
vib.VIB_actuatorReset(0);
this.movieMaterial.Pause();
}
else
{
this.isWaitForPause = false;
this.movieMaterial.Resume();
}
}
else if (this.played)
{
if (doPause)
{
if (!this.isWaitForPause)
{
this.isWaitForPause = true;
base.StartCoroutine(this.WaitForPause());
}
}
else
{
this.isWaitForPause = false;
}
}
}
private IEnumerator WaitForPause()
{
while ((MBG.Instance.IsPlaying() & 2UL) == 0UL)
{
yield return null;
}
if (this.isWaitForPause)
{
vib.VIB_actuatorReset(0);
this.movieMaterial.Pause();
}
yield break;
}
public void Stop()
{
if (PersistenSingleton<FF9StateSystem>.Instance.mode == 1 || PersistenSingleton<FF9StateSystem>.Instance.mode == 5)
{
FF9StateSystem.Field.FF9Field.loc.map.charOTOffset = MBG.MBGParms.oldCharOTOffset;
Shader.SetGlobalFloat("_DepthOffset", (Single)FF9StateSystem.Field.FF9Field.loc.map.charOTOffset);
if (this.currentFieldMap != (UnityEngine.Object)null)
{
this.currentFieldMap.camIdx = -1;
this.currentFieldMap.SetCurrentCameraIndex(MBG.MBGParms.oldBGCamNdx);
}
this.enableBackground = true;
if (this.background != (UnityEngine.Object)null)
{
this.background.SetActive(this.enableBackground);
}
}
ObjList activeObjList = PersistenSingleton<EventEngine>.Instance.GetActiveObjList();
for (ObjList objList = activeObjList; objList != null; objList = objList.next)
{
if (objList.obj.cid == 4 && !(objList.obj.go == (UnityEngine.Object)null))
{
SkinnedMeshRenderer[] componentsInChildren = objList.obj.go.GetComponentsInChildren<SkinnedMeshRenderer>();
SkinnedMeshRenderer[] array = componentsInChildren;
for (Int32 i = 0; i < (Int32)array.Length; i++)
{
SkinnedMeshRenderer skinnedMeshRenderer = array[i];
Material[] materials = skinnedMeshRenderer.materials;
for (Int32 j = 0; j < (Int32)materials.Length; j++)
{
Material material = materials[j];
material.renderQueue = 2000;
}
}
}
}
PersistenSingleton<HonoInputManager>.Instance.SetVirtualAnalogEnable(this.tempVirtualAnalogStatus);
SceneDirector.ToggleFadeAll(true);
Application.targetFrameRate = this.tempTargetFrameRate;
PlayerWindow.Instance.SetTitle(String.Empty);
vib.VIB_actuatorReset(0);
this.movieMaterial.Transparency = 0f;
this.movieMaterial.Stop();
this.mbgCamera.depth = -4096f;
this.MBGInitialized = (SByte)(this.MBGInitialized - 1);
MBG.MarkCharacterDepth = false;
this.played = false;
PersistenSingleton<UIManager>.Instance.SetUIPauseEnable(true);
}
public void Purge()
{
this.Stop();
this.MBGInitialized = 0;
}
public void UpdateCamera()
{
Int32 num = this.GetFrame;
if (this.audioDef != null && num < this.audioDef.Count)
{
MBG.MarkCharacterDepth = true;
AUDIO_HDR_DEF audio_HDR_DEF = this.audioDef[num];
if (this.isMBG116 && num >= 1152 && num <= 1155)
{
audio_HDR_DEF = this.audioDef[1151];
}
MBG_CAM_DEF mbgCameraA = audio_HDR_DEF.mbgCameraA;
Vector2 centerOffset = mbgCameraA.GetCenterOffset();
if (this.currentFieldMap != (UnityEngine.Object)null && FF9StateSystem.Common.FF9.fldMapNo != 2752)
{
Vector2 offset = this.currentFieldMap.offset;
Vector2 zero = Vector2.zero;
zero.x = (Single)((Int16)(this.currentFieldMap.offset.x - (Single)mbgCameraA.centerOffset[0]));
zero.y = (Single)((Int16)(this.currentFieldMap.offset.y + (Single)mbgCameraA.centerOffset[1]));
this.currentFieldMap.mainCamera.transform.localPosition = zero;
Shader.SetGlobalMatrix("_MatrixRT", mbgCameraA.GetMatrixRT());
Shader.SetGlobalFloat("_ViewDistance", mbgCameraA.GetViewDistance());
FF9StateSystem.Common.FF9.cam = mbgCameraA.GetMatrixRT();
FF9StateSystem.Common.FF9.proj = mbgCameraA.proj;
}
if ((FF9StateSystem.Settings.cfg.vibe == (UInt64)FF9CFG.FF9CFG_VIBE_ON || PersistenSingleton<FF9StateSystem>.Instance.mode == 5) && !PersistenSingleton<UIManager>.Instance.IsPause && UIManager.Field != (UnityEngine.Object)null && !UIManager.Field.isShowSkipMovieDialog)
{
vib.VIB_actuatorSet(0, audio_HDR_DEF.vibrate[0] / 255f, audio_HDR_DEF.vibrate[1] / 255f);
}
}
if (FF9StateSystem.Common.FF9.fldMapNo != 2933)
{
num++;
}
if (this.haveMask && this.maskData.ContainsKey(num))
{
ObjList activeObjList = PersistenSingleton<EventEngine>.Instance.GetActiveObjList();
for (ObjList objList = activeObjList; objList != null; objList = objList.next)
{
if (objList.obj.cid == 4)
{
SkinnedMeshRenderer[] componentsInChildren = objList.obj.go.GetComponentsInChildren<SkinnedMeshRenderer>();
SkinnedMeshRenderer[] array = componentsInChildren;
for (Int32 i = 0; i < (Int32)array.Length; i++)
{
SkinnedMeshRenderer skinnedMeshRenderer = array[i];
Material[] materials = skinnedMeshRenderer.materials;
for (Int32 j = 0; j < (Int32)materials.Length; j++)
{
Material material = materials[j];
if (skinnedMeshRenderer.material.shader != this.shader)
{
skinnedMeshRenderer.material.shader = this.shader;
skinnedMeshRenderer.material.renderQueue = this.renderQueue;
}
}
}
}
}
MaskFrame maskFrame = this.maskData[num];
if (this.isMBG116 && num >= 1150 && num <= 1154)
{
maskFrame = this.maskData[1149];
}
Shader.SetGlobalVector("_Frame", maskFrame.frame);
Shader.SetGlobalVector("_SpriteSourceSize", maskFrame.sourceSize);
Int32 sheetID = maskFrame.sheetID;
Vector2 zero2 = Vector2.zero;
zero2.x = maskFrame.frame.z;
zero2.y = maskFrame.frame.w;
if (this.maskSheet.ContainsKey(sheetID) && sheetID != this.currentMaskID && zero2 != Vector2.one)
{
Texture2D tex = this.maskSheet[sheetID];
Shader.SetGlobalTexture("_MBGMask", tex);
if (this.maskSheet.ContainsKey(this.currentMaskID))
{
Resources.UnloadAsset(this.maskSheet[this.currentMaskID]);
this.maskSheet.Remove(this.currentMaskID);
this.UpdateMarkSheet();
}
this.currentMaskID = sheetID;
}
}
if (this.currentFieldMap != (UnityEngine.Object)null && FF9StateSystem.Common.FF9.fldMapNo == 2933)
{
ObjList activeObjList2 = PersistenSingleton<EventEngine>.Instance.GetActiveObjList();
for (ObjList objList2 = activeObjList2; objList2 != null; objList2 = objList2.next)
{
if (objList2.obj.uid == 4 && num == 1154)
{
Actor actor = (Actor)objList2.obj;
actor.flags = 0;
}
if (objList2.obj.uid == 4)
{
Actor actor2 = (Actor)objList2.obj;
if (num > 1045)
{
Vector3 curPos = actor2.fieldMapActorController.curPos;
curPos.y = -30f;
actor2.fieldMapActorController.curPos = curPos;
actor2.fieldMapActorController.SyncPosToTransform();
}
}
if (objList2.obj.uid == 1)
{
Actor actor3 = (Actor)objList2.obj;
if (num == 366 || num == 392)
{
actor3.flags = 0;
}
else if (num == 393)
{
actor3.flags = 1;
}
else if ((num > 628 && num < 636) || num == 392 || num == 1156 || num == 89)
{
SkinnedMeshRenderer[] componentsInChildren2 = objList2.obj.go.GetComponentsInChildren<SkinnedMeshRenderer>();
SkinnedMeshRenderer[] array2 = componentsInChildren2;
for (Int32 k = 0; k < (Int32)array2.Length; k++)
{
SkinnedMeshRenderer skinnedMeshRenderer2 = array2[k];
skinnedMeshRenderer2.enabled = true;
}
Transform transform = objList2.obj.go.transform.FindChild("battle_model");
if (transform == (UnityEngine.Object)null)
{
return;
}
Renderer[] componentsInChildren3 = transform.GetComponentsInChildren<Renderer>();
Renderer[] array3 = componentsInChildren3;
for (Int32 l = 0; l < (Int32)array3.Length; l++)
{
Renderer renderer = array3[l];
renderer.enabled = false;
}
}
else if (num == 88 || num == 391 || num == 1154 || num == 1155)
{
SkinnedMeshRenderer[] componentsInChildren4 = objList2.obj.go.GetComponentsInChildren<SkinnedMeshRenderer>();
SkinnedMeshRenderer[] array4 = componentsInChildren4;
for (Int32 m = 0; m < (Int32)array4.Length; m++)
{
SkinnedMeshRenderer skinnedMeshRenderer3 = array4[m];
skinnedMeshRenderer3.enabled = false;
}
Transform transform2 = objList2.obj.go.transform.FindChild("battle_model");
if (transform2 == (UnityEngine.Object)null)
{
return;
}
Renderer[] componentsInChildren5 = transform2.GetComponentsInChildren<Renderer>();
Renderer[] array5 = componentsInChildren5;
for (Int32 n = 0; n < (Int32)array5.Length; n++)
{
Renderer renderer2 = array5[n];
renderer2.enabled = false;
}
}
else if (num == 980)
{
actor3.flags = 0;
}
}
else if (objList2.obj.uid == 5)
{
Actor actor4 = (Actor)objList2.obj;
if (num == 42)
{
actor4.flags = 0;
}
}
}
}
}
private void UpdateMarkSheet()
{
while (this.loadedMask < this.maskCount && this.maskSheet.Count < 3)
{
this.corutineLoadMask.Add(this.loadedMask, base.StartCoroutine(this.LoadMaskSheet(this.loadedMask)));
this.loadedMask++;
}
}
private IEnumerator LoadMaskSheet(Int32 maskID)
{
String filePath = String.Concat(new Object[]
{
"EmbeddedAsset/Movie/Mask/",
this.maskName,
"/",
this.maskName,
"_",
this.loadedMask
});
AssetManagerRequest resourceRequest = AssetManager.LoadAsync<Texture2D>(filePath);
while (!resourceRequest.isDone)
{
yield return 0;
}
Texture2D maskResource = resourceRequest.asset as Texture2D;
this.maskSheet.Add(maskID, maskResource);
base.StopCoroutine(this.corutineLoadMask[maskID]);
this.corutineLoadMask.Remove(maskID);
yield break;
}
private void Update()
{
Boolean flag = PersistenSingleton<UIManager>.Instance.IsPause || (UIManager.Field != (UnityEngine.Object)null && UIManager.Field.isShowSkipMovieDialog) || this.isSkip;
if (this.isPause != flag)
{
this.isPause = flag;
this.Pause(this.isPause);
}
}
public override void HonoUpdate()
{
base.HonoUpdate();
if (FF9StateSystem.Common.FF9.fldMapNo != 2933)
{
this.MBGUpdate();
}
}
private void LateUpdate()
{
if (FF9StateSystem.Common.FF9.fldMapNo == 2933)
{
this.MBGUpdate();
}
}
public void MBGUpdate()
{
this.cumulativeTime = 0f;
if ((Int32)this.MBGInitialized <= 1)
{
return;
}
if (this.currentFadeDuration < this.fadeDuration)
{
this.currentFadeDuration += Time.deltaTime;
if (this.currentFadeDuration >= this.fadeDuration)
{
this.currentFadeDuration = this.fadeDuration;
}
Single num = this.currentFadeDuration / this.fadeDuration;
this.movieMaterial.Transparency = this.alphaFrom + (this.alphaTo - this.alphaFrom) * num;
if (this.currentFadeDuration >= this.fadeDuration && this.fadeCallback != null)
{
this.fadeCallback();
}
}
if (this.movieMaterial.GetFirstFrame)
{
if (this.updateSwitchCamera)
{
this.updateSwitchCamera = false;
this.Set24BitMode((Int32)this.MBGIsRGB24);
}
if (this.background != (UnityEngine.Object)null && this.background.activeSelf != this.enableBackground)
{
this.background.SetActive(this.enableBackground);
}
if (this.movieMaterial.PlayPosition < this.movieMaterial.Duration)
{
this.UpdateCamera();
if (!this.isEnding)
{
SceneDirector.ToggleFadeAll(false);
}
}
}
}
public void Fade(Single alphaFrom, Single alphaTo, Single duration, Action callback = null)
{
this.alphaFrom = alphaFrom;
this.alphaTo = alphaTo;
this.currentFadeDuration = 0f;
this.fadeDuration = duration;
this.fadeCallback = callback;
}
public Boolean IsFinished()
{
return this.movieMaterial == null || !this.movieMaterial.GetFirstFrame || (this.movieMaterial.GetFirstFrame && this.movieMaterial.Frame >= this.movieMaterial.TotalFrame) || this.isSkip;
}
public bool IsFinishedForDisableBooster()
{
return !this.played || this.isSkip;
}
public Int32 GetFrame
{
get
{
return this.movieMaterial.Frame;
}
}
public void SetFadeInParameters(Int32 threshold, Int32 tickCount, Int32 targetVolume)
{
if (threshold < 0)
{
MBG.MBGParms.threshold = 3UL;
}
else
{
MBG.MBGParms.threshold = (UInt64)((Int64)threshold);
}
if (tickCount < 0)
{
MBG.MBGParms.tickCount = 4UL;
}
else
{
MBG.MBGParms.tickCount = (UInt64)((Int64)tickCount);
}
if (targetVolume < 0)
{
MBG.MBGParms.targetVolume = 127UL;
}
else
{
MBG.MBGParms.targetVolume = (UInt64)((Int64)targetVolume);
}
}
public unsafe Int32 Set24BitMode(Int32 isOn)
{
UInt64 num = this.IsPlaying();
if (isOn == 1)
{
this.MBGIsRGB24 = 1;
if (this.movieMaterial.GetFirstFrame)
{
this.mbgCamera.depth = 1f;
this.SetMovieCamera(this.mbgCamera);
SceneDirector.ToggleFadeAll(true);
}
else
{
this.updateSwitchCamera = true;
}
FF9StateSystem.Common.FF9.attr |= 20u;
if (PersistenSingleton<FF9StateSystem>.Instance.mode == 1 || PersistenSingleton<FF9StateSystem>.Instance.mode == 5)
{
FF9StateSystem.Field.FF9Field.attr |= 9u;
}
this.renderQueue = 2000;
}
else
{
this.updateSwitchCamera = false;
this.MBGIsRGB24 = 0;
FieldMap component = GameObject.Find("FieldMap").GetComponent<FieldMap>();
if (component != (UnityEngine.Object)null)
{
this.SetFieldMap(component);
}
if (PersistenSingleton<FF9StateSystem>.Instance.mode == 1 || PersistenSingleton<FF9StateSystem>.Instance.mode == 5)
{
FieldMap.FF9FieldAttr.ff9[1, 0] |= (UInt16)20;
FieldMap.FF9FieldAttr.field[1, 0] = (UInt16)9;
}
this.renderQueue = 3001;
}
ObjList activeObjList = PersistenSingleton<EventEngine>.Instance.GetActiveObjList();
for (ObjList objList = activeObjList; objList != null; objList = objList.next)
{
if (objList.obj.cid == 4)
{
if (objList.obj.go != (UnityEngine.Object)null)
{
SkinnedMeshRenderer[] componentsInChildren = objList.obj.go.GetComponentsInChildren<SkinnedMeshRenderer>();
SkinnedMeshRenderer[] array = componentsInChildren;
for (Int32 i = 0; i < (Int32)array.Length; i++)
{
SkinnedMeshRenderer skinnedMeshRenderer = array[i];
Material[] materials = skinnedMeshRenderer.materials;
for (Int32 j = 0; j < (Int32)materials.Length; j++)
{
Material material = materials[j];
material.renderQueue = this.renderQueue;
}
}
}
}
}
return 1;
}
public void SetModeEnding()
{
this.isEnding = true;
this.Set24BitMode(1);
}
public void SetFastForward(Boolean IsFastFprward)
{
if (this.movieMaterial != null)
{
this.movieMaterial.FastForward = (MovieMaterial.FastForwardMode)((!IsFastFprward) ? MovieMaterial.FastForwardMode.Normal : MovieMaterial.FastForwardMode.HighSpeed);
}
}
public void ResetFlags()
{
this.isEnding = false;
this.isTitle = false;
this.isMovieGallery = false;
this.isSkip = false;
}
public Int32 GetFrameCount
{
get
{
return this.movieMaterial.TotalFrame;
}
}
public Boolean is24BitMode
{
get
{
return this.MBGIsRGB24 == 1;
}
}
public UInt64 IsPlaying()
{
UInt64 num = 0UL;
if ((Int32)this.MBGInitialized >= 1)
{
num |= 1UL;
if (this.GetFrame > 0)
{
num |= 2UL;
}
if (this.MBGIsRGB24 != 0)
{
num |= 4UL;
}
if (this.MBGType == 1)
{
num |= 8UL;
}
}
return num;
}
private Int32 MBG_isInitialized()
{
return (Int32)this.MBGInitialized;
}
private void SetMovieCamera(Camera movieCamera)
{
this.moviePlane.transform.SetParent(movieCamera.transform);
this.moviePlane.transform.localPosition = Vector3.forward * 2f;
this.moviePlane.transform.localScale = Vector3.Scale(new Vector3(32f, 1f, 22.4f), MovieMaterial.ScaleVector);
this.moviePlane.transform.localRotation = Quaternion.Euler(90f, 180f, 0f);
}
public void SetDepthForTitle()
{
this.isTitle = true;
this.mbgCamera.depth = 0f;
}
public void SetDepthForMovieGallery()
{
this.isMovieGallery = true;
this.mbgCamera.depth = 2f;
}
public const Byte MBG_DEFAULT_THRESHOLD = 3;
public const Byte MBG_DEFAULT_TICKS = 4;
public const Byte MBG_DEFAULT_TARGET = 127;
public const Byte MBG_INITIALIZED = 1;
public const Byte MBG_PLAYING = 2;
public const Byte MBG_24BIT = 4;
public const Byte MBG_DATA_INTERLEAVE = 8;
public const Byte MBG_PAUSED = 16;
private const Int32 maxStoreSheet = 3;
private const Int32 geometryQueue = 2000;
private const Int32 transparentQueue = 3001;
public static readonly MBG_DEF[][] MBGDiscTable = new MBG_DEF[][]
{
new MBG_DEF[]
{
new MBG_DEF("\\SPARE\\FMV090.STR;1", 1, 0),
new MBG_DEF("\\SPARE\\FMV091.STR;1", 1, 0),
new MBG_DEF("\\SPARE\\FMV092.STR;1", 1, 0),
new MBG_DEF("\\SPARE\\FMV093.STR;1", 1, 0),
new MBG_DEF("\\SPARE\\FMV094.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV910.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV920.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV930.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV940.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV950.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV960.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV970.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV980.STR;1", 1, 0),
new MBG_DEF("\\TEST\\FMV990.STR;1", 1, 0)
},
new MBG_DEF[]
{
new MBG_DEF("\\OPENING\\FMVD001.STR;1", 1, 0),
new MBG_DEF("\\OPENING\\FMVD002.STR;1", 1, 0),
new MBG_DEF("\\OPENING\\FMVD003.STR;1", 1, 0),
new MBG_DEF("FMV001", 1, 0),
new MBG_DEF("FMV002", 1, 0),
new MBG_DEF("mbg101", 0, 1),
new MBG_DEF("\\SEQ01\\FMV002X.STR;1", 1, 0),
new MBG_DEF("\\SEQ01\\FMV002Y.STR;1", 1, 0),
new MBG_DEF("FMV003", 1, 0),
new MBG_DEF("FMV004", 1, 0),
new MBG_DEF("FMV005", 1, 0),
new MBG_DEF("FMV006A", 1, 0),
new MBG_DEF("FMV006B", 1, 0),
new MBG_DEF("mbg102", 0, 1),
new MBG_DEF("\\SEQ02\\FMV007X.STR;1", 1, 0),
new MBG_DEF("\\SEQ02\\FMV007Y.STR;1", 1, 0),
new MBG_DEF("FMV008", 1, 0),
new MBG_DEF("mbg105", 0, 1),
new MBG_DEF("\\SEQ02\\FMV010X.STR;1", 1, 0),
new MBG_DEF("\\SEQ02\\FMV010Y.STR;1", 1, 0),
new MBG_DEF("FMV011", 1, 0),
new MBG_DEF("FMV012", 1, 0),
new MBG_DEF("FMV013", 1, 0),
new MBG_DEF("mbg103", 0, 1),
new MBG_DEF("\\SEQ02\\FMV014X.STR;1", 1, 0),
new MBG_DEF("\\SEQ02\\FMV014Y.STR;1", 1, 0),
new MBG_DEF("FMV015", 1, 0),
new MBG_DEF("FMV016", 1, 0),
new MBG_DEF("FMV017", 1, 0)
},
new MBG_DEF[]
{
new MBG_DEF("mbg106", 0, 1),
new MBG_DEF("\\SEQ04\\FMV018X.STR;1", 1, 0),
new MBG_DEF("\\SEQ04\\FMV018Y.STR;1", 1, 0),
new MBG_DEF("FMV019", 1, 0),
new MBG_DEF("FMV021", 1, 0),
new MBG_DEF("mbg107", 0, 1),
new MBG_DEF("\\SEQ05\\FMV022X.STR;1", 1, 0),
new MBG_DEF("\\SEQ05\\FMV022Y.STR;1", 1, 0),
new MBG_DEF("FMV023", 1, 0),
new MBG_DEF("FMV024", 1, 0),
new MBG_DEF("mbg108", 0, 1),
new MBG_DEF("\\SEQ06\\FMV025X.STR;1", 1, 0),
new MBG_DEF("\\SEQ06\\FMV025Y.STR;1", 1, 0),
new MBG_DEF("mbg109", 0, 1),
new MBG_DEF("\\SEQ06\\FMV026X.STR;1", 1, 0),
new MBG_DEF("\\SEQ06\\FMV026Y.STR;1", 1, 0),
new MBG_DEF("FMV027", 1, 0),
new MBG_DEF("FMV029", 1, 0),
new MBG_DEF("mbg110", 0, 1),
new MBG_DEF("\\SEQ06\\FMV030X.STR;1", 1, 0),
new MBG_DEF("\\SEQ06\\FMV030Y.STR;1", 1, 0),
new MBG_DEF("FMV031", 1, 0),
new MBG_DEF("FMV032", 1, 0),
new MBG_DEF("FMV033", 1, 0)
},
new MBG_DEF[]
{
new MBG_DEF("FMV034", 1, 0),
new MBG_DEF("FMV035", 1, 0),
new MBG_DEF("FMV036", 1, 0),
new MBG_DEF("mbg111", 0, 1),
new MBG_DEF("\\SEQ08\\FMV037X.STR;1", 1, 0),
new MBG_DEF("\\SEQ08\\FMV037Y.STR;1", 1, 0),
new MBG_DEF("FMV038", 1, 0),
new MBG_DEF("FMV039", 1, 0),
new MBG_DEF("FMV040", 1, 0),
new MBG_DEF("mbg112", 0, 1),
new MBG_DEF("\\SEQ09\\FMV041X.STR;1", 1, 0),
new MBG_DEF("\\SEQ09\\FMV041Y.STR;1", 1, 0),
new MBG_DEF("FMV042", 1, 0),
new MBG_DEF("FMV045", 1, 0),
new MBG_DEF("FMV046", 1, 0),
new MBG_DEF("mbg113", 0, 1),
new MBG_DEF("\\SEQ10\\FMV048X.STR;1", 1, 0),
new MBG_DEF("\\SEQ10\\FMV048Y.STR;1", 1, 0),
new MBG_DEF("FMV052", 1, 0),
new MBG_DEF("FMV053", 1, 0)
},
new MBG_DEF[]
{
new MBG_DEF("FMV055A", 1, 0),
new MBG_DEF("FMV055B", 1, 0),
new MBG_DEF("FMV055C", 1, 0),
new MBG_DEF("FMV055D", 1, 0),
new MBG_DEF("mbg114", 0, 1),
new MBG_DEF("\\SEQ11\\FMV055X.STR;1", 1, 0),
new MBG_DEF("\\SEQ11\\FMV055Y.STR;1", 1, 0),
new MBG_DEF("FMV056", 1, 0),
new MBG_DEF("mbg115", 0, 1),
new MBG_DEF("mbg116", 0, 1),
new MBG_DEF("mbg117", 0, 1),
new MBG_DEF("mbg118", 0, 1),
new MBG_DEF("mbg119", 0, 1),
new MBG_DEF("\\SEQ11\\FMV057Q.STR;1", 1, 0),
new MBG_DEF("\\SEQ11\\FMV057R.STR;1", 1, 0),
new MBG_DEF("\\SEQ11\\FMV057S.STR;1", 1, 0),
new MBG_DEF("\\SEQ11\\FMV057T.STR;1", 1, 0),
new MBG_DEF("\\SEQ11\\FMV057U.STR;1", 1, 0),
new MBG_DEF("FMV059", 1, 0),
new MBG_DEF("FMV060", 1, 0)
}
};
private readonly Dictionary<String, Int32> maskSheetData = new Dictionary<String, Int32>
{
{
"MBG105",
2
},
{
"MBG108",
1
},
{
"MBG116",
13
},
{
"MBG117",
5
}
};
public static MBG_PARMS_DEF MBGParms;
public MovieMaterial movieMaterial;
private List<AUDIO_HDR_DEF> audioDef;
private Byte MBGIsRGB24;
private SByte MBGInitialized;
public Byte MBGType;
public Boolean isFastForwardOnBeforePlayingMBG;
private Int32 sortingOrder;
private MovieMaterialProcessor process;
public GameObject moviePlane;
public GameObject cameraObject;
private Camera mbgCamera;
private FieldMap currentFieldMap;
private Vector2 startCamOffset = Vector2.zero;
private Single alphaFrom;
private Single alphaTo;
private Single fadeDuration;
private Single currentFadeDuration;
private Action fadeCallback;
private Int32 defaultMBGDepth = -8;
private static MBG instance = (MBG)null;
private Shader shader;
private Dictionary<Int32, Texture2D> maskSheet = new Dictionary<Int32, Texture2D>();
private Dictionary<Int32, Coroutine> corutineLoadMask = new Dictionary<Int32, Coroutine>();
private Dictionary<Int32, MaskFrame> maskData = new Dictionary<Int32, MaskFrame>();
private Boolean haveMask;
private String maskName = String.Empty;
private Int32 loadedMask;
private Int32 maskCount;
private Int32 currentMaskID;
private Int32 renderQueue = 2000;
private Int32 tempTargetFrameRate;
private Boolean updateSwitchCamera;
private GameObject background;
private Boolean enableBackground = true;
private Boolean isSkip;
private Boolean isEnding;
private Boolean isTitle;
private Boolean isMovieGallery;
public Boolean isFMV55D;
public Boolean isFMV045;
public Boolean isMBG116;
public Boolean isFMV055A;
private Boolean played;
private Boolean isWaitForPause;
public static Boolean MarkCharacterDepth = false;
private Boolean tempVirtualAnalogStatus;
private Single cumulativeTime;
private Boolean isPause;
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Tests;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Collections.Tests
{
public class SortedListTests
{
[Fact]
public void Ctor_Empty()
{
var sortList = new SortedList();
Assert.Equal(0, sortList.Count);
Assert.Equal(0, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void Ctor_Int(int initialCapacity)
{
var sortList = new SortedList(initialCapacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(initialCapacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new SortedList(-1)); // InitialCapacity < 0
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void Ctor_IComparer_Int(int initialCapacity)
{
var sortList = new SortedList(new CustomComparer(), initialCapacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(initialCapacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public void Ctor_IComparer_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new SortedList(new CustomComparer(), -1)); // InitialCapacity < 0
}
[Fact]
public void Ctor_IComparer()
{
var sortList = new SortedList(new CustomComparer());
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public void Ctor_IComparer_Null()
{
var sortList = new SortedList((IComparer)null);
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(100, false)]
public void Ctor_IDictionary(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable);
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
Assert.Equal(sortList.GetByIndex(i), value);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList((IDictionary)null)); // Dictionary is null
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(100, false)]
public void Ctor_IDictionary_IComparer(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable, new CustomComparer());
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
string expectedValue = "Value_" + (count - i - 1).ToString("D2");
Assert.Equal(sortList.GetByIndex(i), expectedValue);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public void Ctor_IDictionary_IComparer_Null()
{
var sortList = new SortedList(new Hashtable(), null);
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public void Ctor_IDictionary_IComparer_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList(null, new CustomComparer())); // Dictionary is null
}
[Fact]
public void DebuggerAttribute_Empty()
{
Assert.Equal("Count = 0", DebuggerAttributes.ValidateDebuggerDisplayReferences(new SortedList()));
}
[Fact]
public void DebuggerAttribute_NormalList()
{
var list = new SortedList() { { "a", 1 }, { "b", 2 } };
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(list.Count, items.Length);
}
[Fact]
public void DebuggerAttribute_SynchronizedList()
{
var list = SortedList.Synchronized(new SortedList() { { "a", 1 }, { "b", 2 } });
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), list);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(list.Count, items.Length);
}
[Fact]
public void DebuggerAttribute_NullSortedList_ThrowsArgumentNullException()
{
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Fact]
public void EnsureCapacity_NewCapacityLessThanMin_CapsToMaxArrayLength()
{
// A situation like this occurs for very large lengths of SortedList.
// To avoid allocating several GBs of memory and making this test run for a very
// long time, we can use reflection to invoke SortedList's growth method manually.
// This is relatively brittle, as it relies on accessing a private method via reflection
// that isn't guaranteed to be stable.
const int InitialCapacity = 10;
const int MinCapacity = InitialCapacity * 2 + 1;
var sortedList = new SortedList(InitialCapacity);
MethodInfo ensureCapacity = sortedList.GetType().GetMethod("EnsureCapacity", BindingFlags.NonPublic | BindingFlags.Instance);
ensureCapacity.Invoke(sortedList, new object[] { MinCapacity });
Assert.Equal(MinCapacity, sortedList.Capacity);
}
[Fact]
public void Add()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
sortList2.Add(key, value);
Assert.True(sortList2.ContainsKey(key));
Assert.True(sortList2.ContainsValue(value));
Assert.Equal(i, sortList2.IndexOfKey(key));
Assert.Equal(i, sortList2.IndexOfValue(value));
Assert.Equal(i + 1, sortList2.Count);
}
});
}
[Fact]
public void Add_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Add(null, 101)); // Key is null
AssertExtensions.Throws<ArgumentException>(null, () => sortList2.Add(1, 101)); // Key already exists
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void Clear(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
sortList2.Clear();
Assert.Equal(0, sortList2.Count);
sortList2.Clear();
Assert.Equal(0, sortList2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void Clone(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
SortedList sortListClone = (SortedList)sortList2.Clone();
Assert.Equal(sortList2.Count, sortListClone.Count);
Assert.False(sortListClone.IsSynchronized); // IsSynchronized is not copied
Assert.Equal(sortList2.IsFixedSize, sortListClone.IsFixedSize);
Assert.Equal(sortList2.IsReadOnly, sortListClone.IsReadOnly);
for (int i = 0; i < sortListClone.Count; i++)
{
Assert.Equal(sortList2[i], sortListClone[i]);
}
});
}
[Fact]
public void Clone_IsShallowCopy()
{
var sortList = new SortedList();
for (int i = 0; i < 10; i++)
{
sortList.Add(i, new Foo());
}
SortedList sortListClone = (SortedList)sortList.Clone();
string stringValue = "Hello World";
for (int i = 0; i < 10; i++)
{
Assert.Equal(stringValue, ((Foo)sortListClone[i]).StringValue);
}
// Now we remove an object from the original list, but this should still be present in the clone
sortList.RemoveAt(9);
Assert.Equal(stringValue, ((Foo)sortListClone[9]).StringValue);
stringValue = "Good Bye";
((Foo)sortList[0]).StringValue = stringValue;
Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue);
Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue);
// If we change the object, of course, the previous should not happen
sortListClone[0] = new Foo();
Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue);
stringValue = "Hello World";
Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue);
}
[Fact]
public void ContainsKey()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i;
sortList2.Add(key, i);
Assert.True(sortList2.Contains(key));
Assert.True(sortList2.ContainsKey(key));
}
Assert.False(sortList2.ContainsKey("Non_Existent_Key"));
for (int i = 0; i < sortList2.Count; i++)
{
string removedKey = "Key_" + i;
sortList2.Remove(removedKey);
Assert.False(sortList2.Contains(removedKey));
Assert.False(sortList2.ContainsKey(removedKey));
}
});
}
[Fact]
public void ContainsKey_NullKey_ThrowsArgumentNullException()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Contains(null)); // Key is null
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.ContainsKey(null)); // Key is null
});
}
[Fact]
public void ContainsValue()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
sortList2.Add(i, "Value_" + i);
Assert.True(sortList2.ContainsValue("Value_" + i));
}
Assert.False(sortList2.ContainsValue("Non_Existent_Value"));
for (int i = 0; i < sortList2.Count; i++)
{
sortList2.Remove(i);
Assert.False(sortList2.ContainsValue("Value_" + i));
}
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public void CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
var array = new object[index + count];
sortList2.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
int actualIndex = i - index;
string key = "Key_" + actualIndex.ToString("D2");
string value = "Value_" + actualIndex;
DictionaryEntry entry = (DictionaryEntry)array[i];
Assert.Equal(key, entry.Key);
Assert.Equal(value, entry.Value);
}
});
}
[Fact]
public void CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("array", () => sortList2.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => sortList2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => sortList2.CopyTo(new object[100], -1)); // Index < 0
AssertExtensions.Throws<ArgumentException>(null, () => sortList2.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Fact]
public void GetByIndex()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
Assert.Equal(i, sortList2.GetByIndex(i));
int i2 = sortList2.IndexOfKey(i);
Assert.Equal(i, i2);
i2 = sortList2.IndexOfValue(i);
Assert.Equal(i, i2);
}
});
}
[Fact]
public void GetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(sortList2.Count)); // Index >= list.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void GetEnumerator_IDictionaryEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.NotSame(sortList2.GetEnumerator(), sortList2.GetEnumerator());
IDictionaryEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
Assert.Equal(enumerator.Current, enumerator.Entry);
Assert.Equal(enumerator.Entry.Key, enumerator.Key);
Assert.Equal(enumerator.Entry.Value, enumerator.Value);
Assert.Equal(sortList2.GetKey(counter), enumerator.Entry.Key);
Assert.Equal(sortList2.GetByIndex(counter), enumerator.Entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public void GetEnumerator_IDictionaryEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IDictionaryEnumerator enumerator = sortList2.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw if index < 0
enumerator = sortList2.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw after resetting
enumerator = sortList2.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw if the current index is >= count
enumerator = sortList2.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void GetEnumerator_IEnumerator(int count)
{
SortedList sortList = Helpers.CreateIntSortedList(count);
Assert.NotSame(sortList.GetEnumerator(), sortList.GetEnumerator());
IEnumerator enumerator = sortList.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
DictionaryEntry dictEntry = (DictionaryEntry)enumerator.Current;
Assert.Equal(sortList.GetKey(counter), dictEntry.Key);
Assert.Equal(sortList.GetByIndex(counter), dictEntry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
}
[Fact]
public void GetEnumerator_StartOfEnumeration_Clone()
{
SortedList sortedList = Helpers.CreateIntSortedList(10);
IDictionaryEnumerator enumerator = sortedList.GetEnumerator();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
IDictionaryEnumerator clonedEnumerator = (IDictionaryEnumerator)cloneableEnumerator.Clone();
Assert.NotSame(enumerator, clonedEnumerator);
// Cloned and original enumerators should enumerate separately.
Assert.True(enumerator.MoveNext());
Assert.Equal(sortedList[0], enumerator.Value);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(sortedList[0], enumerator.Value);
Assert.Equal(sortedList[0], clonedEnumerator.Value);
// Cloned and original enumerators should enumerate in the same sequence.
for (int i = 1; i < sortedList.Count; i++)
{
Assert.True(enumerator.MoveNext());
Assert.NotEqual(enumerator.Current, clonedEnumerator.Current);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Equal(sortedList[sortedList.Count - 1], clonedEnumerator.Value);
Assert.False(clonedEnumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value);
}
[Fact]
public void GetEnumerator_InMiddleOfEnumeration_Clone()
{
SortedList sortedList = Helpers.CreateIntSortedList(10);
IEnumerator enumerator = sortedList.GetEnumerator();
enumerator.MoveNext();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
// Cloned and original enumerators should start at the same spot, even
// if the original is in the middle of enumeration.
IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone();
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
for (int i = 0; i < sortedList.Count - 1; i++)
{
Assert.True(clonedEnumerator.MoveNext());
}
Assert.False(clonedEnumerator.MoveNext());
}
[Fact]
public void GetEnumerator_IEnumerator_Invalid()
{
SortedList sortList = Helpers.CreateIntSortedList(100);
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current doesn't
IEnumerator enumerator = ((IEnumerable)sortList).GetEnumerator();
enumerator.MoveNext();
sortList.Add(101, 101);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current throws if index < 0
enumerator = sortList.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throw after resetting
enumerator = sortList.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throw if the current index is >= count
enumerator = sortList.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void GetKeyList(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys1 = sortList2.GetKeyList();
IList keys2 = sortList2.GetKeyList();
// Test we have copied the correct keys
Assert.Equal(count, keys1.Count);
Assert.Equal(count, keys2.Count);
for (int i = 0; i < keys1.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(key, keys1[i]);
Assert.Equal(key, keys2[i]);
Assert.True(sortList2.ContainsKey(keys1[i]));
}
});
}
[Fact]
public void GetKeyList_IsSameAsKeysProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetKeyList(), sortList.Keys);
}
[Fact]
public void GetKeyList_IListProperties()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.True(keys.IsReadOnly);
Assert.True(keys.IsFixedSize);
Assert.False(keys.IsSynchronized);
Assert.Equal(sortList2.SyncRoot, keys.SyncRoot);
});
}
[Fact]
public void GetKeyList_Contains()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
for (int i = 0; i < keys.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.True(keys.Contains(key));
}
Assert.False(keys.Contains("Key_101")); // No such key
});
}
[Fact]
public void GetKeyList_Contains_InvalidValueType_ThrowsInvalidOperationException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<InvalidOperationException>(() => keys.Contains("hello")); // Value is a different object type
});
}
[Fact]
public void GetKeyList_IndexOf()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
for (int i = 0; i < keys.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(i, keys.IndexOf(key));
}
Assert.Equal(-1, keys.IndexOf("Key_101"));
});
}
[Fact]
public void GetKeyList_IndexOf_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
AssertExtensions.Throws<ArgumentNullException>("key", () => keys.IndexOf(null)); // Value is null
Assert.Throws<InvalidOperationException>(() => keys.IndexOf("hello")); // Value is a different object type
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public void GetKeyList_CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
object[] array = new object[index + count];
IList keys = sortList2.GetKeyList();
keys.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(keys[i - index], array[i]);
}
});
}
[Fact]
public void GetKeyList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => keys.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => keys.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => keys.CopyTo(new object[100], -1));
// Index + list.Count > array.Count
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => keys.CopyTo(new object[150], 51));
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void GetKeyList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.NotSame(keys.GetEnumerator(), keys.GetEnumerator());
IEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
object key = keys[counter];
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
Assert.Equal(key, entry.Key);
Assert.Equal(sortList2[key], entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public void GetKeyList_GetEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IEnumerator enumerator = keys.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current etc. throw if index < 0
enumerator = keys.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw after resetting
enumerator = keys.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw if the current index is >= count
enumerator = keys.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public void GetKeyList_TryingToModifyCollection_ThrowsNotSupportedException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<NotSupportedException>(() => keys.Add(101));
Assert.Throws<NotSupportedException>(() => keys.Clear());
Assert.Throws<NotSupportedException>(() => keys.Insert(0, 101));
Assert.Throws<NotSupportedException>(() => keys.Remove(1));
Assert.Throws<NotSupportedException>(() => keys.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => keys[0] = 101);
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public void GetKey(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(key, sortList2.GetKey(sortList2.IndexOfKey(key)));
}
});
}
[Fact]
public void GetKey_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(sortList2.Count)); // Index >= count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void GetValueList(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values1 = sortList2.GetValueList();
IList values2 = sortList2.GetValueList();
// Test we have copied the correct values
Assert.Equal(count, values1.Count);
Assert.Equal(count, values2.Count);
for (int i = 0; i < values1.Count; i++)
{
string value = "Value_" + i;
Assert.Equal(value, values1[i]);
Assert.Equal(value, values2[i]);
Assert.True(sortList2.ContainsValue(values2[i]));
}
});
}
[Fact]
public void GetValueList_IsSameAsValuesProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetValueList(), sortList.Values);
}
[Fact]
public void GetValueList_IListProperties()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.True(values.IsReadOnly);
Assert.True(values.IsFixedSize);
Assert.False(values.IsSynchronized);
Assert.Equal(sortList2.SyncRoot, values.SyncRoot);
});
}
[Fact]
public void GetValueList_Contains()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
for (int i = 0; i < values.Count; i++)
{
string value = "Value_" + i;
Assert.True(values.Contains(value));
}
// No such value
Assert.False(values.Contains("Value_101"));
Assert.False(values.Contains(101));
Assert.False(values.Contains(null));
});
}
[Fact]
public void GetValueList_IndexOf()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
for (int i = 0; i < values.Count; i++)
{
string value = "Value_" + i;
Assert.Equal(i, values.IndexOf(value));
}
Assert.Equal(-1, values.IndexOf(101));
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public void GetValueList_CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
object[] array = new object[index + count];
IList values = sortList2.GetValueList();
values.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(values[i - index], array[i]);
}
});
}
[Fact]
public void GetValueList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => values.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => values.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => values.CopyTo(new object[100], -1)); // Index < 0
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => values.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void GetValueList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.NotSame(values.GetEnumerator(), values.GetEnumerator());
IEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
object key = values[counter];
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
Assert.Equal(key, entry.Key);
Assert.Equal(sortList2[key], entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public void ValueList_GetEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IEnumerator enumerator = values.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current etc. throw if index < 0
enumerator = values.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw after resetting
enumerator = values.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw if the current index is >= count
enumerator = values.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public void GetValueList_TryingToModifyCollection_ThrowsNotSupportedException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.Throws<NotSupportedException>(() => values.Add(101));
Assert.Throws<NotSupportedException>(() => values.Clear());
Assert.Throws<NotSupportedException>(() => values.Insert(0, 101));
Assert.Throws<NotSupportedException>(() => values.Remove(1));
Assert.Throws<NotSupportedException>(() => values.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => values[0] = 101);
});
}
[Fact]
public void IndexOfKey()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
int index = sortList2.IndexOfKey(key);
Assert.Equal(i, index);
Assert.Equal(value, sortList2.GetByIndex(index));
}
Assert.Equal(-1, sortList2.IndexOfKey("Non Existent Key"));
string removedKey = "Key_01";
sortList2.Remove(removedKey);
Assert.Equal(-1, sortList2.IndexOfKey(removedKey));
});
}
[Fact]
public void IndexOfKey_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.IndexOfKey(null)); // Key is null
});
}
[Fact]
public void IndexOfValue()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
string value = "Value_" + i;
int index = sortList2.IndexOfValue(value);
Assert.Equal(i, index);
Assert.Equal(value, sortList2.GetByIndex(index));
}
Assert.Equal(-1, sortList2.IndexOfValue("Non Existent Value"));
string removedKey = "Key_01";
string removedValue = "Value_1";
sortList2.Remove(removedKey);
Assert.Equal(-1, sortList2.IndexOfValue(removedValue));
Assert.Equal(-1, sortList2.IndexOfValue(null));
sortList2.Add("Key_101", null);
Assert.NotEqual(-1, sortList2.IndexOfValue(null));
});
}
[Fact]
public void IndexOfValue_SameValue()
{
var sortList1 = new SortedList();
sortList1.Add("Key_0", "Value_0");
sortList1.Add("Key_1", "Value_Same");
sortList1.Add("Key_2", "Value_Same");
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Equal(1, sortList2.IndexOfValue("Value_Same"));
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(4)]
[InlineData(5000)]
public void Capacity_Get_Set(int capacity)
{
var sortList = new SortedList();
sortList.Capacity = capacity;
Assert.Equal(capacity, sortList.Capacity);
// Ensure nothing changes if we set capacity to the same value again
sortList.Capacity = capacity;
Assert.Equal(capacity, sortList.Capacity);
}
[Fact]
public void Capacity_Set_ShrinkingCapacity_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = sortList2.Count - 1); // Capacity < count
});
}
[Fact]
public void Capacity_Set_Invalid()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = -1); // Capacity < 0
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotIntMaxValueArrayIndexSupported))]
public void Capacity_Excessive()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<OutOfMemoryException>(() => sortList2.Capacity = int.MaxValue); // Capacity is too large
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
public void Item_Get(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
Assert.Equal(value, sortList2[key]);
}
Assert.Null(sortList2["No Such Key"]);
string removedKey = "Key_01";
sortList2.Remove(removedKey);
Assert.Null(sortList2[removedKey]);
});
}
[Fact]
public void Item_Get_DifferentCulture()
{
var sortList = new SortedList();
try
{
var cultureNames = new string[]
{
"cs-CZ","da-DK","de-DE","el-GR","en-US",
"es-ES","fi-FI","fr-FR","hu-HU","it-IT",
"ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
"pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
"zh-CN","zh-HK","zh-TW"
};
var installedCultures = new CultureInfo[cultureNames.Length];
var cultureDisplayNames = new string[installedCultures.Length];
int uniqueDisplayNameCount = 0;
foreach (string cultureName in cultureNames)
{
var culture = new CultureInfo(cultureName);
installedCultures[uniqueDisplayNameCount] = culture;
cultureDisplayNames[uniqueDisplayNameCount] = culture.DisplayName;
sortList.Add(cultureDisplayNames[uniqueDisplayNameCount], culture);
uniqueDisplayNameCount++;
}
// In Czech ch comes after h if the comparer changes based on the current culture of the thread
// we will not be able to find some items
using (new ThreadCultureChange("cs-CZ"))
{
for (int i = 0; i < uniqueDisplayNameCount; i++)
{
Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]);
}
}
}
catch (CultureNotFoundException)
{
}
}
[Fact]
public void Item_Set()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Change existing keys
for (int i = 0; i < sortList2.Count; i++)
{
sortList2[i] = i + 1;
Assert.Equal(i + 1, sortList2[i]);
// Make sure nothing bad happens when we try to set the key to its current valeu
sortList2[i] = i + 1;
Assert.Equal(i + 1, sortList2[i]);
}
// Add new keys
sortList2[101] = 2048;
Assert.Equal(2048, sortList2[101]);
sortList2[102] = null;
Assert.Null(sortList2[102]);
});
}
[Fact]
public void Item_Set_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2[null] = 101); // Key is null
});
}
[Fact]
public void RemoveAt()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Remove from end
for (int i = sortList2.Count - 1; i >= 0; i--)
{
sortList2.RemoveAt(i);
Assert.False(sortList2.ContainsKey(i));
Assert.False(sortList2.ContainsValue(i));
Assert.Equal(i, sortList2.Count);
}
});
}
[Fact]
public void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(sortList2.Count)); // Index >= count
});
}
[Fact]
public void Remove()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Remove from the end
for (int i = sortList2.Count - 1; i >= 0; i--)
{
sortList2.Remove(i);
Assert.False(sortList2.ContainsKey(i));
Assert.False(sortList2.ContainsValue(i));
Assert.Equal(i, sortList2.Count);
}
sortList2.Remove(101); // No such key
});
}
[Fact]
public void Remove_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Remove(null)); // Key is null
});
}
[Fact]
public void SetByIndex()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
sortList2.SetByIndex(i, i + 1);
Assert.Equal(i + 1, sortList2.GetByIndex(i));
}
});
}
[Fact]
public void SetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(-1, 101)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(sortList2.Count, 101)); // Index >= list.Count
});
}
[Fact]
public void Synchronized_IsSynchronized()
{
SortedList sortList = SortedList.Synchronized(new SortedList());
Assert.True(sortList.IsSynchronized);
}
[Fact]
public void Synchronized_NullList_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("list", () => SortedList.Synchronized(null)); // List is null
}
[Fact]
public void TrimToSize()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 10; i++)
{
sortList2.RemoveAt(0);
}
sortList2.TrimToSize();
Assert.Equal(sortList2.Count, sortList2.Capacity);
sortList2.Clear();
sortList2.TrimToSize();
Assert.Equal(0, sortList2.Capacity);
});
}
private class Foo
{
public string StringValue { get; set; } = "Hello World";
}
private class CustomComparer : IComparer
{
public int Compare(object obj1, object obj2) => -string.Compare(obj1.ToString(), obj2.ToString());
}
}
public class SortedList_SyncRootTests
{
private SortedList _sortListDaughter;
private SortedList _sortListGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
[OuterLoop]
public void GetSyncRootBasic()
{
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother SortedList
// 2) Get a synchronized wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var sortListMother = new SortedList();
for (int i = 0; i < NumberOfElements; i++)
{
sortListMother.Add("Key_" + i, "Value_" + i);
}
Assert.Equal(typeof(SortedList), sortListMother.SyncRoot.GetType());
SortedList sortListSon = SortedList.Synchronized(sortListMother);
_sortListGrandDaughter = SortedList.Synchronized(sortListSon);
_sortListDaughter = SortedList.Synchronized(sortListMother);
Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(sortListMother.SyncRoot, sortListSon.SyncRoot);
Assert.Equal(_sortListGrandDaughter.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(_sortListDaughter.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot);
//we are going to rumble with the SortedLists with some threads
var workers = new Task[4];
for (int i = 0; i < workers.Length; i += 2)
{
var name = "Thread_worker_" + i;
var action1 = new Action(() => AddMoreElements(name));
var action2 = new Action(RemoveElements);
workers[i] = Task.Run(action1);
workers[i + 1] = Task.Run(action2);
}
Task.WaitAll(workers);
// Checking time
// Now lets see how this is done.
// Either there are some elements or none
var sortListPossible = new SortedList();
for (int i = 0; i < NumberOfElements; i++)
{
sortListPossible.Add("Key_" + i, "Value_" + i);
}
for (int i = 0; i < workers.Length; i++)
{
sortListPossible.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
}
//lets check the values if
IDictionaryEnumerator enumerator = sortListMother.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.True(sortListPossible.ContainsKey(enumerator.Key));
Assert.True(sortListPossible.ContainsValue(enumerator.Value));
}
}
private void AddMoreElements(string threadName)
{
_sortListGrandDaughter.Add("Key_" + threadName, threadName);
}
private void RemoveElements()
{
_sortListDaughter.Clear();
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ExpressRouteCircuitAuthorizationsOperations.
/// </summary>
public static partial class ExpressRouteCircuitAuthorizationsOperationsExtensions
{
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
public static void Delete(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
operations.DeleteAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
public static ExpressRouteCircuitAuthorization Get(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
return operations.GetAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> GetAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
public static ExpressRouteCircuitAuthorization CreateOrUpdate(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> CreateOrUpdateAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
public static IPage<ExpressRouteCircuitAuthorization> List(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName)
{
return operations.ListAsync(resourceGroupName, circuitName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuitAuthorization>> ListAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
public static void BeginDelete(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
operations.BeginDeleteAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
public static ExpressRouteCircuitAuthorization BeginCreateOrUpdate(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> BeginCreateOrUpdateAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ExpressRouteCircuitAuthorization> ListNext(this IExpressRouteCircuitAuthorizationsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuitAuthorization>> ListNextAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace MoraleOMeter.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// ****************************************************************************
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// CONTENTS
// Performance counters used by default host
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Transactions;
using System.Workflow.Runtime.Hosting;
namespace System.Workflow.Runtime
{
internal enum PerformanceCounterOperation
{
Increment,
Decrement
}
internal enum PerformanceCounterAction
{
Aborted,
Completion,
Creation,
Unloading,
Executing,
Idle,
NotExecuting,
Persisted,
Loading,
Runnable,
Suspension,
Resumption,
Termination,
Starting,
}
internal sealed class PerformanceCounterManager
{
private static String c_PerformanceCounterCategoryName = ExecutionStringManager.PerformanceCounterCategory;
// Create a declarative model for specifying performance counter behavior.
private static PerformanceCounterData[] s_DefaultPerformanceCounters = new PerformanceCounterData[]
{
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesCreatedName,
ExecutionStringManager.PerformanceCounterSchedulesCreatedDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Creation, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesCreatedRateName,
ExecutionStringManager.PerformanceCounterSchedulesCreatedRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Creation, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesUnloadedName,
ExecutionStringManager.PerformanceCounterSchedulesUnloadedDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Unloading, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesUnloadedRateName,
ExecutionStringManager.PerformanceCounterSchedulesUnloadedRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Unloading, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesLoadedName,
ExecutionStringManager.PerformanceCounterSchedulesLoadedDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Loading, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesLoadedRateName,
ExecutionStringManager.PerformanceCounterSchedulesLoadedRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Loading, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesCompletedName,
ExecutionStringManager.PerformanceCounterSchedulesCompletedDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Completion, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesCompletedRateName,
ExecutionStringManager.PerformanceCounterSchedulesCompletedRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Completion, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesSuspendedName,
ExecutionStringManager.PerformanceCounterSchedulesSuspendedDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Suspension, PerformanceCounterOperation.Increment ),
new PerformanceCounterActionMapping( PerformanceCounterAction.Resumption, PerformanceCounterOperation.Decrement ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesSuspendedRateName,
ExecutionStringManager.PerformanceCounterSchedulesSuspendedRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Suspension, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesTerminatedName,
ExecutionStringManager.PerformanceCounterSchedulesTerminatedDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Termination, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesTerminatedRateName,
ExecutionStringManager.PerformanceCounterSchedulesTerminatedRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Termination, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesInMemoryName,
ExecutionStringManager.PerformanceCounterSchedulesInMemoryDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Creation, PerformanceCounterOperation.Increment ),
new PerformanceCounterActionMapping( PerformanceCounterAction.Loading, PerformanceCounterOperation.Increment ),
new PerformanceCounterActionMapping( PerformanceCounterAction.Unloading, PerformanceCounterOperation.Decrement ),
new PerformanceCounterActionMapping( PerformanceCounterAction.Completion, PerformanceCounterOperation.Decrement ),
new PerformanceCounterActionMapping( PerformanceCounterAction.Termination, PerformanceCounterOperation.Decrement ),
new PerformanceCounterActionMapping( PerformanceCounterAction.Aborted, PerformanceCounterOperation.Decrement ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesExecutingName,
ExecutionStringManager.PerformanceCounterSchedulesExecutingDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Executing, PerformanceCounterOperation.Increment ),
new PerformanceCounterActionMapping( PerformanceCounterAction.NotExecuting, PerformanceCounterOperation.Decrement ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesIdleRateName,
ExecutionStringManager.PerformanceCounterSchedulesIdleRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Idle, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesRunnableName,
ExecutionStringManager.PerformanceCounterSchedulesRunnableDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Runnable, PerformanceCounterOperation.Increment ),
new PerformanceCounterActionMapping( PerformanceCounterAction.NotExecuting, PerformanceCounterOperation.Decrement ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesAbortedName,
ExecutionStringManager.PerformanceCounterSchedulesAbortedDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Aborted, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesAbortedRateName,
ExecutionStringManager.PerformanceCounterSchedulesAbortedRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Aborted, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesPersistedName,
ExecutionStringManager.PerformanceCounterSchedulesPersistedDescription,
PerformanceCounterType.NumberOfItems64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Persisted, PerformanceCounterOperation.Increment ),
}),
new PerformanceCounterData( ExecutionStringManager.PerformanceCounterSchedulesPersistedRateName,
ExecutionStringManager.PerformanceCounterSchedulesPersistedRateDescription,
PerformanceCounterType.RateOfCountsPerSecond64,
new PerformanceCounterActionMapping[]
{
new PerformanceCounterActionMapping( PerformanceCounterAction.Persisted, PerformanceCounterOperation.Increment ),
}),
};
private String m_instanceName;
private Dictionary<PerformanceCounterAction, List<PerformanceCounterStatement>> m_actionStatements;
internal PerformanceCounterManager()
{
}
internal void Initialize(WorkflowRuntime runtime)
{
runtime.WorkflowExecutorInitializing += WorkflowExecutorInitializing;
}
internal void Uninitialize(WorkflowRuntime runtime)
{
runtime.WorkflowExecutorInitializing -= WorkflowExecutorInitializing;
}
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts",
Justification = "Design has been approved.")]
internal void SetInstanceName(String instanceName)
{
PerformanceCounterData[] data = s_DefaultPerformanceCounters;
if (String.IsNullOrEmpty(instanceName))
{
try
{
// The assert is safe here as we never give out the instance name.
new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
Process process = Process.GetCurrentProcess();
ProcessModule mainModule = process.MainModule;
instanceName = mainModule.ModuleName;
}
finally
{
System.Security.CodeAccessPermission.RevertAssert();
}
}
this.m_instanceName = instanceName;
// Build a mapping of PerformanceCounterActions to the actual actions that need
// to be performed. If this become a perf issue, we could build the default mapping
// at build time.
Dictionary<PerformanceCounterAction, List<PerformanceCounterStatement>> actionStatements = new Dictionary<PerformanceCounterAction, List<PerformanceCounterStatement>>();
if (PerformanceCounterCategory.Exists(c_PerformanceCounterCategoryName))
{
for (int i = 0; i < data.Length; ++i)
{
PerformanceCounterData currentData = data[i];
for (int j = 0; j < currentData.Mappings.Length; ++j)
{
PerformanceCounterActionMapping currentMapping = currentData.Mappings[j];
if (!actionStatements.ContainsKey(currentMapping.Action))
{
actionStatements.Add(currentMapping.Action, new List<PerformanceCounterStatement>());
}
List<PerformanceCounterStatement> lStatements = actionStatements[currentMapping.Action];
PerformanceCounterStatement newStatement = new PerformanceCounterStatement(CreateCounters(currentData.Name), currentMapping.Operation);
lStatements.Add(newStatement);
}
}
}
this.m_actionStatements = actionStatements;
}
private void Notify(PerformanceCounterAction action, WorkflowExecutor executor)
{
System.Diagnostics.Debug.Assert(this.m_actionStatements != null);
List<PerformanceCounterStatement> lStatements;
if (this.m_actionStatements.TryGetValue(action, out lStatements))
{
foreach (PerformanceCounterStatement statement in lStatements)
{
NotifyCounter(action, statement, executor);
}
}
}
internal List<PerformanceCounter> CreateCounters(String name)
{
List<PerformanceCounter> counters = new List<PerformanceCounter>();
counters.Add(
new PerformanceCounter(
c_PerformanceCounterCategoryName,
name,
"_Global_",
false));
if (!String.IsNullOrEmpty(this.m_instanceName))
{
counters.Add(
new PerformanceCounter(
c_PerformanceCounterCategoryName,
name,
this.m_instanceName,
false));
}
return counters;
}
private void NotifyCounter(PerformanceCounterAction action, PerformanceCounterStatement statement, WorkflowExecutor executor)
{
foreach (PerformanceCounter counter in statement.Counters)
{
switch (statement.Operation)
{
case PerformanceCounterOperation.Increment:
counter.Increment();
break;
case PerformanceCounterOperation.Decrement:
counter.Decrement();
break;
default:
System.Diagnostics.Debug.Assert(false, "Unknown performance counter operation.");
break;
}
}
}
private void WorkflowExecutorInitializing(object sender, WorkflowRuntime.WorkflowExecutorInitializingEventArgs e)
{
if (null == sender)
throw new ArgumentNullException("sender");
if (null == e)
throw new ArgumentNullException("e");
if (!typeof(WorkflowExecutor).IsInstanceOfType(sender))
throw new ArgumentException("sender");
WorkflowExecutor exec = (WorkflowExecutor)sender;
exec.WorkflowExecutionEvent += new EventHandler<WorkflowExecutor.WorkflowExecutionEventArgs>(WorkflowExecutionEvent);
}
private void WorkflowExecutionEvent(object sender, WorkflowExecutor.WorkflowExecutionEventArgs e)
{
if (null == sender)
throw new ArgumentNullException("sender");
if (!typeof(WorkflowExecutor).IsInstanceOfType(sender))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InvalidArgumentType, "sender", typeof(WorkflowExecutor).ToString()));
WorkflowExecutor exec = (WorkflowExecutor)sender;
PerformanceCounterAction action;
switch (e.EventType)
{
case WorkflowEventInternal.Created:
action = PerformanceCounterAction.Creation;
break;
case WorkflowEventInternal.Started:
action = PerformanceCounterAction.Starting;
break;
case WorkflowEventInternal.Runnable:
action = PerformanceCounterAction.Runnable;
break;
case WorkflowEventInternal.Executing:
action = PerformanceCounterAction.Executing;
break;
case WorkflowEventInternal.NotExecuting:
action = PerformanceCounterAction.NotExecuting;
break;
case WorkflowEventInternal.Resumed:
action = PerformanceCounterAction.Resumption;
break;
case WorkflowEventInternal.SchedulerEmpty:
//
// SchedulerEmpty signals that are about to persist
// after which we will be idle. We need to do the idle
// work now so that it is included in the state for the idle persist.
action = PerformanceCounterAction.Idle;
break;
case WorkflowEventInternal.Completed:
action = PerformanceCounterAction.Completion;
break;
case WorkflowEventInternal.Suspended:
action = PerformanceCounterAction.Suspension;
break;
case WorkflowEventInternal.Terminated:
action = PerformanceCounterAction.Termination;
break;
case WorkflowEventInternal.Loaded:
action = PerformanceCounterAction.Loading;
break;
case WorkflowEventInternal.Aborted:
action = PerformanceCounterAction.Aborted;
break;
case WorkflowEventInternal.Unloaded:
action = PerformanceCounterAction.Unloading;
break;
case WorkflowEventInternal.Persisted:
action = PerformanceCounterAction.Persisted;
break;
default:
return;
}
Notify(action, exec);
}
}
internal struct PerformanceCounterData
{
internal String Name;
internal String Description;
internal PerformanceCounterType CounterType;
internal PerformanceCounterActionMapping[] Mappings;
internal PerformanceCounterData(
String name,
String description,
PerformanceCounterType counterType,
PerformanceCounterActionMapping[] mappings)
{
System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(name));
System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(description));
System.Diagnostics.Debug.Assert(mappings != null && mappings.Length != 0);
this.Name = name;
this.Description = description;
this.CounterType = counterType;
this.Mappings = mappings;
}
};
internal struct PerformanceCounterActionMapping
{
internal PerformanceCounterOperation Operation;
internal PerformanceCounterAction Action;
internal PerformanceCounterActionMapping(PerformanceCounterAction action, PerformanceCounterOperation operation)
{
this.Operation = operation;
this.Action = action;
}
}
internal struct PerformanceCounterStatement
{
internal List<PerformanceCounter> Counters;
internal PerformanceCounterOperation Operation;
internal PerformanceCounterStatement(List<PerformanceCounter> counters,
PerformanceCounterOperation operation)
{
System.Diagnostics.Debug.Assert(counters != null);
this.Counters = counters;
this.Operation = operation;
}
}
}
| |
namespace Lucene.Net.Search
{
using NUnit.Framework;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using Directory = Lucene.Net.Store.Directory;
/*
* 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 Document = Documents.Document;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
[TestFixture]
public class TestTopDocsCollector : LuceneTestCase
{
private sealed class MyTopsDocCollector : TopDocsCollector<ScoreDoc>
{
internal int Idx = 0;
internal int @base = 0;
public MyTopsDocCollector(int size)
: base(new HitQueue(size, false))
{
}
protected override TopDocs NewTopDocs(ScoreDoc[] results, int start)
{
if (results == null)
{
return EMPTY_TOPDOCS;
}
float maxScore = float.NaN;
if (start == 0)
{
maxScore = results[0].Score;
}
else
{
for (int i = m_pq.Count; i > 1; i--)
{
m_pq.Pop();
}
maxScore = m_pq.Pop().Score;
}
return new TopDocs(TotalHits, results, maxScore);
}
public override void Collect(int doc)
{
++TotalHits;
m_pq.InsertWithOverflow(new ScoreDoc(doc + @base, Scores[Idx++]));
}
public override void SetNextReader(AtomicReaderContext context)
{
@base = context.DocBase;
}
public override void SetScorer(Scorer scorer)
{
// Don't do anything. Assign scores in random
}
public override bool AcceptsDocsOutOfOrder
{
get { return true; }
}
}
// Scores array to be used by MyTopDocsCollector. If it is changed, MAX_SCORE
// must also change.
private static readonly float[] Scores = new float[] { 0.7767749f, 1.7839992f, 8.9925785f, 7.9608946f, 0.07948637f, 2.6356435f, 7.4950366f, 7.1490803f, 8.108544f, 4.961808f, 2.2423935f, 7.285586f, 4.6699767f, 2.9655676f, 6.953706f, 5.383931f, 6.9916306f, 8.365894f, 7.888485f, 8.723962f, 3.1796896f, 0.39971232f, 1.3077754f, 6.8489285f, 9.17561f, 5.060466f, 7.9793315f, 8.601509f, 4.1858315f, 0.28146625f };
private const float MAX_SCORE = 9.17561f;
private Directory Dir;
private IndexReader Reader;
private TopDocsCollector<ScoreDoc> DoSearch(int numResults)
{
Query q = new MatchAllDocsQuery();
IndexSearcher searcher = NewSearcher(Reader);
TopDocsCollector<ScoreDoc> tdc = new MyTopsDocCollector(numResults);
searcher.Search(q, tdc);
return tdc;
}
[SetUp]
public override void SetUp()
{
base.SetUp();
// populate an index with 30 documents, this should be enough for the test.
// The documents have no content - the test uses MatchAllDocsQuery().
Dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, Similarity, TimeZone);
for (int i = 0; i < 30; i++)
{
writer.AddDocument(new Document());
}
Reader = writer.Reader;
writer.Dispose();
}
[TearDown]
public override void TearDown()
{
Reader.Dispose();
Dir.Dispose();
Dir = null;
base.TearDown();
}
[Test]
public virtual void TestInvalidArguments()
{
int numResults = 5;
TopDocsCollector<ScoreDoc> tdc = DoSearch(numResults);
// start < 0
Assert.AreEqual(0, tdc.GetTopDocs(-1).ScoreDocs.Length);
// start > pq.Size()
Assert.AreEqual(0, tdc.GetTopDocs(numResults + 1).ScoreDocs.Length);
// start == pq.Size()
Assert.AreEqual(0, tdc.GetTopDocs(numResults).ScoreDocs.Length);
// howMany < 0
Assert.AreEqual(0, tdc.GetTopDocs(0, -1).ScoreDocs.Length);
// howMany == 0
Assert.AreEqual(0, tdc.GetTopDocs(0, 0).ScoreDocs.Length);
}
[Test]
public virtual void TestZeroResults()
{
TopDocsCollector<ScoreDoc> tdc = new MyTopsDocCollector(5);
Assert.AreEqual(0, tdc.GetTopDocs(0, 1).ScoreDocs.Length);
}
[Test]
public virtual void TestFirstResultsPage()
{
TopDocsCollector<ScoreDoc> tdc = DoSearch(15);
Assert.AreEqual(10, tdc.GetTopDocs(0, 10).ScoreDocs.Length);
}
[Test]
public virtual void TestSecondResultsPages()
{
TopDocsCollector<ScoreDoc> tdc = DoSearch(15);
// ask for more results than are available
Assert.AreEqual(5, tdc.GetTopDocs(10, 10).ScoreDocs.Length);
// ask for 5 results (exactly what there should be
tdc = DoSearch(15);
Assert.AreEqual(5, tdc.GetTopDocs(10, 5).ScoreDocs.Length);
// ask for less results than there are
tdc = DoSearch(15);
Assert.AreEqual(4, tdc.GetTopDocs(10, 4).ScoreDocs.Length);
}
[Test]
public virtual void TestGetAllResults()
{
TopDocsCollector<ScoreDoc> tdc = DoSearch(15);
Assert.AreEqual(15, tdc.GetTopDocs().ScoreDocs.Length);
}
[Test]
public virtual void TestGetResultsFromStart()
{
TopDocsCollector<ScoreDoc> tdc = DoSearch(15);
// should bring all results
Assert.AreEqual(15, tdc.GetTopDocs(0).ScoreDocs.Length);
tdc = DoSearch(15);
// get the last 5 only.
Assert.AreEqual(5, tdc.GetTopDocs(10).ScoreDocs.Length);
}
[Test]
public virtual void TestMaxScore()
{
// ask for all results
TopDocsCollector<ScoreDoc> tdc = DoSearch(15);
TopDocs td = tdc.GetTopDocs();
Assert.AreEqual(MAX_SCORE, td.MaxScore, 0f);
// ask for 5 last results
tdc = DoSearch(15);
td = tdc.GetTopDocs(10);
Assert.AreEqual(MAX_SCORE, td.MaxScore, 0f);
}
// this does not test the PQ's correctness, but whether topDocs()
// implementations return the results in decreasing score order.
[Test]
public virtual void TestResultsOrder()
{
TopDocsCollector<ScoreDoc> tdc = DoSearch(15);
ScoreDoc[] sd = tdc.GetTopDocs().ScoreDocs;
Assert.AreEqual(MAX_SCORE, sd[0].Score, 0f);
for (int i = 1; i < sd.Length; i++)
{
Assert.IsTrue(sd[i - 1].Score >= sd[i].Score);
}
}
}
}
| |
using Discord.Rest;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Channel;
namespace Discord.WebSocket
{
/// <summary>
/// Represents a WebSocket-based direct-message channel.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SocketDMChannel : SocketChannel, IDMChannel, ISocketPrivateChannel, ISocketMessageChannel
{
private readonly MessageCache _messages;
/// <summary>
/// Gets the recipient of the channel.
/// </summary>
public SocketUser Recipient { get; }
/// <inheritdoc />
public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>();
/// <summary>
/// Gets a collection that is the current logged-in user and the recipient.
/// </summary>
public new IReadOnlyCollection<SocketUser> Users => ImmutableArray.Create(Discord.CurrentUser, Recipient);
internal SocketDMChannel(DiscordSocketClient discord, ulong id, SocketGlobalUser recipient)
: base(discord, id)
{
Recipient = recipient;
recipient.GlobalUser.AddRef();
if (Discord.MessageCacheSize > 0)
_messages = new MessageCache(Discord);
}
internal static SocketDMChannel Create(DiscordSocketClient discord, ClientState state, Model model)
{
var entity = new SocketDMChannel(discord, model.Id, discord.GetOrCreateUser(state, model.Recipients.Value[0]));
entity.Update(state, model);
return entity;
}
internal override void Update(ClientState state, Model model)
{
Recipient.Update(state, model.Recipients.Value[0]);
}
/// <inheritdoc />
public Task CloseAsync(RequestOptions options = null)
=> ChannelHelper.DeleteAsync(this, Discord, options);
//Messages
/// <inheritdoc />
public SocketMessage GetCachedMessage(ulong id)
=> _messages?.Get(id);
/// <summary>
/// Gets the message associated with the given <paramref name="id"/>.
/// </summary>
/// <param name="id">TThe ID of the message.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// The message gotten from either the cache or the download, or <c>null</c> if none is found.
/// </returns>
public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null)
{
IMessage msg = _messages?.Get(id);
if (msg == null)
msg = await ChannelHelper.GetMessageAsync(this, Discord, id, options).ConfigureAwait(false);
return msg;
}
/// <summary>
/// Gets the last N messages from this message channel.
/// </summary>
/// <remarks>
/// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(int, CacheMode, RequestOptions)"/>.
/// Please visit its documentation for more details on this method.
/// </remarks>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options);
/// <summary>
/// Gets a collection of messages in this channel.
/// </summary>
/// <remarks>
/// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(ulong, Direction, int, CacheMode, RequestOptions)"/>.
/// Please visit its documentation for more details on this method.
/// </remarks>
/// <param name="fromMessageId">The ID of the starting message to get the messages from.</param>
/// <param name="dir">The direction of the messages to be gotten from.</param>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options);
/// <summary>
/// Gets a collection of messages in this channel.
/// </summary>
/// <remarks>
/// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(IMessage, Direction, int, CacheMode, RequestOptions)"/>.
/// Please visit its documentation for more details on this method.
/// </remarks>
/// <param name="fromMessage">The starting message to get the messages from.</param>
/// <param name="dir">The direction of the messages to be gotten from.</param>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options);
/// <inheritdoc />
public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch)
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit);
/// <inheritdoc />
public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit);
/// <inheritdoc />
public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit);
/// <inheritdoc />
public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null)
=> ChannelHelper.GetPinnedMessagesAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options);
/// <inheritdoc />
public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false)
=> ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options, isSpoiler);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false)
=> ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options, isSpoiler);
/// <inheritdoc />
public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
/// <inheritdoc />
public Task TriggerTypingAsync(RequestOptions options = null)
=> ChannelHelper.TriggerTypingAsync(this, Discord, options);
/// <inheritdoc />
public IDisposable EnterTypingState(RequestOptions options = null)
=> ChannelHelper.EnterTypingState(this, Discord, options);
internal void AddMessage(SocketMessage msg)
=> _messages?.Add(msg);
internal SocketMessage RemoveMessage(ulong id)
=> _messages?.Remove(id);
//Users
/// <summary>
/// Gets a user in this channel from the provided <paramref name="id"/>.
/// </summary>
/// <param name="id">The snowflake identifier of the user.</param>
/// <returns>
/// A <see cref="SocketUser"/> object that is a recipient of this channel; otherwise <c>null</c>.
/// </returns>
public new SocketUser GetUser(ulong id)
{
if (id == Recipient.Id)
return Recipient;
else if (id == Discord.CurrentUser.Id)
return Discord.CurrentUser;
else
return null;
}
/// <summary>
/// Returns the recipient user.
/// </summary>
public override string ToString() => $"@{Recipient}";
private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)";
internal new SocketDMChannel Clone() => MemberwiseClone() as SocketDMChannel;
//SocketChannel
/// <inheritdoc />
internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users;
/// <inheritdoc />
internal override SocketUser GetUserInternal(ulong id) => GetUser(id);
//IDMChannel
/// <inheritdoc />
IUser IDMChannel.Recipient => Recipient;
//ISocketPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<SocketUser> ISocketPrivateChannel.Recipients => ImmutableArray.Create(Recipient);
//IPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<IUser> IPrivateChannel.Recipients => ImmutableArray.Create<IUser>(Recipient);
//IMessageChannel
/// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return await GetMessageAsync(id, options).ConfigureAwait(false);
else
return GetCachedMessage(id);
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options);
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options);
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options);
/// <inheritdoc />
async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
=> await GetPinnedMessagesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler)
=> await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler)
=> await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
//IChannel
/// <inheritdoc />
string IChannel.Name => $"@{Recipient}";
/// <inheritdoc />
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(id));
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
}
}
| |
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// 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.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Mono.Security.Protocol.Tls.Handshake;
using Mono.Security.Interface;
namespace Mono.Security.Protocol.Tls
{
#if INSIDE_SYSTEM
internal
#else
public
#endif
class SslServerStream : SslStreamBase
{
#region Internal Events
internal event CertificateValidationCallback ClientCertValidation;
internal event PrivateKeySelectionCallback PrivateKeySelection;
#endregion
#region Properties
public X509Certificate ClientCertificate
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.ClientSettings.ClientCertificate;
}
return null;
}
}
#endregion
#region Callback Properties
public CertificateValidationCallback ClientCertValidationDelegate
{
get { return this.ClientCertValidation; }
set { this.ClientCertValidation = value; }
}
public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
{
get { return this.PrivateKeySelection; }
set { this.PrivateKeySelection = value; }
}
#endregion
public event CertificateValidationCallback2 ClientCertValidation2;
#region Constructors
public SslServerStream(
Stream stream,
X509Certificate serverCertificate) : this(
stream,
serverCertificate,
false,
false,
SecurityProtocolType.Default)
{
}
public SslServerStream(
Stream stream,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool ownsStream): this(
stream,
serverCertificate,
clientCertificateRequired,
ownsStream,
SecurityProtocolType.Default)
{
}
public SslServerStream(
Stream stream,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool requestClientCertificate,
bool ownsStream)
: this (stream, serverCertificate, clientCertificateRequired, requestClientCertificate, ownsStream, SecurityProtocolType.Default)
{
}
public SslServerStream(
Stream stream,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool ownsStream,
SecurityProtocolType securityProtocolType)
: this (stream, serverCertificate, clientCertificateRequired, false, ownsStream, securityProtocolType)
{
}
public SslServerStream(
Stream stream,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool requestClientCertificate,
bool ownsStream,
SecurityProtocolType securityProtocolType)
: base(stream, ownsStream)
{
this.context = new ServerContext(
this,
securityProtocolType,
serverCertificate,
clientCertificateRequired,
requestClientCertificate);
this.protocol = new ServerRecordProtocol(innerStream, (ServerContext)this.context);
}
#endregion
#region Finalizer
~SslServerStream()
{
this.Dispose(false);
}
#endregion
#region IDisposable Methods
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.ClientCertValidation = null;
this.PrivateKeySelection = null;
}
}
#endregion
#region Handsake Methods
/*
Client Server
ClientHello -------->
ServerHello
Certificate*
ServerKeyExchange*
CertificateRequest*
<-------- ServerHelloDone
Certificate*
ClientKeyExchange
CertificateVerify*
[ChangeCipherSpec]
Finished -------->
[ChangeCipherSpec]
<-------- Finished
Application Data <-------> Application Data
Fig. 1 - Message flow for a full handshake
*/
internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state)
{
// Reset the context if needed
if (this.context.HandshakeState != HandshakeState.None)
{
this.context.Clear();
}
// Obtain supported cipher suites
this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (true, context.SecurityProtocol);
// Set handshake state
this.context.HandshakeState = HandshakeState.Started;
// Receive Client Hello message
return this.protocol.BeginReceiveRecord(this.innerStream, callback, state);
}
internal override void EndNegotiateHandshake(IAsyncResult asyncResult)
{
// Receive Client Hello message and ignore it
this.protocol.EndReceiveRecord(asyncResult);
// If received message is not an ClientHello send a
// Fatal Alert
if (this.context.LastHandshakeMsg != HandshakeType.ClientHello)
{
this.protocol.SendAlert(AlertDescription.UnexpectedMessage);
}
// Send ServerHello message
this.protocol.SendRecord(HandshakeType.ServerHello);
// Send ServerCertificate message
this.protocol.SendRecord(HandshakeType.Certificate);
// If the client certificate is required send the CertificateRequest message
if (((ServerContext)this.context).ClientCertificateRequired ||
((ServerContext)this.context).RequestClientCertificate)
{
this.protocol.SendRecord(HandshakeType.CertificateRequest);
}
// Send ServerHelloDone message
this.protocol.SendRecord(HandshakeType.ServerHelloDone);
// Receive client response, until the Client Finished message
// is received. IE can be interrupted at this stage and never
// complete the handshake
while (this.context.LastHandshakeMsg != HandshakeType.Finished)
{
byte[] record = this.protocol.ReceiveRecord(this.innerStream);
if ((record == null) || (record.Length == 0))
{
throw new TlsException(
AlertDescription.HandshakeFailiure,
"The client stopped the handshake.");
}
}
// Send ChangeCipherSpec and ServerFinished messages
this.protocol.SendChangeCipherSpec();
this.protocol.SendRecord (HandshakeType.Finished);
// The handshake is finished
this.context.HandshakeState = HandshakeState.Finished;
// Reset Handshake messages information
this.context.HandshakeMessages.Reset ();
// Clear Key Info
this.context.ClearKeyInfo();
}
#endregion
#region Event Methods
internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
{
throw new NotSupportedException();
}
internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
{
if (this.ClientCertValidation != null)
{
return this.ClientCertValidation(certificate, errors);
}
return (errors != null && errors.Length == 0);
}
internal override bool HaveRemoteValidation2Callback {
get { return ClientCertValidation2 != null; }
}
internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
{
CertificateValidationCallback2 cb = ClientCertValidation2;
if (cb != null)
return cb (collection);
return null;
}
internal bool RaiseClientCertificateValidation(
X509Certificate certificate,
int[] certificateErrors)
{
return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
}
internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
{
if (this.PrivateKeySelection != null)
{
return this.PrivateKeySelection(certificate, targetHost);
}
return null;
}
internal AsymmetricAlgorithm RaisePrivateKeySelection(
X509Certificate certificate,
string targetHost)
{
return base.RaiseLocalPrivateKeySelection(certificate, targetHost);
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace OpenLiveWriter.HtmlParser.Parser
{
/// <summary>
/// Wrapper class for the HTML parser that makes it easy to
/// search for and extract particular elements in the HTML.
/// </summary>
public class HtmlExtractor
{
private readonly string html;
private SimpleHtmlParser parser;
private Element lastMatch = null;
public HtmlExtractor(Stream data) : this(data, Encoding.UTF8)
{
}
public HtmlExtractor(Stream data, Encoding encoding)
{
using (StreamReader reader = new StreamReader(data, encoding))
html = reader.ReadToEnd();
this.parser = new SimpleHtmlParser(html);
}
public HtmlExtractor(string html)
{
this.html = html;
this.parser = new SimpleHtmlParser(html);
}
/// <summary>
/// Returns the underlying parser that the HtmlExtractor is wrapping.
/// </summary>
public SimpleHtmlParser Parser
{
get { return parser; }
}
/// <summary>
/// Indicates whether the last match succeeded.
/// </summary>
public bool Success
{
get
{
return lastMatch != null;
}
}
/// <summary>
/// Gets the element that was last matched. If the last
/// match failed, then returns null.
/// </summary>
public Element Element
{
get
{
return lastMatch;
}
}
/// <summary>
/// Reposition the extractor back to the beginning of the
/// HTML.
/// </summary>
/// <returns>Returns this. This allows chaining together of calls,
/// like this:
///
/// if (ex.Seek(...).Success || ex.Reset().Seek(...).Success) { ... }
/// </returns>
public HtmlExtractor Reset()
{
lastMatch = null;
parser = new SimpleHtmlParser(html);
return this;
}
public HtmlExtractor Seek(IElementPredicate predicate)
{
lastMatch = null;
SeekWithin(predicate, null);
return this;
}
public HtmlExtractor SeekWithin(IElementPredicate predicate, IElementPredicate withinPredicate)
{
lastMatch = null;
Element e;
while (null != (e = parser.Next()))
{
if (predicate.IsMatch(e))
{
lastMatch = e;
break;
}
if (withinPredicate != null && withinPredicate.IsMatch(e))
break;
}
return this;
}
/// <summary>
/// Seeks forward from the current position for the criterion.
///
/// If the seek fails, the parser will be positioned at the end of the file--all
/// future seeks will also fail (until Reset() is called).
/// </summary>
/// <param name="criterion">
/// Can be either a begin tag or end tag, or a run of text, or a comment.
///
/// Examples of start tags:
/// <a> (any anchor tag)
/// <a name> (any anchor tag that has at least one "name" attribute (with or without value)
/// <a name='title'> (any anchor tag that has a name attribute whose value is "title")
///
/// Example of end tag:
/// </a> (any end anchor tag)
///
/// Examples of invalid criteria:
/// <a></a> (only one criterion allowed per seek; chain Seek() calls if necessary)
/// foo (only begin tags and end tags are allowed)
///
/// TODO: Allow regular expression matching on attribute values, e.g. <a class=/^heading.*$/>
/// </param>
public HtmlExtractor Seek(string criterion)
{
lastMatch = null;
SeekWithin(Parse(criterion), null);
return this;
}
public HtmlExtractor SeekWithin(string criterion, string withinCriterion)
{
lastMatch = null;
SeekWithin(Parse(criterion), Parse(withinCriterion));
return this;
}
public HtmlExtractor MatchNext(IElementPredicate predicate, bool ignoreWhitespace)
{
lastMatch = null;
Element e;
do
{
e = parser.Next();
}
while (e != null && ignoreWhitespace && IsWhitespaceOrZeroLengthText(e));
if (e != null && predicate.IsMatch(e))
lastMatch = e;
return this;
}
public HtmlExtractor MatchNext(string criterion)
{
return MatchNext(criterion, false);
}
public HtmlExtractor MatchNext(string criterion, bool ignoreWhitespace)
{
lastMatch = null;
MatchNext(Parse(criterion), ignoreWhitespace);
return this;
}
/// <summary>
/// Does tag balancing. Pass just the tag *name*, not
/// an actual end tag.
/// </summary>
public string CollectTextUntil(string endTagName)
{
return HtmlUtils.HTMLToPlainText(parser.CollectHtmlUntil(endTagName));
/*
string text = parser.CollectTextUntil(endTagName);
if (convertToPlainText && text != null)
return HtmlUtils.HTMLToPlainText(text);
else
return text;
*/
}
/// <summary>
/// Does not do tag balancing.
/// </summary>
public string CollectTextUntilCriterion(string criterion)
{
return CollectTextUntilPredicate(Parse(criterion));
}
/// <summary>
/// Does not do tag balancing.
/// </summary>
public string CollectTextUntilPredicate(IElementPredicate elementp)
{
return HtmlUtils.HTMLToPlainText(CollectHtmlUntilPredicate(elementp));
}
/// <summary>
/// Does not do tag balancing.
/// </summary>
public string CollectHtmlUntilPredicate(IElementPredicate elementp)
{
StringBuilder result = new StringBuilder();
Element el;
while (null != (el = Next()))
{
if (elementp.IsMatch(el))
break;
result.Append(html, el.Offset, el.Length);
}
return result.ToString();
}
public Element Next()
{
return Next(false);
}
public Element Next(bool ignoreWhitespace)
{
Element e;
do
{
e = parser.Next();
}
while (e != null && ignoreWhitespace && IsWhitespaceOrZeroLengthText(e));
return e;
}
internal static IElementPredicate Parse(string criterion)
{
SimpleHtmlParser parser = new SimpleHtmlParser(criterion);
Element el = parser.Next();
if (el == null)
{
Trace.Fail("Criterion was null");
throw new ArgumentException("Criterion was null");
}
if (parser.Next() != null)
{
Trace.Fail("Too many criteria");
throw new ArgumentException("Too many criteria");
}
if (el is BeginTag)
{
BeginTag tag = (BeginTag)el;
if (tag.HasResidue || tag.Unterminated)
{
Trace.Fail("Malformed criterion");
throw new ArgumentException("Malformed criterion");
}
RequiredAttribute[] attributes = new RequiredAttribute[tag.Attributes.Length];
for (int i = 0; i < attributes.Length; i++)
attributes[i] = new RequiredAttribute(tag.Attributes[i].Name, tag.Attributes[i].Value);
return new BeginTagPredicate(tag.Name, attributes);
}
else if (el is EndTag)
{
return new EndTagPredicate(((EndTag)el).Name);
}
else if (el is Text)
{
return new TextPredicate(el.RawText);
}
else if (el is Comment)
{
return new CommentPredicate(el.RawText);
}
else
{
Trace.Fail("Invalid criterion \"" + criterion + "\"");
throw new ArgumentException("Invalid criterion \"" + criterion + "\"");
}
}
private bool IsWhitespaceOrZeroLengthText(Element e)
{
if (!(e is Text))
return false;
int end = e.Offset + e.Length;
for (int i = e.Offset; i < end; i++)
{
if (!char.IsWhiteSpace(html[i]))
return false;
}
return true;
}
}
public interface IElementPredicate
{
bool IsMatch(Element e);
}
public class PredicatePair
{
private readonly IElementPredicate _match;
private readonly IElementPredicate _stop;
public PredicatePair(IElementPredicate match, IElementPredicate stop)
{
_match = match;
_stop = stop;
}
public IElementPredicate Match
{
get
{
return _match;
}
}
public IElementPredicate Stop
{
get
{
return _stop;
}
}
}
public class AndPredicate : IElementPredicate
{
private readonly IElementPredicate[] predicates;
public AndPredicate(params IElementPredicate[] predicates)
{
this.predicates = predicates;
}
public bool IsMatch(Element e)
{
foreach (IElementPredicate predicate in predicates)
if (!predicate.IsMatch(e))
return false;
return true;
}
}
public class OrPredicate : IElementPredicate
{
private readonly IElementPredicate[] predicates;
public OrPredicate(params IElementPredicate[] predicates)
{
this.predicates = predicates;
}
public bool IsMatch(Element e)
{
foreach (IElementPredicate predicate in predicates)
if (predicate.IsMatch(e))
return true;
return false;
}
}
public class EndTagPredicate : IElementPredicate
{
private readonly string tagName;
public EndTagPredicate(string tagName)
{
this.tagName = tagName;
}
public bool IsMatch(Element e)
{
EndTag tag = e as EndTag;
if (tag == null)
return false;
return tag.NameEquals(tagName);
}
}
public class BeginTagPredicate : IElementPredicate
{
private string tagName;
private RequiredAttribute[] attrs;
public BeginTagPredicate(string tagName, params RequiredAttribute[] attrs)
{
this.tagName = tagName;
this.attrs = attrs;
}
public bool IsMatch(Element e)
{
BeginTag tag = e as BeginTag;
if (tag == null)
return false;
if (tagName != null && !tag.NameEquals(tagName))
return false;
foreach (RequiredAttribute reqAttr in attrs)
{
int foundAt;
Attr attr = tag.GetAttribute(reqAttr.Name, true, 0, out foundAt);
if (attr == null)
return false;
if (reqAttr.Value != null && reqAttr.Value != attr.Value)
return false;
}
return true;
}
}
public class TextPredicate : IElementPredicate
{
private readonly string textToMatch;
public TextPredicate(string textToMatch)
{
this.textToMatch = textToMatch;
}
public bool IsMatch(Element e)
{
Text text = e as Text;
if (text == null)
return false;
return text.RawText == textToMatch;
}
}
public class CommentPredicate : IElementPredicate
{
private readonly string textToMatch;
public CommentPredicate(string textToMatch)
{
this.textToMatch = textToMatch;
}
public bool IsMatch(Element e)
{
Comment comment = e as Comment;
if (comment == null)
return false;
return comment.RawText == textToMatch;
}
}
public class SmartPredicate : IElementPredicate
{
private readonly IElementPredicate actualPredicate;
public SmartPredicate(string criterion)
{
actualPredicate = HtmlExtractor.Parse(criterion);
}
public bool IsMatch(Element e)
{
return actualPredicate.IsMatch(e);
}
}
public class TypePredicate : IElementPredicate
{
private readonly Type type;
private readonly bool allowSubtypes;
public TypePredicate(Type type) : this(type, true)
{
}
public TypePredicate(Type type, bool allowSubtypes)
{
this.type = type;
this.allowSubtypes = allowSubtypes;
}
public bool IsMatch(Element e)
{
if (!allowSubtypes)
return e.GetType().Equals(type);
else
return type.IsInstanceOfType(e);
}
}
public class RequiredAttribute
{
private readonly string name;
private readonly string value;
public RequiredAttribute(string name) : this(name, null)
{
}
public RequiredAttribute(string name, string value)
{
this.name = name;
this.value = value;
}
public string Name
{
get { return name; }
}
public string Value
{
get { return this.value; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using DelegateTestInternal;
using Xunit;
namespace DelegateTestInternal
{
public static class TestExtensionMethod
{
public static DelegateTests.TestStruct TestFunc(this DelegateTests.TestClass testparam)
{
return testparam.structField;
}
}
}
public static unsafe class DelegateTests
{
public struct TestStruct
{
public object o1;
public object o2;
}
public class TestClass
{
public TestStruct structField;
}
public delegate int SomeDelegate(int x);
private static int SquareNumber(int x)
{
return x * x;
}
private static void EmptyFunc()
{
return;
}
public delegate TestStruct StructReturningDelegate();
[Fact]
public static void TestClosedStaticDelegate()
{
TestClass foo = new TestClass();
foo.structField.o1 = new object();
foo.structField.o2 = new object();
StructReturningDelegate testDelegate = foo.TestFunc;
TestStruct returnedStruct = testDelegate();
Assert.True(RuntimeHelpers.ReferenceEquals(foo.structField.o1, returnedStruct.o1));
Assert.True(RuntimeHelpers.ReferenceEquals(foo.structField.o2, returnedStruct.o2));
}
public class A { }
public class B : A { }
public delegate A DynamicInvokeDelegate(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam);
public static A DynamicInvokeTestFunction(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam)
{
outParam = (B)refParam;
refParam = nonRefParam2;
return nonRefParam1;
}
[Fact]
public static void TestDynamicInvoke()
{
A a1 = new A();
A a2 = new A();
B b1 = new B();
B b2 = new B();
DynamicInvokeDelegate testDelegate = DynamicInvokeTestFunction;
// Check that the delegate behaves as expected
A refParam = b2;
B outParam = null;
A returnValue = testDelegate(a1, b1, ref refParam, out outParam);
Assert.True(RuntimeHelpers.ReferenceEquals(returnValue, a1));
Assert.True(RuntimeHelpers.ReferenceEquals(refParam, b1));
Assert.True(RuntimeHelpers.ReferenceEquals(outParam, b2));
// Check dynamic invoke behavior
object[] parameters = new object[4];
parameters[0] = a1;
parameters[1] = b1;
parameters[2] = b2;
parameters[3] = null;
object retVal = testDelegate.DynamicInvoke(parameters);
Assert.True(RuntimeHelpers.ReferenceEquals(retVal, a1));
Assert.True(RuntimeHelpers.ReferenceEquals(parameters[2], b1));
Assert.True(RuntimeHelpers.ReferenceEquals(parameters[3], b2));
// Check invoke on a delegate that takes no parameters.
Action emptyDelegate = EmptyFunc;
emptyDelegate.DynamicInvoke(new object[] { });
emptyDelegate.DynamicInvoke(null);
}
[Fact]
public static void TestDynamicInvokeCastingDefaultValues()
{
{
// Passing Type.Missing without providing default.
Delegate d = new DFoo1(Foo1);
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(7, Type.Missing));
}
{
// Passing Type.Missing with default.
Delegate d = new DFoo1WithDefault(Foo1);
d.DynamicInvoke(7, Type.Missing);
}
return;
}
[Fact]
public static void TestDynamicInvokeCastingByRef()
{
{
Delegate d = new DFoo2(Foo2);
Object[] args = { 7 };
d.DynamicInvoke(args);
Assert.Equal(args[0], 8);
}
{
Delegate d = new DFoo2(Foo2);
Object[] args = { null };
d.DynamicInvoke(args);
Assert.Equal(args[0], 1);
}
// for "byref ValueType" arguments, the incoming is allowed to be null. The target will receive default(ValueType).
{
Delegate d = new DFoo3(Foo3);
Object[] args = { null };
d.DynamicInvoke(args);
MyStruct s = (MyStruct)(args[0]);
Assert.Equal(s.X, 7);
Assert.Equal(s.Y, 8);
}
// For "byref ValueType" arguments, the type must match exactly.
{
Delegate d = new DFoo2(Foo2);
Object[] args = { (uint)7 };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
{
Delegate d = new DFoo2(Foo2);
Object[] args = { E4.One };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
return;
}
[Fact]
public static void TestDynamicInvokeCastingPrimitiveWiden()
{
{
// For primitives, value-preserving widenings allowed.
Delegate d = new DFoo1(Foo1);
Object[] args = { 7, (short)7 };
d.DynamicInvoke(args);
}
{
// For primitives, conversion of enum to underlying integral prior to value-preserving widening allowed.
Delegate d = new DFoo1(Foo1);
Object[] args = { 7, E4.Seven };
d.DynamicInvoke(args);
}
{
// For primitives, conversion of enum to underlying integral prior to value-preserving widening allowed.
Delegate d = new DFoo1(Foo1);
Object[] args = { 7, E2.Seven };
d.DynamicInvoke(args);
}
{
// For primitives, conversion to enum after value-preserving widening allowed.
Delegate d = new DFoo4(Foo4);
Object[] args = { E4.Seven, 7 };
d.DynamicInvoke(args);
}
{
// For primitives, conversion to enum after value-preserving widening allowed.
Delegate d = new DFoo4(Foo4);
Object[] args = { E4.Seven, (short)7 };
d.DynamicInvoke(args);
}
{
// Size-preserving but non-value-preserving conversions NOT allowed.
Delegate d = new DFoo1(Foo1);
Object[] args = { 7, (uint)7 };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
{
// Size-preserving but non-value-preserving conversions NOT allowed.
Delegate d = new DFoo1(Foo1);
Object[] args = { 7, U4.Seven };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
return;
}
[Fact]
public static void TestDynamicInvokeCastingMisc()
{
{
// DynamicInvoke allows "null" for any value type (converts to default(valuetype)).
Delegate d = new DFoo5(Foo5);
Object[] args = { null };
d.DynamicInvoke(args);
}
{
// DynamicInvoke allows conversion of T to Nullable<T>
Delegate d = new DFoo6(Foo6);
Object[] args = { 7 };
d.DynamicInvoke(args);
}
{
// DynamicInvoke allows conversion of T to Nullable<T> but T must match exactly.
Delegate d = new DFoo6(Foo6);
Object[] args = { (short)7 };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
{
// DynamicInvoke allows conversion of T to Nullable<T> but T must match exactly.
Delegate d = new DFoo6(Foo6);
Object[] args = { E4.Seven };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
return;
}
private static void Foo1(int expected, int actual)
{
Assert.Equal(expected, actual);
}
private delegate void DFoo1(int expected, int actual);
private delegate void DFoo1WithDefault(int expected, int actual = 7);
private static void Foo2(ref int i)
{
i++;
}
private delegate void DFoo2(ref int i);
private struct MyStruct
{
public int X;
public int Y;
}
private static void Foo3(ref MyStruct s)
{
s.X += 7;
s.Y += 8;
}
private delegate void DFoo3(ref MyStruct s);
private static void Foo4(E4 expected, E4 actual)
{
Assert.Equal(expected, actual);
}
private delegate void DFoo4(E4 expected, E4 actual);
private static void Foo5(MyStruct s)
{
Assert.Equal(s.X, 0);
Assert.Equal(s.Y, 0);
}
private delegate void DFoo5(MyStruct s);
private static void Foo6(Nullable<int> n)
{
Assert.True(n.HasValue);
Assert.Equal(n.Value, 7);
}
private delegate void DFoo6(Nullable<int> s);
private enum E2 : short
{
One = 1,
Seven = 7,
}
private enum E4 : int
{
One = 1,
Seven = 7,
}
private enum U4 : uint
{
One = 1,
Seven = 7,
}
}
| |
namespace YAF.Pages
{
#region Using
using System;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using VZF.Data.Common;
using YAF.Classes;
using VZF.Controls;
using YAF.Core;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.EventProxies;
using YAF.Types.Interfaces;
using VZF.Utilities;
using VZF.Utils;
#endregion
/// <summary>
/// The cp_message.
/// </summary>
public partial class cp_message : ForumPageRegistered
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref = "cp_message" /> class.
/// </summary>
public cp_message()
: base("CP_MESSAGE")
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether IsArchived.
/// </summary>
protected bool IsArchived
{
get
{
return this.ViewState["IsArchived"] != null && (bool)this.ViewState["IsArchived"];
}
set
{
this.ViewState["IsArchived"] = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether IsOutbox.
/// </summary>
protected bool IsOutbox
{
get
{
return this.ViewState["IsOutbox"] != null && (bool)this.ViewState["IsOutbox"];
}
set
{
this.ViewState["IsOutbox"] = value;
}
}
#endregion
#region Methods
/// <summary>
/// The On PreRender event.
/// </summary>
/// <param name="e">
/// the Event Arguments
/// </param>
protected override void OnPreRender([NotNull] EventArgs e)
{
// Setup Syntax Highlight JS
YafContext.Current.PageElements.RegisterJsResourceInclude(
"syntaxhighlighter", "js/jquery.syntaxhighligher.js");
YafContext.Current.PageElements.RegisterCssIncludeResource("css/jquery.syntaxhighligher.css");
YafContext.Current.PageElements.RegisterJsBlockStartup(
"syntaxhighlighterjs", JavaScriptBlocks.SyntaxHighlightLoadJs);
base.OnPreRender(e);
}
/// <summary>
/// Handles the ItemCommand event of the Inbox control.
/// </summary>
/// <param name="source">The source of the event.</param>
/// <param name="e">The <see cref="RepeaterCommandEventArgs" /> instance containing the event data.</param>
protected void Inbox_ItemCommand([NotNull] object source, [NotNull] RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "delete":
if (this.IsOutbox)
{
CommonDb.pmessage_delete(PageContext.PageModuleID, e.CommandArgument, true);
}
else
{
CommonDb.pmessage_delete(PageContext.PageModuleID, e.CommandArgument);
}
this.BindData();
this.PageContext.AddLoadMessage(this.GetText("msg_deleted"), MessageTypes.Success);
YafBuildLink.Redirect(ForumPages.cp_pm);
break;
case "reply":
YafBuildLink.Redirect(ForumPages.pmessage, "p={0}&q=0", e.CommandArgument);
break;
case "quote":
YafBuildLink.Redirect(ForumPages.pmessage, "p={0}&q=1", e.CommandArgument);
break;
}
}
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
// check if this feature is disabled
if (!this.Get<YafBoardSettings>().AllowPrivateMessages)
{
YafBuildLink.RedirectInfoPage(InfoMessage.Disabled);
}
if (this.IsPostBack)
{
return;
}
if (this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("pm").IsNotSet())
{
YafBuildLink.AccessDenied();
}
this.PageLinks.AddLink(this.Get<YafBoardSettings>().Name, YafBuildLink.GetLink(ForumPages.forum));
this.PageLinks.AddLink(
this.Get<YafBoardSettings>().EnableDisplayName
? this.PageContext.CurrentUserData.DisplayName
: this.PageContext.PageUserName,
YafBuildLink.GetLink(ForumPages.cp_profile));
// handle custom YafBBCode javascript or CSS...
this.Get<IBBCode>().RegisterCustomBBCodePageElements(this.Page, this.GetType());
this.BindData();
}
/// <summary>
/// The theme button delete_ load.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
protected void ThemeButtonDelete_Load([NotNull] object sender, [NotNull] EventArgs e)
{
var themeButton = (ThemeButton)sender;
themeButton.Attributes["onclick"] = "return confirm('{0}')".FormatWith(
this.GetText("confirm_deletemessage"));
}
/// <summary>
/// Binds the data.
/// </summary>
private void BindData()
{
using (
DataTable dt =
CommonDb.pmessage_list(PageContext.PageModuleID, Security.StringToLongOrRedirect(this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("pm"))))
{
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
// if the pm isn't from or two the current user--then it's access denied
if ((int)row["ToUserID"] != this.PageContext.PageUserID
&& (int)row["FromUserID"] != this.PageContext.PageUserID)
{
YafBuildLink.AccessDenied();
}
this.SetMessageView(
row["FromUserID"],
row["ToUserID"],
Convert.ToBoolean(row["IsInOutbox"]),
Convert.ToBoolean(row["IsArchived"]));
// get the return link to the pm listing
if (this.IsOutbox)
{
this.PageLinks.AddLink(
this.GetText("SENTITEMS"), YafBuildLink.GetLink(ForumPages.cp_pm, "v=out"));
}
else if (this.IsArchived)
{
this.PageLinks.AddLink(
this.GetText("ARCHIVE"), YafBuildLink.GetLink(ForumPages.cp_pm, "v=arch"));
}
else
{
this.PageLinks.AddLink(this.GetText("INBOX"), YafBuildLink.GetLink(ForumPages.cp_pm));
}
this.PageLinks.AddLink(row["Subject"].ToString());
this.Inbox.DataSource = dt;
}
else
{
YafBuildLink.Redirect(ForumPages.cp_pm);
}
}
this.DataBind();
if (this.IsOutbox)
{
return;
}
var userPmessageId = this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("pm").ToType<int>();
CommonDb.pmessage_markread(PageContext.PageModuleID, userPmessageId);
this.Get<IDataCache>().Remove(Constants.Cache.ActiveUserLazyData.FormatWith(this.PageContext.PageUserID));
this.Get<IRaiseEvent>().Raise(
new UpdateUserPrivateMessageEvent(this.PageContext.PageUserID, userPmessageId));
}
/// <summary>
/// Sets the IsOutbox property as appropriate for this private message.
/// </summary>
/// <remarks>
/// User id parameters are downcast to object to allow for potential future use of non-integer user id's
/// </remarks>
/// <param name="fromUserID">
/// The from User ID.
/// </param>
/// <param name="toUserID">
/// The to User ID.
/// </param>
/// <param name="messageIsInOutbox">
/// Bool indicating whether the message is in the sender's outbox
/// </param>
/// <param name="messageIsArchived">
/// The message Is Archived.
/// </param>
private void SetMessageView(
[NotNull] object fromUserID, [NotNull] object toUserID, bool messageIsInOutbox, bool messageIsArchived)
{
bool isCurrentUserFrom = fromUserID.Equals(this.PageContext.PageUserID);
bool isCurrentUserTo = toUserID.Equals(this.PageContext.PageUserID);
// check if it's the same user...
if (isCurrentUserFrom && isCurrentUserTo)
{
// it is... handle the view based on the query string passed
this.IsOutbox = this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("v") == "out";
this.IsArchived = this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("v") == "arch";
// see if the message got deleted, if so, redirect to their outbox/archive
if (this.IsOutbox && !messageIsInOutbox)
{
YafBuildLink.Redirect(ForumPages.cp_pm, "v=out");
}
else if (this.IsArchived && !messageIsArchived)
{
YafBuildLink.Redirect(ForumPages.cp_pm, "v=arch");
}
}
else if (isCurrentUserFrom)
{
// see if it's been deleted by the from user...
if (!messageIsInOutbox)
{
// deleted for this user, redirect...
YafBuildLink.Redirect(ForumPages.cp_pm, "v=out");
}
else
{
// nope
this.IsOutbox = true;
}
}
else if (isCurrentUserTo)
{
// get the status for the receiver
this.IsArchived = messageIsArchived;
this.IsOutbox = 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.Collections.Generic;
using System.IO.Enumeration;
using System.Linq;
using System.Security;
namespace System.IO
{
public static partial class Directory
{
public static DirectoryInfo GetParent(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, nameof(path));
string fullPath = Path.GetFullPath(path);
string s = Path.GetDirectoryName(fullPath);
if (s == null)
return null;
return new DirectoryInfo(s);
}
public static DirectoryInfo CreateDirectory(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, nameof(path));
string fullPath = Path.GetFullPath(path);
FileSystem.CreateDirectory(fullPath);
return new DirectoryInfo(fullPath, null);
}
// Input to this method should already be fullpath. This method will ensure that we append
// the trailing slash only when appropriate.
internal static string EnsureTrailingDirectorySeparator(string fullPath)
{
string fullPathWithTrailingDirectorySeparator;
if (!PathHelpers.EndsInDirectorySeparator(fullPath))
fullPathWithTrailingDirectorySeparator = fullPath + PathHelpers.DirectorySeparatorCharAsString;
else
fullPathWithTrailingDirectorySeparator = fullPath;
return fullPathWithTrailingDirectorySeparator;
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
public static bool Exists(string path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
string fullPath = Path.GetFullPath(path);
return FileSystem.DirectoryExists(fullPath);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
public static void SetCreationTime(string path, DateTime creationTime)
{
string fullPath = Path.GetFullPath(path);
FileSystem.SetCreationTime(fullPath, creationTime, asDirectory: true);
}
public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
{
string fullPath = Path.GetFullPath(path);
FileSystem.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true);
}
public static DateTime GetCreationTime(string path)
{
return File.GetCreationTime(path);
}
public static DateTime GetCreationTimeUtc(string path)
{
return File.GetCreationTimeUtc(path);
}
public static void SetLastWriteTime(string path, DateTime lastWriteTime)
{
string fullPath = Path.GetFullPath(path);
FileSystem.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true);
}
public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
{
string fullPath = Path.GetFullPath(path);
FileSystem.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true);
}
public static DateTime GetLastWriteTime(string path)
{
return File.GetLastWriteTime(path);
}
public static DateTime GetLastWriteTimeUtc(string path)
{
return File.GetLastWriteTimeUtc(path);
}
public static void SetLastAccessTime(string path, DateTime lastAccessTime)
{
string fullPath = Path.GetFullPath(path);
FileSystem.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true);
}
public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
{
string fullPath = Path.GetFullPath(path);
FileSystem.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true);
}
public static DateTime GetLastAccessTime(string path)
{
return File.GetLastAccessTime(path);
}
public static DateTime GetLastAccessTimeUtc(string path)
{
return File.GetLastAccessTimeUtc(path);
}
public static string[] GetFiles(string path) => GetFiles(path, "*", enumerationOptions: EnumerationOptions.Compatible);
public static string[] GetFiles(string path, string searchPattern) => GetFiles(path, searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
=> GetFiles(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public static string[] GetFiles(string path, string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumeratePaths(path, searchPattern, SearchTarget.Files, enumerationOptions).ToArray();
public static string[] GetDirectories(string path) => GetDirectories(path, "*", enumerationOptions: EnumerationOptions.Compatible);
public static string[] GetDirectories(string path, string searchPattern) => GetDirectories(path, searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public static string[] GetDirectories(string path, string searchPattern, SearchOption searchOption)
=> GetDirectories(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public static string[] GetDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumeratePaths(path, searchPattern, SearchTarget.Directories, enumerationOptions).ToArray();
public static string[] GetFileSystemEntries(string path) => GetFileSystemEntries(path, "*", enumerationOptions: EnumerationOptions.Compatible);
public static string[] GetFileSystemEntries(string path, string searchPattern) => GetFileSystemEntries(path, searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public static string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption)
=> GetFileSystemEntries(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public static string[] GetFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumeratePaths(path, searchPattern, SearchTarget.Both, enumerationOptions).ToArray();
internal static IEnumerable<string> InternalEnumeratePaths(
string path,
string searchPattern,
SearchTarget searchTarget,
EnumerationOptions options)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options);
switch (searchTarget)
{
case SearchTarget.Files:
return FileSystemEnumerableFactory.UserFiles(path, searchPattern, options);
case SearchTarget.Directories:
return FileSystemEnumerableFactory.UserDirectories(path, searchPattern, options);
case SearchTarget.Both:
return FileSystemEnumerableFactory.UserEntries(path, searchPattern, options);
default:
throw new ArgumentOutOfRangeException(nameof(searchTarget));
}
}
public static IEnumerable<string> EnumerateDirectories(string path) => EnumerateDirectories(path, "*", enumerationOptions: EnumerationOptions.Compatible);
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern) => EnumerateDirectories(path, searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption)
=> EnumerateDirectories(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumeratePaths(path, searchPattern, SearchTarget.Directories, enumerationOptions);
public static IEnumerable<string> EnumerateFiles(string path) => EnumerateFiles(path, "*", enumerationOptions: EnumerationOptions.Compatible);
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern)
=> EnumerateFiles(path, searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption)
=> EnumerateFiles(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumeratePaths(path, searchPattern, SearchTarget.Files, enumerationOptions);
public static IEnumerable<string> EnumerateFileSystemEntries(string path)
=> EnumerateFileSystemEntries(path, "*", enumerationOptions: EnumerationOptions.Compatible);
public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern)
=> EnumerateFileSystemEntries(path, searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption)
=> EnumerateFileSystemEntries(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumeratePaths(path, searchPattern, SearchTarget.Both, enumerationOptions);
public static string GetDirectoryRoot(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
string fullPath = Path.GetFullPath(path);
string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath));
return root;
}
internal static string InternalGetDirectoryRoot(string path)
{
if (path == null) return null;
return path.Substring(0, PathInternal.GetRootLength(path));
}
public static string GetCurrentDirectory() => Environment.CurrentDirectory;
public static void SetCurrentDirectory(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, nameof(path));
Environment.CurrentDirectory = Path.GetFullPath(path);
}
public static void Move(string sourceDirName, string destDirName)
{
if (sourceDirName == null)
throw new ArgumentNullException(nameof(sourceDirName));
if (sourceDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceDirName));
if (destDirName == null)
throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName));
string fullsourceDirName = Path.GetFullPath(sourceDirName);
string sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName);
string fulldestDirName = Path.GetFullPath(destDirName);
string destPath = EnsureTrailingDirectorySeparator(fulldestDirName);
StringComparison pathComparison = PathInternal.StringComparison;
if (string.Equals(sourcePath, destPath, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
string sourceRoot = Path.GetPathRoot(sourcePath);
string destinationRoot = Path.GetPathRoot(destPath);
if (!string.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
// Windows will throw if the source file/directory doesn't exist, we preemptively check
// to make sure our cross platform behavior matches NetFX behavior.
if (!FileSystem.DirectoryExists(fullsourceDirName) && !FileSystem.FileExists(fullsourceDirName))
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, fullsourceDirName));
if (FileSystem.DirectoryExists(fulldestDirName))
throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, fulldestDirName));
FileSystem.MoveDirectory(fullsourceDirName, fulldestDirName);
}
public static void Delete(string path)
{
string fullPath = Path.GetFullPath(path);
FileSystem.RemoveDirectory(fullPath, false);
}
public static void Delete(string path, bool recursive)
{
string fullPath = Path.GetFullPath(path);
FileSystem.RemoveDirectory(fullPath, recursive);
}
public static string[] GetLogicalDrives()
{
return FileSystem.GetLogicalDrives();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: This class will encapsulate a long and provide an
** Object representation of it.
**
**
===========================================================*/
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Int64 : IComparable, IConvertible, IFormattable, IComparable<Int64>, IEquatable<Int64>
{
private long m_value; // Do not rename (binary serialization)
public const long MaxValue = 0x7fffffffffffffffL;
public const long MinValue = unchecked((long)0x8000000000000000L);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int64, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Int64)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
long i = (long)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeInt64);
}
public int CompareTo(Int64 value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is Int64))
{
return false;
}
return m_value == ((Int64)obj).m_value;
}
[NonVersionable]
public bool Equals(Int64 obj)
{
return m_value == obj;
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode()
{
return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
}
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
}
public static long Parse(String s)
{
return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static long Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo);
}
public static long Parse(String s, IFormatProvider provider)
{
return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses a long from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
public static long Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
public static Boolean TryParse(String s, out Int64 result)
{
return Number.TryParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Int64;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return m_value;
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int64", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// 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.Versioning;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Rules for the Hijri calendar:
// - The Hijri calendar is a strictly Lunar calendar.
// - Days begin at sunset.
// - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date
// 227015 (Friday, July 16, 622 C.E. - Julian).
// - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th
// years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11).
// - There are 12 months which contain alternately 30 and 29 days.
// - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days
// in a leap year.
// - Common years have 354 days. Leap years have 355 days.
// - There are 10,631 days in a 30-year cycle.
// - The Islamic months are:
// 1. Muharram (30 days) 7. Rajab (30 days)
// 2. Safar (29 days) 8. Sha'ban (29 days)
// 3. Rabi I (30 days) 9. Ramadan (30 days)
// 4. Rabi II (29 days) 10. Shawwal (29 days)
// 5. Jumada I (30 days) 11. Dhu al-Qada (30 days)
// 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30}
//
// NOTENOTE
// The calculation of the HijriCalendar is based on the absolute date. And the
// absolute date means the number of days from January 1st, 1 A.D.
// Therefore, we do not support the days before the January 1st, 1 A.D.
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0622/07/18 9999/12/31
** Hijri 0001/01/01 9666/04/03
*/
[Serializable]
public partial class HijriCalendar : Calendar
{
public static readonly int HijriEra = 1;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int MinAdvancedHijri = -2;
internal const int MaxAdvancedHijri = 2;
internal static readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 };
private int _hijriAdvance = Int32.MinValue;
// DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3).
internal const int MaxCalendarYear = 9666;
internal const int MaxCalendarMonth = 4;
internal const int MaxCalendarDay = 3;
// Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18)
// This is the minimal Gregorian date that we support in the HijriCalendar.
internal static readonly DateTime calendarMinValue = new DateTime(622, 7, 18);
internal static readonly DateTime calendarMaxValue = DateTime.MaxValue;
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (calendarMaxValue);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.LunarCalendar;
}
}
public HijriCalendar()
{
}
internal override CalendarId ID
{
get
{
return CalendarId.HIJRI;
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// the year before the 1st year of the cycle would have been the 30th year
// of the previous cycle which is not a leap year. Common years have 354 days.
return 354;
}
}
/*=================================GetAbsoluteDateHijri==========================
**Action: Gets the Absolute date for the given Hijri date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
private long GetAbsoluteDateHijri(int y, int m, int d)
{
return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m - 1] + d - 1 - HijriAdjustment);
}
/*=================================DaysUpToHijriYear==========================
**Action: Gets the total number of days (absolute date) up to the given Hijri Year.
** The absolute date means the number of days from January 1st, 1 A.D.
**Returns: Gets the total number of days (absolute date) up to the given Hijri Year.
**Arguments: HijriYear year value in Hijri calendar.
**Exceptions: None
**Notes:
============================================================================*/
private long DaysUpToHijriYear(int HijriYear)
{
long NumDays; // number of absolute days
int NumYear30; // number of years up to current 30 year cycle
int NumYearsLeft; // number of years into 30 year cycle
//
// Compute the number of years up to the current 30 year cycle.
//
NumYear30 = ((HijriYear - 1) / 30) * 30;
//
// Compute the number of years left. This is the number of years
// into the 30 year cycle for the given year.
//
NumYearsLeft = HijriYear - NumYear30 - 1;
//
// Compute the number of absolute days up to the given year.
//
NumDays = ((NumYear30 * 10631L) / 30L) + 227013L;
while (NumYearsLeft > 0)
{
// Common year is 354 days, and leap year is 355 days.
NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1 : 0);
NumYearsLeft--;
}
//
// Return the number of absolute days.
//
return (NumDays);
}
public int HijriAdjustment
{
get
{
if (_hijriAdvance == Int32.MinValue)
{
// Never been set before. Use the system value from registry.
_hijriAdvance = GetHijriDateAdjustment();
}
return (_hijriAdvance);
}
set
{
// NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good.
if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
{
throw new ArgumentOutOfRangeException(
"HijriAdjustment",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
MinAdvancedHijri,
MaxAdvancedHijri));
}
Contract.EndContractBlock();
VerifyWritable();
_hijriAdvance = value;
}
}
internal static void CheckTicksRange(long ticks)
{
if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
calendarMinValue,
calendarMaxValue));
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != HijriEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal static void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
}
internal static void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
nameof(month),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
}
/*=================================GetDatePart==========================
**Action: Returns a given date part of this <i>DateTime</i>. This method is used
** to compute the year, day-of-year, month, or day part.
**Returns:
**Arguments:
**Exceptions: ArgumentException if part is incorrect.
**Notes:
** First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
** Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year.
** In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1).
** From here, we can get the correct Hijri year.
============================================================================*/
internal virtual int GetDatePart(long ticks, int part)
{
int HijriYear; // Hijri year
int HijriMonth; // Hijri month
int HijriDay; // Hijri day
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
//
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
//
NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
//
// See how much we need to backup or advance
//
NumDays += HijriAdjustment;
//
// Calculate the appromixate Hijri Year from this magic formula.
//
HijriYear = (int)(((NumDays - 227013) * 30) / 10631) + 1;
long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absoulte date for HijriYear
long daysOfHijriYear = GetDaysInYear(HijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
if (NumDays < daysToHijriYear)
{
daysToHijriYear -= daysOfHijriYear;
HijriYear--;
}
else if (NumDays == daysToHijriYear)
{
HijriYear--;
daysToHijriYear -= GetDaysInYear(HijriYear, CurrentEra);
}
else
{
if (NumDays > daysToHijriYear + daysOfHijriYear)
{
daysToHijriYear += daysOfHijriYear;
HijriYear++;
}
}
if (part == DatePartYear)
{
return (HijriYear);
}
//
// Calculate the Hijri Month.
//
HijriMonth = 1;
NumDays -= daysToHijriYear;
if (part == DatePartDayOfYear)
{
return ((int)NumDays);
}
while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1]))
{
HijriMonth++;
}
HijriMonth--;
if (part == DatePartMonth)
{
return (HijriMonth);
}
//
// Calculate the Hijri Day.
//
HijriDay = (int)(NumDays - HijriMonthDays[HijriMonth - 1]);
if (part == DatePartDay)
{
return (HijriDay);
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
// Get the date in Hijri calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
[Pure]
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if (month == 12)
{
// For the 12th month, leap year has 30 days, and common year has 29 days.
return (IsLeapYear(year, CurrentEra) ? 30 : 29);
}
// Other months contain 30 and 29 days alternatively. The 1st month has 30 days.
return (((month % 2) == 1) ? 30 : 29);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
// Common years have 354 days. Leap years have 355 days.
return (IsLeapYear(year, CurrentEra) ? 355 : 354);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return (HijriEra);
}
public override int[] Eras
{
get
{
return (new int[] { HijriEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(year, era);
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
return (IsLeapYear(year, era) && month == 12 && day == 30);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
return ((((year * 11) + 14) % 30) < 11);
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
long lDate = GetAbsoluteDateHijri(year, month, day);
if (lDate >= 0)
{
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(value),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return (base.ToFourDigitYear(year));
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
return (year);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2015 Tim Stair
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
namespace CardMaker.Forms
{
partial class CardMakerMDI
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.menuStripMain = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveProjectAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
this.exportProjectThroughPDFSharpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.recentProjectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.drawElementBordersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.drawSelectedElementGuidesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.drawFormattedTextWordOutlinesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.projectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearCacheToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.updateIssuesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importLayoutsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearGoogleCacheToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.layoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.reloadReferencesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.projectManagerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.colorPickerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.layoutTemplatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.illegalFilenameCharacterReplacementToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.updateGoogleCredentialsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pDFToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.samplePDFToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.drawSelectedElementRotationBoundsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuStripMain.SuspendLayout();
this.SuspendLayout();
//
// menuStripMain
//
this.menuStripMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.viewToolStripMenuItem,
this.projectToolStripMenuItem,
this.layoutToolStripMenuItem,
this.toolsToolStripMenuItem,
this.windowToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStripMain.Location = new System.Drawing.Point(0, 0);
this.menuStripMain.Name = "menuStripMain";
this.menuStripMain.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.menuStripMain.Size = new System.Drawing.Size(1088, 24);
this.menuStripMain.TabIndex = 15;
this.menuStripMain.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openProjectToolStripMenuItem,
this.saveProjectToolStripMenuItem,
this.saveProjectAsToolStripMenuItem,
this.toolStripSeparator1,
this.toolStripMenuItem3,
this.exportProjectThroughPDFSharpToolStripMenuItem,
this.toolStripMenuItem1,
this.recentProjectsToolStripMenuItem,
this.toolStripMenuItem2,
this.closeToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "&File";
this.fileToolStripMenuItem.DropDownOpening += new System.EventHandler(this.fileToolStripMenuItem_DropDownOpening);
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.newToolStripMenuItem.Text = "&New Project";
this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
//
// openProjectToolStripMenuItem
//
this.openProjectToolStripMenuItem.Name = "openProjectToolStripMenuItem";
this.openProjectToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openProjectToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.openProjectToolStripMenuItem.Text = "&Open Project...";
this.openProjectToolStripMenuItem.Click += new System.EventHandler(this.openProjectToolStripMenuItem_Click);
//
// saveProjectToolStripMenuItem
//
this.saveProjectToolStripMenuItem.Name = "saveProjectToolStripMenuItem";
this.saveProjectToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveProjectToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.saveProjectToolStripMenuItem.Text = "&Save Project...";
this.saveProjectToolStripMenuItem.Click += new System.EventHandler(this.saveProjectToolStripMenuItem_Click);
//
// saveProjectAsToolStripMenuItem
//
this.saveProjectAsToolStripMenuItem.Name = "saveProjectAsToolStripMenuItem";
this.saveProjectAsToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.saveProjectAsToolStripMenuItem.Text = "Save Project &As...";
this.saveProjectAsToolStripMenuItem.Click += new System.EventHandler(this.saveProjectAsToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(241, 6);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.E)));
this.toolStripMenuItem3.Size = new System.Drawing.Size(244, 22);
this.toolStripMenuItem3.Text = "Export Project to Images...";
this.toolStripMenuItem3.Click += new System.EventHandler(this.exportImagesToolStripMenuItem_Click);
//
// exportProjectThroughPDFSharpToolStripMenuItem
//
this.exportProjectThroughPDFSharpToolStripMenuItem.Name = "exportProjectThroughPDFSharpToolStripMenuItem";
this.exportProjectThroughPDFSharpToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.exportProjectThroughPDFSharpToolStripMenuItem.Text = "Export Project to PDF...";
this.exportProjectThroughPDFSharpToolStripMenuItem.Click += new System.EventHandler(this.exportProjectToPDFToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(241, 6);
//
// recentProjectsToolStripMenuItem
//
this.recentProjectsToolStripMenuItem.Name = "recentProjectsToolStripMenuItem";
this.recentProjectsToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.recentProjectsToolStripMenuItem.Text = "Recent Projects";
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(241, 6);
//
// closeToolStripMenuItem
//
this.closeToolStripMenuItem.Name = "closeToolStripMenuItem";
this.closeToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.closeToolStripMenuItem.Text = "Close";
this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.editToolStripMenuItem.Text = "Edit";
this.editToolStripMenuItem.DropDownOpening += new System.EventHandler(this.editToolStripMenuItem_DropDownOpening);
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.undoToolStripMenuItem.Text = "Undo";
this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click);
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.redoToolStripMenuItem.Text = "Redo";
this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.drawElementBordersToolStripMenuItem,
this.drawSelectedElementGuidesToolStripMenuItem,
this.drawSelectedElementRotationBoundsToolStripMenuItem,
this.drawFormattedTextWordOutlinesToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(41, 20);
this.viewToolStripMenuItem.Text = "&View";
//
// drawElementBordersToolStripMenuItem
//
this.drawElementBordersToolStripMenuItem.Checked = true;
this.drawElementBordersToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.drawElementBordersToolStripMenuItem.Name = "drawElementBordersToolStripMenuItem";
this.drawElementBordersToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F4;
this.drawElementBordersToolStripMenuItem.Size = new System.Drawing.Size(290, 22);
this.drawElementBordersToolStripMenuItem.Text = "&Draw Element Borders";
this.drawElementBordersToolStripMenuItem.Click += new System.EventHandler(this.drawElementBordersToolStripMenuItem_Click);
//
// drawSelectedElementGuidesToolStripMenuItem
//
this.drawSelectedElementGuidesToolStripMenuItem.Checked = true;
this.drawSelectedElementGuidesToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.drawSelectedElementGuidesToolStripMenuItem.Name = "drawSelectedElementGuidesToolStripMenuItem";
this.drawSelectedElementGuidesToolStripMenuItem.Size = new System.Drawing.Size(290, 22);
this.drawSelectedElementGuidesToolStripMenuItem.Text = "Draw Selected Element Guides";
this.drawSelectedElementGuidesToolStripMenuItem.Click += new System.EventHandler(this.drawSelectedElementGuidesToolStripMenuItem_Click);
//
// drawFormattedTextWordOutlinesToolStripMenuItem
//
this.drawFormattedTextWordOutlinesToolStripMenuItem.Name = "drawFormattedTextWordOutlinesToolStripMenuItem";
this.drawFormattedTextWordOutlinesToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F4)));
this.drawFormattedTextWordOutlinesToolStripMenuItem.Size = new System.Drawing.Size(290, 22);
this.drawFormattedTextWordOutlinesToolStripMenuItem.Text = "Draw Formatted Text Word Borders";
this.drawFormattedTextWordOutlinesToolStripMenuItem.Click += new System.EventHandler(this.drawFormattedTextWordBordersToolStripMenuItem_Click);
//
// projectToolStripMenuItem
//
this.projectToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.clearCacheToolStripMenuItem,
this.updateIssuesToolStripMenuItem,
this.importLayoutsToolStripMenuItem,
this.clearGoogleCacheToolStripMenuItem});
this.projectToolStripMenuItem.Name = "projectToolStripMenuItem";
this.projectToolStripMenuItem.Size = new System.Drawing.Size(53, 20);
this.projectToolStripMenuItem.Text = "&Project";
//
// clearCacheToolStripMenuItem
//
this.clearCacheToolStripMenuItem.Name = "clearCacheToolStripMenuItem";
this.clearCacheToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F6;
this.clearCacheToolStripMenuItem.Size = new System.Drawing.Size(221, 22);
this.clearCacheToolStripMenuItem.Text = "&Clear Image Cache";
this.clearCacheToolStripMenuItem.Click += new System.EventHandler(this.clearCacheToolStripMenuItem_Click);
//
// updateIssuesToolStripMenuItem
//
this.updateIssuesToolStripMenuItem.Name = "updateIssuesToolStripMenuItem";
this.updateIssuesToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F8;
this.updateIssuesToolStripMenuItem.Size = new System.Drawing.Size(221, 22);
this.updateIssuesToolStripMenuItem.Text = "&Update Known Issues...";
this.updateIssuesToolStripMenuItem.Click += new System.EventHandler(this.updateIssuesToolStripMenuItem_Click);
//
// importLayoutsToolStripMenuItem
//
this.importLayoutsToolStripMenuItem.Name = "importLayoutsToolStripMenuItem";
this.importLayoutsToolStripMenuItem.Size = new System.Drawing.Size(221, 22);
this.importLayoutsToolStripMenuItem.Text = "Import Layouts from Project...";
this.importLayoutsToolStripMenuItem.Click += new System.EventHandler(this.importLayoutsToolStripMenuItem_Click);
//
// clearGoogleCacheToolStripMenuItem
//
this.clearGoogleCacheToolStripMenuItem.Name = "clearGoogleCacheToolStripMenuItem";
this.clearGoogleCacheToolStripMenuItem.Size = new System.Drawing.Size(221, 22);
this.clearGoogleCacheToolStripMenuItem.Text = "Clear All Google Cache Entries";
this.clearGoogleCacheToolStripMenuItem.Click += new System.EventHandler(this.clearGoogleCacheToolStripMenuItem_Click);
//
// layoutToolStripMenuItem
//
this.layoutToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.reloadReferencesToolStripMenuItem});
this.layoutToolStripMenuItem.Name = "layoutToolStripMenuItem";
this.layoutToolStripMenuItem.Size = new System.Drawing.Size(52, 20);
this.layoutToolStripMenuItem.Text = "Layout";
//
// reloadReferencesToolStripMenuItem
//
this.reloadReferencesToolStripMenuItem.Name = "reloadReferencesToolStripMenuItem";
this.reloadReferencesToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F9;
this.reloadReferencesToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.reloadReferencesToolStripMenuItem.Text = "Reload References";
this.reloadReferencesToolStripMenuItem.Click += new System.EventHandler(this.reloadReferencesToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.projectManagerToolStripMenuItem,
this.colorPickerToolStripMenuItem,
this.layoutTemplatesToolStripMenuItem,
this.illegalFilenameCharacterReplacementToolStripMenuItem,
this.updateGoogleCredentialsToolStripMenuItem,
this.settingsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// projectManagerToolStripMenuItem
//
this.projectManagerToolStripMenuItem.Name = "projectManagerToolStripMenuItem";
this.projectManagerToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F7;
this.projectManagerToolStripMenuItem.Size = new System.Drawing.Size(279, 22);
this.projectManagerToolStripMenuItem.Text = "Project Manager...";
this.projectManagerToolStripMenuItem.Click += new System.EventHandler(this.projectManagerToolStripMenuItem_Click);
//
// colorPickerToolStripMenuItem
//
this.colorPickerToolStripMenuItem.Name = "colorPickerToolStripMenuItem";
this.colorPickerToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.colorPickerToolStripMenuItem.Size = new System.Drawing.Size(279, 22);
this.colorPickerToolStripMenuItem.Text = "Color Picker...";
this.colorPickerToolStripMenuItem.Click += new System.EventHandler(this.colorPickerToolStripMenuItem_Click);
//
// layoutTemplatesToolStripMenuItem
//
this.layoutTemplatesToolStripMenuItem.Name = "layoutTemplatesToolStripMenuItem";
this.layoutTemplatesToolStripMenuItem.Size = new System.Drawing.Size(279, 22);
this.layoutTemplatesToolStripMenuItem.Text = "Remove Layout Templates...";
this.layoutTemplatesToolStripMenuItem.Click += new System.EventHandler(this.removeLayoutTemplatesToolStripMenuItem_Click);
//
// illegalFilenameCharacterReplacementToolStripMenuItem
//
this.illegalFilenameCharacterReplacementToolStripMenuItem.Name = "illegalFilenameCharacterReplacementToolStripMenuItem";
this.illegalFilenameCharacterReplacementToolStripMenuItem.Size = new System.Drawing.Size(279, 22);
this.illegalFilenameCharacterReplacementToolStripMenuItem.Text = "&Illegal File Name Character Replacement...";
this.illegalFilenameCharacterReplacementToolStripMenuItem.Click += new System.EventHandler(this.illegalFilenameCharacterReplacementToolStripMenuItem_Click);
//
// updateGoogleCredentialsToolStripMenuItem
//
this.updateGoogleCredentialsToolStripMenuItem.Name = "updateGoogleCredentialsToolStripMenuItem";
this.updateGoogleCredentialsToolStripMenuItem.Size = new System.Drawing.Size(279, 22);
this.updateGoogleCredentialsToolStripMenuItem.Text = "Update Google Credentials...";
this.updateGoogleCredentialsToolStripMenuItem.Click += new System.EventHandler(this.updateGoogleCredentialsToolStripMenuItem_Click);
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(279, 22);
this.settingsToolStripMenuItem.Text = "Settings...";
this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click);
//
// windowToolStripMenuItem
//
this.windowToolStripMenuItem.Name = "windowToolStripMenuItem";
this.windowToolStripMenuItem.Size = new System.Drawing.Size(57, 20);
this.windowToolStripMenuItem.Text = "&Window";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.pDFToolStripMenuItem,
this.samplePDFToolStripMenuItem,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.helpToolStripMenuItem.Text = "Help";
//
// pDFToolStripMenuItem
//
this.pDFToolStripMenuItem.Name = "pDFToolStripMenuItem";
this.pDFToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F1;
this.pDFToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.pDFToolStripMenuItem.Text = "&Instructions (PDF)";
this.pDFToolStripMenuItem.Click += new System.EventHandler(this.pDFToolStripMenuItem_Click);
//
// samplePDFToolStripMenuItem
//
this.samplePDFToolStripMenuItem.Name = "samplePDFToolStripMenuItem";
this.samplePDFToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.samplePDFToolStripMenuItem.Text = "&Sample (PDF)";
this.samplePDFToolStripMenuItem.Click += new System.EventHandler(this.samplePDFToolStripMenuItem_Click);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.aboutToolStripMenuItem.Text = "&About";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// drawSelectedElementRotationBoundsToolStripMenuItem
//
this.drawSelectedElementRotationBoundsToolStripMenuItem.Checked = true;
this.drawSelectedElementRotationBoundsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.drawSelectedElementRotationBoundsToolStripMenuItem.Name = "drawSelectedElementRotationBoundsToolStripMenuItem";
this.drawSelectedElementRotationBoundsToolStripMenuItem.Size = new System.Drawing.Size(290, 22);
this.drawSelectedElementRotationBoundsToolStripMenuItem.Text = "Draw Selected Element Rotation Bounds";
this.drawSelectedElementRotationBoundsToolStripMenuItem.Click += new System.EventHandler(this.drawSelectedElementRotationBoundsToolStripMenuItem_Click);
//
// CardMakerMDI
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1088, 696);
this.Controls.Add(this.menuStripMain);
this.IsMdiContainer = true;
this.KeyPreview = true;
this.Name = "CardMakerMDI";
this.Text = "MDIParent1";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.CardMakerMDI_FormClosing);
this.Load += new System.EventHandler(this.CardMakerMDI_Load);
this.menuStripMain.ResumeLayout(false);
this.menuStripMain.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStripMain;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openProjectToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveProjectToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveProjectAsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem drawElementBordersToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem recentProjectsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pDFToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem samplePDFToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem projectToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearCacheToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem updateIssuesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem illegalFilenameCharacterReplacementToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem layoutTemplatesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem projectManagerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem drawFormattedTextWordOutlinesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem updateGoogleCredentialsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem colorPickerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportProjectThroughPDFSharpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importLayoutsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearGoogleCacheToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem layoutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem reloadReferencesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem drawSelectedElementGuidesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem drawSelectedElementRotationBoundsToolStripMenuItem;
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Orleans.Runtime
{
/// <summary>
/// SafeTimerBase - an internal base class for implementing sync and async timers in Orleans.
///
/// </summary>
internal class SafeTimerBase : IDisposable
{
private Timer timer;
private Func<object, Task> asynTaskCallback;
private TimerCallback syncCallbackFunc;
private TimeSpan dueTime;
private TimeSpan timerFrequency;
private bool timerStarted;
private DateTime previousTickTime;
private int totalNumTicks;
private TraceLogger logger;
internal SafeTimerBase(Func<object, Task> asynTaskCallback, object state)
{
Init(asynTaskCallback, null, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
internal SafeTimerBase(Func<object, Task> asynTaskCallback, object state, TimeSpan dueTime, TimeSpan period)
{
Init(asynTaskCallback, null, state, dueTime, period);
Start(dueTime, period);
}
internal SafeTimerBase(TimerCallback syncCallback, object state)
{
Init(null, syncCallback, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
internal SafeTimerBase(TimerCallback syncCallback, object state, TimeSpan dueTime, TimeSpan period)
{
Init(null, syncCallback, state, dueTime, period);
Start(dueTime, period);
}
public void Start(TimeSpan due, TimeSpan period)
{
if (timerStarted) throw new InvalidOperationException(String.Format("Calling start on timer {0} is not allowed, since it was already created in a started mode with specified due.", GetFullName()));
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, "Cannot use TimeSpan.Zero for timer period");
timerFrequency = period;
dueTime = due;
timerStarted = true;
previousTickTime = DateTime.UtcNow;
timer.Change(due, Constants.INFINITE_TIMESPAN);
}
private void Init(Func<object, Task> asynCallback, TimerCallback synCallback, object state, TimeSpan due, TimeSpan period)
{
if (synCallback == null && asynCallback == null) throw new ArgumentNullException("synCallback", "Cannot use null for both sync and asyncTask timer callbacks.");
int numNonNulls = (asynCallback != null ? 1 : 0) + (synCallback != null ? 1 : 0);
if (numNonNulls > 1) throw new ArgumentNullException("synCallback", "Cannot define more than one timer callbacks. Pick one.");
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, "Cannot use TimeSpan.Zero for timer period");
this.asynTaskCallback = asynCallback;
syncCallbackFunc = synCallback;
timerFrequency = period;
this.dueTime = due;
totalNumTicks = 0;
logger = TraceLogger.GetLogger(GetFullName(), TraceLogger.LoggerType.Runtime);
if (logger.IsVerbose) logger.Verbose(ErrorCode.TimerChanging, "Creating timer {0} with dueTime={1} period={2}", GetFullName(), due, period);
timer = new Timer(HandleTimerCallback, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Maybe called by finalizer thread with disposing=false. As per guidelines, in such a case do not touch other objects.
// Dispose() may be called multiple times
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
DisposeTimer();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void DisposeTimer()
{
if (timer != null)
{
try
{
var t = timer;
timer = null;
if (logger.IsVerbose) logger.Verbose(ErrorCode.TimerDisposing, "Disposing timer {0}", GetFullName());
t.Dispose();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerDisposeError,
string.Format("Ignored error disposing timer {0}", GetFullName()), exc);
}
}
}
#endregion
private string GetFullName()
{
// the type information is really useless and just too long.
string name;
if (syncCallbackFunc != null)
name = "sync";
else if (asynTaskCallback != null)
name = "asynTask";
else
throw new InvalidOperationException("invalid SafeTimerBase state");
return String.Format("{0}.SafeTimerBase", name);
}
public bool CheckTimerFreeze(DateTime lastCheckTime, Func<string> callerName)
{
return CheckTimerDelay(previousTickTime, totalNumTicks,
dueTime, timerFrequency, logger, () => String.Format("{0}.{1}", GetFullName(), callerName()), ErrorCode.Timer_SafeTimerIsNotTicking, true);
}
public static bool CheckTimerDelay(DateTime previousTickTime, int totalNumTicks,
TimeSpan dueTime, TimeSpan timerFrequency, TraceLogger logger, Func<string> getName, ErrorCode errorCode, bool freezeCheck)
{
TimeSpan timeSinceLastTick = DateTime.UtcNow - previousTickTime;
TimeSpan exceptedTimeToNexTick = totalNumTicks == 0 ? dueTime : timerFrequency;
TimeSpan exceptedTimeWithSlack;
if (exceptedTimeToNexTick >= TimeSpan.FromSeconds(6))
{
exceptedTimeWithSlack = exceptedTimeToNexTick + TimeSpan.FromSeconds(3);
}
else
{
exceptedTimeWithSlack = exceptedTimeToNexTick.Multiply(1.5);
}
if (timeSinceLastTick <= exceptedTimeWithSlack) return true;
// did not tick in the last period.
var errMsg = String.Format("{0}{1} did not fire on time. Last fired at {2}, {3} since previous fire, should have fired after {4}.",
freezeCheck ? "Watchdog Freeze Alert: " : "-", // 0
getName == null ? "" : getName(), // 1
TraceLogger.PrintDate(previousTickTime), // 2
timeSinceLastTick, // 3
exceptedTimeToNexTick); // 4
if(freezeCheck)
{
logger.Error(errorCode, errMsg);
}else
{
logger.Warn(errorCode, errMsg);
}
return false;
}
/// <summary>
/// Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.
/// </summary>
/// <param name="newDueTime">A TimeSpan representing the amount of time to delay before invoking the callback method specified when the Timer was constructed. Specify negative one (-1) milliseconds to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.</param>
/// <param name="period">The time interval between invocations of the callback method specified when the Timer was constructed. Specify negative one (-1) milliseconds to disable periodic signaling.</param>
/// <returns><c>true</c> if the timer was successfully updated; otherwise, <c>false</c>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool Change(TimeSpan newDueTime, TimeSpan period)
{
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, string.Format("Cannot use TimeSpan.Zero for timer {0} period", GetFullName()));
if (timer == null) return false;
timerFrequency = period;
if (logger.IsVerbose) logger.Verbose(ErrorCode.TimerChanging, "Changing timer {0} to dueTime={1} period={2}", GetFullName(), newDueTime, period);
try
{
// Queue first new timer tick
return timer.Change(newDueTime, Constants.INFINITE_TIMESPAN);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerChangeError,
string.Format("Error changing timer period - timer {0} not changed", GetFullName()), exc);
return false;
}
}
private void HandleTimerCallback(object state)
{
if (timer == null) return;
if (asynTaskCallback != null)
{
HandleAsyncTaskTimerCallback(state);
}
else
{
HandleSyncTimerCallback(state);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void HandleSyncTimerCallback(object state)
{
try
{
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerBeforeCallback, "About to make sync timer callback for timer {0}", GetFullName());
syncCallbackFunc(state);
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerAfterCallback, "Completed sync timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerCallbackError, string.Format("Ignored exception {0} during sync timer callback {1}", exc.Message, GetFullName()), exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
// Queue next timer callback
QueueNextTimerTick();
}
}
private async void HandleAsyncTaskTimerCallback(object state)
{
if (timer == null) return;
// There is a subtle race/issue here w.r.t unobserved promises.
// It may happen than the asyncCallbackFunc will resolve some promises on which the higher level application code is depends upon
// and this promise's await or CW will fire before the below code (after await or Finally) even runs.
// In the unit test case this may lead to the situation where unit test has finished, but p1 or p2 or p3 have not been observed yet.
// To properly fix this we may use a mutex/monitor to delay execution of asyncCallbackFunc until all CWs and Finally in the code below were scheduled
// (not until CW lambda was run, but just until CW function itself executed).
// This however will relay on scheduler executing these in separate threads to prevent deadlock, so needs to be done carefully.
// In particular, need to make sure we execute asyncCallbackFunc in another thread (so use StartNew instead of ExecuteWithSafeTryCatch).
try
{
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerBeforeCallback, "About to make async task timer callback for timer {0}", GetFullName());
await asynTaskCallback(state);
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerAfterCallback, "Completed async task timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerCallbackError, string.Format("Ignored exception {0} during async task timer callback {1}", exc.Message, GetFullName()), exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
// Queue next timer callback
QueueNextTimerTick();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void QueueNextTimerTick()
{
try
{
if (timer == null) return;
totalNumTicks++;
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerChanging, "About to QueueNextTimerTick for timer {0}", GetFullName());
if (timerFrequency == Constants.INFINITE_TIMESPAN)
{
//timer.Change(Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
DisposeTimer();
if (logger.IsVerbose) logger.Verbose(ErrorCode.TimerStopped, "Timer {0} is now stopped and disposed", GetFullName());
}
else
{
timer.Change(timerFrequency, Constants.INFINITE_TIMESPAN);
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerNextTick, "Queued next tick for timer {0} in {1}", GetFullName(), timerFrequency);
}
}
catch (ObjectDisposedException ode)
{
logger.Warn(ErrorCode.TimerDisposeError,
string.Format("Timer {0} already disposed - will not queue next timer tick", GetFullName()), ode);
}
catch (Exception exc)
{
logger.Error(ErrorCode.TimerQueueTickError,
string.Format("Error queueing next timer tick - WARNING: timer {0} is now stopped", GetFullName()), exc);
}
}
}
}
| |
using OpenSim.Framework;
/*
* 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;
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSShapeCollection : IDisposable
{
#pragma warning disable 414
private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]";
#pragma warning restore 414
private BSScene m_physicsScene { get; set; }
private Object m_collectionActivityLock = new Object();
private bool DDetail = false;
public BSShapeCollection(BSScene physScene)
{
m_physicsScene = physScene;
// Set the next to 'true' for very detailed shape update detailed logging (detailed details?)
// While detailed debugging is still active, this is better than commenting out all the
// DetailLog statements. When debugging slows down, this and the protected logging
// statements can be commented/removed.
DDetail = true;
}
public void Dispose()
{
// TODO!!!!!!!!!
}
// Callbacks called just before either the body or shape is destroyed.
// Mostly used for changing bodies out from under Linksets.
// Useful for other cases where parameters need saving.
// Passing 'null' says no callback.
public delegate void PhysicalDestructionCallback(BulletBody pBody, BulletShape pShape);
// Called to update/change the body and shape for an object.
// The object has some shape and body on it. Here we decide if that is the correct shape
// for the current state of the object (static/dynamic/...).
// If bodyCallback is not null, it is called if either the body or the shape are changed
// so dependencies (like constraints) can be removed before the physical object is dereferenced.
// Return 'true' if either the body or the shape changed.
// Called at taint-time.
public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim, PhysicalDestructionCallback bodyCallback)
{
m_physicsScene.AssertInTaintTime("BSShapeCollection.GetBodyAndShape");
bool ret = false;
// This lock could probably be pushed down lower but building shouldn't take long
lock (m_collectionActivityLock)
{
// Do we have the correct geometry for this type of object?
// Updates prim.BSShape with information/pointers to shape.
// Returns 'true' of BSShape is changed to a new shape.
bool newGeom = CreateGeom(forceRebuild, prim, bodyCallback);
// If we had to select a new shape geometry for the object,
// rebuild the body around it.
// Updates prim.BSBody with information/pointers to requested body
// Returns 'true' if BSBody was changed.
bool newBody = CreateBody((newGeom || forceRebuild), prim, m_physicsScene.World, bodyCallback);
ret = newGeom || newBody;
}
DetailLog("{0},BSShapeCollection.GetBodyAndShape,taintExit,force={1},ret={2},body={3},shape={4}",
prim.LocalID, forceRebuild, ret, prim.PhysBody, prim.PhysShape);
return ret;
}
public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim)
{
return GetBodyAndShape(forceRebuild, sim, prim, null);
}
// If the existing prim's shape is to be replaced, remove the tie to the existing shape
// before replacing it.
private void DereferenceExistingShape(BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
{
if (prim.PhysShape.HasPhysicalShape)
{
if (shapeCallback != null)
shapeCallback(prim.PhysBody, prim.PhysShape.physShapeInfo);
prim.PhysShape.Dereference(m_physicsScene);
}
prim.PhysShape = new BSShapeNull();
}
// Create the geometry information in Bullet for later use.
// The objects needs a hull if it's physical otherwise a mesh is enough.
// if 'forceRebuild' is true, the geometry is unconditionally rebuilt. For meshes and hulls,
// shared geometries will be used. If the parameters of the existing shape are the same
// as this request, the shape is not rebuilt.
// Info in prim.BSShape is updated to the new shape.
// Returns 'true' if the geometry was rebuilt.
// Called at taint-time!
public const int AvatarShapeCapsule = 0;
public const int AvatarShapeCube = 1;
public const int AvatarShapeOvoid = 2;
public const int AvatarShapeMesh = 3;
private bool CreateGeom(bool forceRebuild, BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
{
bool ret = false;
bool haveShape = false;
bool nativeShapePossible = true;
PrimitiveBaseShape pbs = prim.BaseShape;
// Kludge to create the capsule for the avatar.
// TDOD: Remove/redo this when BSShapeAvatar is working!!
BSCharacter theChar = prim as BSCharacter;
if (theChar != null)
{
DereferenceExistingShape(prim, shapeCallback);
switch (BSParam.AvatarShape)
{
case AvatarShapeCapsule:
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_CAPSULE, FixedShapeKey.KEY_CAPSULE);
ret = true;
haveShape = true;
break;
case AvatarShapeCube:
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_CAPSULE);
ret = true;
haveShape = true;
break;
case AvatarShapeOvoid:
// Saddly, Bullet doesn't scale spheres so this doesn't work as an avatar shape
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_CAPSULE);
ret = true;
haveShape = true;
break;
case AvatarShapeMesh:
break;
default:
break;
}
}
// If the prim attributes are simple, this could be a simple Bullet native shape
// Native shapes work whether to object is static or physical.
if (!haveShape
&& nativeShapePossible
&& pbs != null
&& PrimHasNoCuts(pbs)
&& ( !pbs.SculptEntry || (pbs.SculptEntry && !BSParam.ShouldMeshSculptedPrim) )
)
{
// Get the scale of any existing shape so we can see if the new shape is same native type and same size.
OMV.Vector3 scaleOfExistingShape = OMV.Vector3.Zero;
if (prim.PhysShape.HasPhysicalShape)
scaleOfExistingShape = m_physicsScene.PE.GetLocalScaling(prim.PhysShape.physShapeInfo);
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,maybeNative,force={1},primScale={2},primSize={3},primShape={4}",
prim.LocalID, forceRebuild, prim.Scale, prim.Size, prim.PhysShape.physShapeInfo.shapeType);
// It doesn't look like Bullet scales native spheres so make sure the scales are all equal
if ((pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1)
&& pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z)
{
haveShape = true;
if (forceRebuild
|| prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_SPHERE
)
{
DereferenceExistingShape(prim, shapeCallback);
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_SPHERE);
ret = true;
}
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},rebuilt={2},shape={3}",
prim.LocalID, forceRebuild, ret, prim.PhysShape);
}
// If we didn't make a sphere, maybe a box will work.
if (!haveShape && pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
{
haveShape = true;
if (forceRebuild
|| prim.Scale != scaleOfExistingShape
|| prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_BOX
)
{
DereferenceExistingShape(prim, shapeCallback);
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX);
ret = true;
}
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},rebuilt={2},shape={3}",
prim.LocalID, forceRebuild, ret, prim.PhysShape);
}
}
// If a simple shape is not happening, create a mesh and possibly a hull.
if (!haveShape && pbs != null)
{
ret = CreateGeomMeshOrHull(prim, shapeCallback);
}
return ret;
}
// return 'true' if this shape description does not include any cutting or twisting.
public static bool PrimHasNoCuts(PrimitiveBaseShape pbs)
{
return pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
&& pbs.ProfileHollow == 0
&& pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
&& pbs.PathBegin == 0 && pbs.PathEnd == 0
&& pbs.PathTaperX == 0 && pbs.PathTaperY == 0
&& pbs.PathScaleX == 100 && pbs.PathScaleY == 100
&& pbs.PathShearX == 0 && pbs.PathShearY == 0;
}
// return 'true' if the prim's shape was changed.
private bool CreateGeomMeshOrHull(BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
{
bool ret = false;
// Note that if it's a native shape, the check for physical/non-physical is not
// made. Native shapes work in either case.
if (prim.IsPhysical && BSParam.ShouldUseHullsForPhysicalObjects)
{
// Use a simple, single mesh convex hull shape if the object is simple enough
BSShape potentialHull = null;
PrimitiveBaseShape pbs = prim.BaseShape;
// Use a simple, one section convex shape for prims that are probably convex (no cuts or twists)
if (BSParam.ShouldUseSingleConvexHullForPrims
&& pbs != null
&& !pbs.SculptEntry
&& PrimHasNoCuts(pbs)
)
{
potentialHull = BSShapeConvexHull.GetReference(m_physicsScene, false /* forceRebuild */, prim);
}
// Use the GImpact shape if it is a prim that has some concaveness
if (potentialHull == null
&& BSParam.ShouldUseGImpactShapeForPrims
&& pbs != null
&& !pbs.SculptEntry
)
{
potentialHull = BSShapeGImpact.GetReference(m_physicsScene, false /* forceRebuild */, prim);
}
// If not any of the simple cases, just make a hull
if (potentialHull == null)
{
potentialHull = BSShapeHull.GetReference(m_physicsScene, false /*forceRebuild*/, prim);
}
// If the current shape is not what is on the prim at the moment, time to change.
if (!prim.PhysShape.HasPhysicalShape
|| potentialHull.ShapeType != prim.PhysShape.ShapeType
|| potentialHull.physShapeInfo.shapeKey != prim.PhysShape.physShapeInfo.shapeKey)
{
DereferenceExistingShape(prim, shapeCallback);
prim.PhysShape = potentialHull;
ret = true;
}
else
{
// The current shape on the prim is the correct one. We don't need the potential reference.
potentialHull.Dereference(m_physicsScene);
}
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1}", prim.LocalID, prim.PhysShape);
}
else
{
// Non-physical objects should be just meshes.
BSShape potentialMesh = BSShapeMesh.GetReference(m_physicsScene, false /*forceRebuild*/, prim);
// If the current shape is not what is on the prim at the moment, time to change.
if (!prim.PhysShape.HasPhysicalShape
|| potentialMesh.ShapeType != prim.PhysShape.ShapeType
|| potentialMesh.physShapeInfo.shapeKey != prim.PhysShape.physShapeInfo.shapeKey)
{
DereferenceExistingShape(prim, shapeCallback);
prim.PhysShape = potentialMesh;
ret = true;
}
else
{
// We don't need this reference to the mesh that is already being using.
potentialMesh.Dereference(m_physicsScene);
}
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1}", prim.LocalID, prim.PhysShape);
}
return ret;
}
// Track another user of a body.
// We presume the caller has allocated the body.
// Bodies only have one user so the body is just put into the world if not already there.
private void ReferenceBody(BulletBody body)
{
lock (m_collectionActivityLock)
{
if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,body={1}", body.ID, body);
if (!m_physicsScene.PE.IsInWorld(m_physicsScene.World, body))
{
m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, body);
if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", body.ID, body);
}
}
}
// Release the usage of a body.
// Called when releasing use of a BSBody. BSShape is handled separately.
// Called in taint time.
public void DereferenceBody(BulletBody body, PhysicalDestructionCallback bodyCallback )
{
if (!body.HasPhysicalBody)
return;
m_physicsScene.AssertInTaintTime("BSShapeCollection.DereferenceBody");
lock (m_collectionActivityLock)
{
if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody,body={1}", body.ID, body);
// If the caller needs to know the old body is going away, pass the event up.
if (bodyCallback != null)
bodyCallback(body, null);
// Removing an object not in the world is a NOOP
m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, body);
// Zero any reference to the shape so it is not freed when the body is deleted.
m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, body, null);
m_physicsScene.PE.DestroyObject(m_physicsScene.World, body);
}
}
// Create a body object in Bullet.
// Updates prim.BSBody with the information about the new body if one is created.
// Returns 'true' if an object was actually created.
// Called at taint-time.
private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletWorld sim, PhysicalDestructionCallback bodyCallback)
{
bool ret = false;
// the mesh, hull or native shape must have already been created in Bullet
bool mustRebuild = !prim.PhysBody.HasPhysicalBody;
// If there is an existing body, verify it's of an acceptable type.
// If not a solid object, body is a GhostObject. Otherwise a RigidBody.
if (!mustRebuild)
{
CollisionObjectTypes bodyType = (CollisionObjectTypes)m_physicsScene.PE.GetBodyType(prim.PhysBody);
if (prim.IsSolid && bodyType != CollisionObjectTypes.CO_RIGID_BODY
|| !prim.IsSolid && bodyType != CollisionObjectTypes.CO_GHOST_OBJECT)
{
// If the collisionObject is not the correct type for solidness, rebuild what's there
mustRebuild = true;
if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,forceRebuildBecauseChangingBodyType,bodyType={1}", prim.LocalID, bodyType);
}
}
if (mustRebuild || forceRebuild)
{
// Free any old body
DereferenceBody(prim.PhysBody, bodyCallback);
BulletBody aBody;
if (prim.IsSolid)
{
aBody = m_physicsScene.PE.CreateBodyFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation);
if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,rigid,body={1}", prim.LocalID, aBody);
}
else
{
aBody = m_physicsScene.PE.CreateGhostFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation);
if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,ghost,body={1}", prim.LocalID, aBody);
}
ReferenceBody(aBody);
prim.PhysBody = aBody;
ret = true;
}
return ret;
}
private void DetailLog(string msg, params Object[] args)
{
if (m_physicsScene.PhysicsLogging.Enabled)
m_physicsScene.DetailLog(msg, args);
}
}
}
| |
# CS_ARCH_PPC, CS_MODE_BIG_ENDIAN, CS_OPT_SYNTAX_NOREGNAME
0x4d,0x82,0x00,0x20 = beqlr 0
0x4d,0x86,0x00,0x20 = beqlr 1
0x4d,0x8a,0x00,0x20 = beqlr 2
0x4d,0x8e,0x00,0x20 = beqlr 3
0x4d,0x92,0x00,0x20 = beqlr 4
0x4d,0x96,0x00,0x20 = beqlr 5
0x4d,0x9a,0x00,0x20 = beqlr 6
0x4d,0x9e,0x00,0x20 = beqlr 7
0x4d,0x80,0x00,0x20 = bclr 12, 0, 0
0x4d,0x81,0x00,0x20 = bclr 12, 1, 0
0x4d,0x82,0x00,0x20 = bclr 12, 2, 0
0x4d,0x83,0x00,0x20 = bclr 12, 3, 0
0x4d,0x83,0x00,0x20 = bclr 12, 3, 0
0x4d,0x84,0x00,0x20 = bclr 12, 4, 0
0x4d,0x85,0x00,0x20 = bclr 12, 5, 0
0x4d,0x86,0x00,0x20 = bclr 12, 6, 0
0x4d,0x87,0x00,0x20 = bclr 12, 7, 0
0x4d,0x87,0x00,0x20 = bclr 12, 7, 0
0x4d,0x88,0x00,0x20 = bclr 12, 8, 0
0x4d,0x89,0x00,0x20 = bclr 12, 9, 0
0x4d,0x8a,0x00,0x20 = bclr 12, 10, 0
0x4d,0x8b,0x00,0x20 = bclr 12, 11, 0
0x4d,0x8b,0x00,0x20 = bclr 12, 11, 0
0x4d,0x8c,0x00,0x20 = bclr 12, 12, 0
0x4d,0x8d,0x00,0x20 = bclr 12, 13, 0
0x4d,0x8e,0x00,0x20 = bclr 12, 14, 0
0x4d,0x8f,0x00,0x20 = bclr 12, 15, 0
0x4d,0x8f,0x00,0x20 = bclr 12, 15, 0
0x4d,0x90,0x00,0x20 = bclr 12, 16, 0
0x4d,0x91,0x00,0x20 = bclr 12, 17, 0
0x4d,0x92,0x00,0x20 = bclr 12, 18, 0
0x4d,0x93,0x00,0x20 = bclr 12, 19, 0
0x4d,0x93,0x00,0x20 = bclr 12, 19, 0
0x4d,0x94,0x00,0x20 = bclr 12, 20, 0
0x4d,0x95,0x00,0x20 = bclr 12, 21, 0
0x4d,0x96,0x00,0x20 = bclr 12, 22, 0
0x4d,0x97,0x00,0x20 = bclr 12, 23, 0
0x4d,0x97,0x00,0x20 = bclr 12, 23, 0
0x4d,0x98,0x00,0x20 = bclr 12, 24, 0
0x4d,0x99,0x00,0x20 = bclr 12, 25, 0
0x4d,0x9a,0x00,0x20 = bclr 12, 26, 0
0x4d,0x9b,0x00,0x20 = bclr 12, 27, 0
0x4d,0x9b,0x00,0x20 = bclr 12, 27, 0
0x4d,0x9c,0x00,0x20 = bclr 12, 28, 0
0x4d,0x9d,0x00,0x20 = bclr 12, 29, 0
0x4d,0x9e,0x00,0x20 = bclr 12, 30, 0
0x4d,0x9f,0x00,0x20 = bclr 12, 31, 0
0x4d,0x9f,0x00,0x20 = bclr 12, 31, 0
0x4e,0x80,0x00,0x20 = blr
0x4e,0x80,0x04,0x20 = bctr
0x4e,0x80,0x00,0x21 = blrl
0x4e,0x80,0x04,0x21 = bctrl
0x4d,0x82,0x00,0x20 = bclr 12, 2, 0
0x4d,0x82,0x04,0x20 = bcctr 12, 2, 0
0x4d,0x82,0x00,0x21 = bclrl 12, 2, 0
0x4d,0x82,0x04,0x21 = bcctrl 12, 2, 0
0x4d,0xe2,0x00,0x20 = bclr 15, 2, 0
0x4d,0xe2,0x04,0x20 = bcctr 15, 2, 0
0x4d,0xe2,0x00,0x21 = bclrl 15, 2, 0
0x4d,0xe2,0x04,0x21 = bcctrl 15, 2, 0
0x4d,0xc2,0x00,0x20 = bclr 14, 2, 0
0x4d,0xc2,0x04,0x20 = bcctr 14, 2, 0
0x4d,0xc2,0x00,0x21 = bclrl 14, 2, 0
0x4d,0xc2,0x04,0x21 = bcctrl 14, 2, 0
0x4c,0x82,0x00,0x20 = bclr 4, 2, 0
0x4c,0x82,0x04,0x20 = bcctr 4, 2, 0
0x4c,0x82,0x00,0x21 = bclrl 4, 2, 0
0x4c,0x82,0x04,0x21 = bcctrl 4, 2, 0
0x4c,0xe2,0x00,0x20 = bclr 7, 2, 0
0x4c,0xe2,0x04,0x20 = bcctr 7, 2, 0
0x4c,0xe2,0x00,0x21 = bclrl 7, 2, 0
0x4c,0xe2,0x04,0x21 = bcctrl 7, 2, 0
0x4c,0xc2,0x00,0x20 = bclr 6, 2, 0
0x4c,0xc2,0x04,0x20 = bcctr 6, 2, 0
0x4c,0xc2,0x00,0x21 = bclrl 6, 2, 0
0x4c,0xc2,0x04,0x21 = bcctrl 6, 2, 0
0x4e,0x00,0x00,0x20 = bdnzlr
0x4e,0x00,0x00,0x21 = bdnzlrl
0x4f,0x20,0x00,0x20 = bdnzlr+
0x4f,0x20,0x00,0x21 = bdnzlrl+
0x4f,0x00,0x00,0x20 = bdnzlr-
0x4f,0x00,0x00,0x21 = bdnzlrl-
0x4d,0x02,0x00,0x20 = bclr 8, 2, 0
0x4d,0x02,0x00,0x21 = bclrl 8, 2, 0
0x4c,0x02,0x00,0x20 = bclr 0, 2, 0
0x4c,0x02,0x00,0x21 = bclrl 0, 2, 0
0x4e,0x40,0x00,0x20 = bdzlr
0x4e,0x40,0x00,0x21 = bdzlrl
0x4f,0x60,0x00,0x20 = bdzlr+
0x4f,0x60,0x00,0x21 = bdzlrl+
0x4f,0x40,0x00,0x20 = bdzlr-
0x4f,0x40,0x00,0x21 = bdzlrl-
0x4d,0x42,0x00,0x20 = bclr 10, 2, 0
0x4d,0x42,0x00,0x21 = bclrl 10, 2, 0
0x4c,0x42,0x00,0x20 = bclr 2, 2, 0
0x4c,0x42,0x00,0x21 = bclrl 2, 2, 0
0x4d,0x88,0x00,0x20 = bltlr 2
0x4d,0x80,0x00,0x20 = bltlr 0
0x4d,0x88,0x04,0x20 = bltctr 2
0x4d,0x80,0x04,0x20 = bltctr 0
0x4d,0x88,0x00,0x21 = bltlrl 2
0x4d,0x80,0x00,0x21 = bltlrl 0
0x4d,0x88,0x04,0x21 = bltctrl 2
0x4d,0x80,0x04,0x21 = bltctrl 0
0x4d,0xe8,0x00,0x20 = bltlr+ 2
0x4d,0xe0,0x00,0x20 = bltlr+ 0
0x4d,0xe8,0x04,0x20 = bltctr+ 2
0x4d,0xe0,0x04,0x20 = bltctr+ 0
0x4d,0xe8,0x00,0x21 = bltlrl+ 2
0x4d,0xe0,0x00,0x21 = bltlrl+ 0
0x4d,0xe8,0x04,0x21 = bltctrl+ 2
0x4d,0xe0,0x04,0x21 = bltctrl+ 0
0x4d,0xc8,0x00,0x20 = bltlr- 2
0x4d,0xc0,0x00,0x20 = bltlr- 0
0x4d,0xc8,0x04,0x20 = bltctr- 2
0x4d,0xc0,0x04,0x20 = bltctr- 0
0x4d,0xc8,0x00,0x21 = bltlrl- 2
0x4d,0xc0,0x00,0x21 = bltlrl- 0
0x4d,0xc8,0x04,0x21 = bltctrl- 2
0x4d,0xc0,0x04,0x21 = bltctrl- 0
0x4c,0x89,0x00,0x20 = blelr 2
0x4c,0x81,0x00,0x20 = blelr 0
0x4c,0x89,0x04,0x20 = blectr 2
0x4c,0x81,0x04,0x20 = blectr 0
0x4c,0x89,0x00,0x21 = blelrl 2
0x4c,0x81,0x00,0x21 = blelrl 0
0x4c,0x89,0x04,0x21 = blectrl 2
0x4c,0x81,0x04,0x21 = blectrl 0
0x4c,0xe9,0x00,0x20 = blelr+ 2
0x4c,0xe1,0x00,0x20 = blelr+ 0
0x4c,0xe9,0x04,0x20 = blectr+ 2
0x4c,0xe1,0x04,0x20 = blectr+ 0
0x4c,0xe9,0x00,0x21 = blelrl+ 2
0x4c,0xe1,0x00,0x21 = blelrl+ 0
0x4c,0xe9,0x04,0x21 = blectrl+ 2
0x4c,0xe1,0x04,0x21 = blectrl+ 0
0x4c,0xc9,0x00,0x20 = blelr- 2
0x4c,0xc1,0x00,0x20 = blelr- 0
0x4c,0xc9,0x04,0x20 = blectr- 2
0x4c,0xc1,0x04,0x20 = blectr- 0
0x4c,0xc9,0x00,0x21 = blelrl- 2
0x4c,0xc1,0x00,0x21 = blelrl- 0
0x4c,0xc9,0x04,0x21 = blectrl- 2
0x4c,0xc1,0x04,0x21 = blectrl- 0
0x4d,0x8a,0x00,0x20 = beqlr 2
0x4d,0x82,0x00,0x20 = beqlr 0
0x4d,0x8a,0x04,0x20 = beqctr 2
0x4d,0x82,0x04,0x20 = beqctr 0
0x4d,0x8a,0x00,0x21 = beqlrl 2
0x4d,0x82,0x00,0x21 = beqlrl 0
0x4d,0x8a,0x04,0x21 = beqctrl 2
0x4d,0x82,0x04,0x21 = beqctrl 0
0x4d,0xea,0x00,0x20 = beqlr+ 2
0x4d,0xe2,0x00,0x20 = beqlr+ 0
0x4d,0xea,0x04,0x20 = beqctr+ 2
0x4d,0xe2,0x04,0x20 = beqctr+ 0
0x4d,0xea,0x00,0x21 = beqlrl+ 2
0x4d,0xe2,0x00,0x21 = beqlrl+ 0
0x4d,0xea,0x04,0x21 = beqctrl+ 2
0x4d,0xe2,0x04,0x21 = beqctrl+ 0
0x4d,0xca,0x00,0x20 = beqlr- 2
0x4d,0xc2,0x00,0x20 = beqlr- 0
0x4d,0xca,0x04,0x20 = beqctr- 2
0x4d,0xc2,0x04,0x20 = beqctr- 0
0x4d,0xca,0x00,0x21 = beqlrl- 2
0x4d,0xc2,0x00,0x21 = beqlrl- 0
0x4d,0xca,0x04,0x21 = beqctrl- 2
0x4d,0xc2,0x04,0x21 = beqctrl- 0
0x4c,0x88,0x00,0x20 = bgelr 2
0x4c,0x80,0x00,0x20 = bgelr 0
0x4c,0x88,0x04,0x20 = bgectr 2
0x4c,0x80,0x04,0x20 = bgectr 0
0x4c,0x88,0x00,0x21 = bgelrl 2
0x4c,0x80,0x00,0x21 = bgelrl 0
0x4c,0x88,0x04,0x21 = bgectrl 2
0x4c,0x80,0x04,0x21 = bgectrl 0
0x4c,0xe8,0x00,0x20 = bgelr+ 2
0x4c,0xe0,0x00,0x20 = bgelr+ 0
0x4c,0xe8,0x04,0x20 = bgectr+ 2
0x4c,0xe0,0x04,0x20 = bgectr+ 0
0x4c,0xe8,0x00,0x21 = bgelrl+ 2
0x4c,0xe0,0x00,0x21 = bgelrl+ 0
0x4c,0xe8,0x04,0x21 = bgectrl+ 2
0x4c,0xe0,0x04,0x21 = bgectrl+ 0
0x4c,0xc8,0x00,0x20 = bgelr- 2
0x4c,0xc0,0x00,0x20 = bgelr- 0
0x4c,0xc8,0x04,0x20 = bgectr- 2
0x4c,0xc0,0x04,0x20 = bgectr- 0
0x4c,0xc8,0x00,0x21 = bgelrl- 2
0x4c,0xc0,0x00,0x21 = bgelrl- 0
0x4c,0xc8,0x04,0x21 = bgectrl- 2
0x4c,0xc0,0x04,0x21 = bgectrl- 0
0x4d,0x89,0x00,0x20 = bgtlr 2
0x4d,0x81,0x00,0x20 = bgtlr 0
0x4d,0x89,0x04,0x20 = bgtctr 2
0x4d,0x81,0x04,0x20 = bgtctr 0
0x4d,0x89,0x00,0x21 = bgtlrl 2
0x4d,0x81,0x00,0x21 = bgtlrl 0
0x4d,0x89,0x04,0x21 = bgtctrl 2
0x4d,0x81,0x04,0x21 = bgtctrl 0
0x4d,0xe9,0x00,0x20 = bgtlr+ 2
0x4d,0xe1,0x00,0x20 = bgtlr+ 0
0x4d,0xe9,0x04,0x20 = bgtctr+ 2
0x4d,0xe1,0x04,0x20 = bgtctr+ 0
0x4d,0xe9,0x00,0x21 = bgtlrl+ 2
0x4d,0xe1,0x00,0x21 = bgtlrl+ 0
0x4d,0xe9,0x04,0x21 = bgtctrl+ 2
0x4d,0xe1,0x04,0x21 = bgtctrl+ 0
0x4d,0xc9,0x00,0x20 = bgtlr- 2
0x4d,0xc1,0x00,0x20 = bgtlr- 0
0x4d,0xc9,0x04,0x20 = bgtctr- 2
0x4d,0xc1,0x04,0x20 = bgtctr- 0
0x4d,0xc9,0x00,0x21 = bgtlrl- 2
0x4d,0xc1,0x00,0x21 = bgtlrl- 0
0x4d,0xc9,0x04,0x21 = bgtctrl- 2
0x4d,0xc1,0x04,0x21 = bgtctrl- 0
0x4c,0x88,0x00,0x20 = bgelr 2
0x4c,0x80,0x00,0x20 = bgelr 0
0x4c,0x88,0x04,0x20 = bgectr 2
0x4c,0x80,0x04,0x20 = bgectr 0
0x4c,0x88,0x00,0x21 = bgelrl 2
0x4c,0x80,0x00,0x21 = bgelrl 0
0x4c,0x88,0x04,0x21 = bgectrl 2
0x4c,0x80,0x04,0x21 = bgectrl 0
0x4c,0xe8,0x00,0x20 = bgelr+ 2
0x4c,0xe0,0x00,0x20 = bgelr+ 0
0x4c,0xe8,0x04,0x20 = bgectr+ 2
0x4c,0xe0,0x04,0x20 = bgectr+ 0
0x4c,0xe8,0x00,0x21 = bgelrl+ 2
0x4c,0xe0,0x00,0x21 = bgelrl+ 0
0x4c,0xe8,0x04,0x21 = bgectrl+ 2
0x4c,0xe0,0x04,0x21 = bgectrl+ 0
0x4c,0xc8,0x00,0x20 = bgelr- 2
0x4c,0xc0,0x00,0x20 = bgelr- 0
0x4c,0xc8,0x04,0x20 = bgectr- 2
0x4c,0xc0,0x04,0x20 = bgectr- 0
0x4c,0xc8,0x00,0x21 = bgelrl- 2
0x4c,0xc0,0x00,0x21 = bgelrl- 0
0x4c,0xc8,0x04,0x21 = bgectrl- 2
0x4c,0xc0,0x04,0x21 = bgectrl- 0
0x4c,0x8a,0x00,0x20 = bnelr 2
0x4c,0x82,0x00,0x20 = bnelr 0
0x4c,0x8a,0x04,0x20 = bnectr 2
0x4c,0x82,0x04,0x20 = bnectr 0
0x4c,0x8a,0x00,0x21 = bnelrl 2
0x4c,0x82,0x00,0x21 = bnelrl 0
0x4c,0x8a,0x04,0x21 = bnectrl 2
0x4c,0x82,0x04,0x21 = bnectrl 0
0x4c,0xea,0x00,0x20 = bnelr+ 2
0x4c,0xe2,0x00,0x20 = bnelr+ 0
0x4c,0xea,0x04,0x20 = bnectr+ 2
0x4c,0xe2,0x04,0x20 = bnectr+ 0
0x4c,0xea,0x00,0x21 = bnelrl+ 2
0x4c,0xe2,0x00,0x21 = bnelrl+ 0
0x4c,0xea,0x04,0x21 = bnectrl+ 2
0x4c,0xe2,0x04,0x21 = bnectrl+ 0
0x4c,0xca,0x00,0x20 = bnelr- 2
0x4c,0xc2,0x00,0x20 = bnelr- 0
0x4c,0xca,0x04,0x20 = bnectr- 2
0x4c,0xc2,0x04,0x20 = bnectr- 0
0x4c,0xca,0x00,0x21 = bnelrl- 2
0x4c,0xc2,0x00,0x21 = bnelrl- 0
0x4c,0xca,0x04,0x21 = bnectrl- 2
0x4c,0xc2,0x04,0x21 = bnectrl- 0
0x4c,0x89,0x00,0x20 = blelr 2
0x4c,0x81,0x00,0x20 = blelr 0
0x4c,0x89,0x04,0x20 = blectr 2
0x4c,0x81,0x04,0x20 = blectr 0
0x4c,0x89,0x00,0x21 = blelrl 2
0x4c,0x81,0x00,0x21 = blelrl 0
0x4c,0x89,0x04,0x21 = blectrl 2
0x4c,0x81,0x04,0x21 = blectrl 0
0x4c,0xe9,0x00,0x20 = blelr+ 2
0x4c,0xe1,0x00,0x20 = blelr+ 0
0x4c,0xe9,0x04,0x20 = blectr+ 2
0x4c,0xe1,0x04,0x20 = blectr+ 0
0x4c,0xe9,0x00,0x21 = blelrl+ 2
0x4c,0xe1,0x00,0x21 = blelrl+ 0
0x4c,0xe9,0x04,0x21 = blectrl+ 2
0x4c,0xe1,0x04,0x21 = blectrl+ 0
0x4c,0xc9,0x00,0x20 = blelr- 2
0x4c,0xc1,0x00,0x20 = blelr- 0
0x4c,0xc9,0x04,0x20 = blectr- 2
0x4c,0xc1,0x04,0x20 = blectr- 0
0x4c,0xc9,0x00,0x21 = blelrl- 2
0x4c,0xc1,0x00,0x21 = blelrl- 0
0x4c,0xc9,0x04,0x21 = blectrl- 2
0x4c,0xc1,0x04,0x21 = blectrl- 0
0x4d,0x8b,0x00,0x20 = bunlr 2
0x4d,0x83,0x00,0x20 = bunlr 0
0x4d,0x8b,0x04,0x20 = bunctr 2
0x4d,0x83,0x04,0x20 = bunctr 0
0x4d,0x8b,0x00,0x21 = bunlrl 2
0x4d,0x83,0x00,0x21 = bunlrl 0
0x4d,0x8b,0x04,0x21 = bunctrl 2
0x4d,0x83,0x04,0x21 = bunctrl 0
0x4d,0xeb,0x00,0x20 = bunlr+ 2
0x4d,0xe3,0x00,0x20 = bunlr+ 0
0x4d,0xeb,0x04,0x20 = bunctr+ 2
0x4d,0xe3,0x04,0x20 = bunctr+ 0
0x4d,0xeb,0x00,0x21 = bunlrl+ 2
0x4d,0xe3,0x00,0x21 = bunlrl+ 0
0x4d,0xeb,0x04,0x21 = bunctrl+ 2
0x4d,0xe3,0x04,0x21 = bunctrl+ 0
0x4d,0xcb,0x00,0x20 = bunlr- 2
0x4d,0xc3,0x00,0x20 = bunlr- 0
0x4d,0xcb,0x04,0x20 = bunctr- 2
0x4d,0xc3,0x04,0x20 = bunctr- 0
0x4d,0xcb,0x00,0x21 = bunlrl- 2
0x4d,0xc3,0x00,0x21 = bunlrl- 0
0x4d,0xcb,0x04,0x21 = bunctrl- 2
0x4d,0xc3,0x04,0x21 = bunctrl- 0
0x4c,0x8b,0x00,0x20 = bnulr 2
0x4c,0x83,0x00,0x20 = bnulr 0
0x4c,0x8b,0x04,0x20 = bnuctr 2
0x4c,0x83,0x04,0x20 = bnuctr 0
0x4c,0x8b,0x00,0x21 = bnulrl 2
0x4c,0x83,0x00,0x21 = bnulrl 0
0x4c,0x8b,0x04,0x21 = bnuctrl 2
0x4c,0x83,0x04,0x21 = bnuctrl 0
0x4c,0xeb,0x00,0x20 = bnulr+ 2
0x4c,0xe3,0x00,0x20 = bnulr+ 0
0x4c,0xeb,0x04,0x20 = bnuctr+ 2
0x4c,0xe3,0x04,0x20 = bnuctr+ 0
0x4c,0xeb,0x00,0x21 = bnulrl+ 2
0x4c,0xe3,0x00,0x21 = bnulrl+ 0
0x4c,0xeb,0x04,0x21 = bnuctrl+ 2
0x4c,0xe3,0x04,0x21 = bnuctrl+ 0
0x4c,0xcb,0x00,0x20 = bnulr- 2
0x4c,0xc3,0x00,0x20 = bnulr- 0
0x4c,0xcb,0x04,0x20 = bnuctr- 2
0x4c,0xc3,0x04,0x20 = bnuctr- 0
0x4c,0xcb,0x00,0x21 = bnulrl- 2
0x4c,0xc3,0x00,0x21 = bnulrl- 0
0x4c,0xcb,0x04,0x21 = bnuctrl- 2
0x4c,0xc3,0x04,0x21 = bnuctrl- 0
0x4d,0x8b,0x00,0x20 = bunlr 2
0x4d,0x83,0x00,0x20 = bunlr 0
0x4d,0x8b,0x04,0x20 = bunctr 2
0x4d,0x83,0x04,0x20 = bunctr 0
0x4d,0x8b,0x00,0x21 = bunlrl 2
0x4d,0x83,0x00,0x21 = bunlrl 0
0x4d,0x8b,0x04,0x21 = bunctrl 2
0x4d,0x83,0x04,0x21 = bunctrl 0
0x4d,0xeb,0x00,0x20 = bunlr+ 2
0x4d,0xe3,0x00,0x20 = bunlr+ 0
0x4d,0xeb,0x04,0x20 = bunctr+ 2
0x4d,0xe3,0x04,0x20 = bunctr+ 0
0x4d,0xeb,0x00,0x21 = bunlrl+ 2
0x4d,0xe3,0x00,0x21 = bunlrl+ 0
0x4d,0xeb,0x04,0x21 = bunctrl+ 2
0x4d,0xe3,0x04,0x21 = bunctrl+ 0
0x4d,0xcb,0x00,0x20 = bunlr- 2
0x4d,0xc3,0x00,0x20 = bunlr- 0
0x4d,0xcb,0x04,0x20 = bunctr- 2
0x4d,0xc3,0x04,0x20 = bunctr- 0
0x4d,0xcb,0x00,0x21 = bunlrl- 2
0x4d,0xc3,0x00,0x21 = bunlrl- 0
0x4d,0xcb,0x04,0x21 = bunctrl- 2
0x4d,0xc3,0x04,0x21 = bunctrl- 0
0x4c,0x8b,0x00,0x20 = bnulr 2
0x4c,0x83,0x00,0x20 = bnulr 0
0x4c,0x8b,0x04,0x20 = bnuctr 2
0x4c,0x83,0x04,0x20 = bnuctr 0
0x4c,0x8b,0x00,0x21 = bnulrl 2
0x4c,0x83,0x00,0x21 = bnulrl 0
0x4c,0x8b,0x04,0x21 = bnuctrl 2
0x4c,0x83,0x04,0x21 = bnuctrl 0
0x4c,0xeb,0x00,0x20 = bnulr+ 2
0x4c,0xe3,0x00,0x20 = bnulr+ 0
0x4c,0xeb,0x04,0x20 = bnuctr+ 2
0x4c,0xe3,0x04,0x20 = bnuctr+ 0
0x4c,0xeb,0x00,0x21 = bnulrl+ 2
0x4c,0xe3,0x00,0x21 = bnulrl+ 0
0x4c,0xeb,0x04,0x21 = bnuctrl+ 2
0x4c,0xe3,0x04,0x21 = bnuctrl+ 0
0x4c,0xcb,0x00,0x20 = bnulr- 2
0x4c,0xc3,0x00,0x20 = bnulr- 0
0x4c,0xcb,0x04,0x20 = bnuctr- 2
0x4c,0xc3,0x04,0x20 = bnuctr- 0
0x4c,0xcb,0x00,0x21 = bnulrl- 2
0x4c,0xc3,0x00,0x21 = bnulrl- 0
0x4c,0xcb,0x04,0x21 = bnuctrl- 2
0x4c,0xc3,0x04,0x21 = bnuctrl- 0
0x4c,0x42,0x12,0x42 = creqv 2, 2, 2
0x4c,0x42,0x11,0x82 = crxor 2, 2, 2
0x4c,0x43,0x1b,0x82 = cror 2, 3, 3
0x4c,0x43,0x18,0x42 = crnor 2, 3, 3
0x38,0x43,0xff,0x80 = addi 2, 3, -128
0x3c,0x43,0xff,0x80 = addis 2, 3, -128
0x30,0x43,0xff,0x80 = addic 2, 3, -128
0x34,0x43,0xff,0x80 = addic. 2, 3, -128
0x7c,0x44,0x18,0x50 = subf 2, 4, 3
0x7c,0x44,0x18,0x51 = subf. 2, 4, 3
0x7c,0x44,0x18,0x10 = subfc 2, 4, 3
0x7c,0x44,0x18,0x11 = subfc. 2, 4, 3
0x2d,0x23,0x00,0x80 = cmpdi 2, 3, 128
0x2c,0x23,0x00,0x80 = cmpdi 0, 3, 128
0x7d,0x23,0x20,0x00 = cmpd 2, 3, 4
0x7c,0x23,0x20,0x00 = cmpd 0, 3, 4
0x29,0x23,0x00,0x80 = cmpldi 2, 3, 128
0x28,0x23,0x00,0x80 = cmpldi 0, 3, 128
0x7d,0x23,0x20,0x40 = cmpld 2, 3, 4
0x7c,0x23,0x20,0x40 = cmpld 0, 3, 4
0x2d,0x03,0x00,0x80 = cmpwi 2, 3, 128
0x2c,0x03,0x00,0x80 = cmpwi 0, 3, 128
0x7d,0x03,0x20,0x00 = cmpw 2, 3, 4
0x7c,0x03,0x20,0x00 = cmpw 0, 3, 4
0x29,0x03,0x00,0x80 = cmplwi 2, 3, 128
0x28,0x03,0x00,0x80 = cmplwi 0, 3, 128
0x7d,0x03,0x20,0x40 = cmplw 2, 3, 4
0x7c,0x03,0x20,0x40 = cmplw 0, 3, 4
0x0e,0x03,0x00,0x04 = twi 16, 3, 4
0x7e,0x03,0x20,0x08 = tw 16, 3, 4
0x0a,0x03,0x00,0x04 = tdi 16, 3, 4
0x7e,0x03,0x20,0x88 = td 16, 3, 4
0x0e,0x83,0x00,0x04 = twi 20, 3, 4
0x7e,0x83,0x20,0x08 = tw 20, 3, 4
0x0a,0x83,0x00,0x04 = tdi 20, 3, 4
0x7e,0x83,0x20,0x88 = td 20, 3, 4
0x0c,0x83,0x00,0x04 = twi 4, 3, 4
0x7c,0x83,0x20,0x08 = tw 4, 3, 4
0x08,0x83,0x00,0x04 = tdi 4, 3, 4
0x7c,0x83,0x20,0x88 = td 4, 3, 4
0x0d,0x83,0x00,0x04 = twi 12, 3, 4
0x7d,0x83,0x20,0x08 = tw 12, 3, 4
0x09,0x83,0x00,0x04 = tdi 12, 3, 4
0x7d,0x83,0x20,0x88 = td 12, 3, 4
0x0d,0x03,0x00,0x04 = twi 8, 3, 4
0x7d,0x03,0x20,0x08 = tw 8, 3, 4
0x09,0x03,0x00,0x04 = tdi 8, 3, 4
0x7d,0x03,0x20,0x88 = td 8, 3, 4
0x0d,0x83,0x00,0x04 = twi 12, 3, 4
0x7d,0x83,0x20,0x08 = tw 12, 3, 4
0x09,0x83,0x00,0x04 = tdi 12, 3, 4
0x7d,0x83,0x20,0x88 = td 12, 3, 4
0x0f,0x03,0x00,0x04 = twi 24, 3, 4
0x7f,0x03,0x20,0x08 = tw 24, 3, 4
0x0b,0x03,0x00,0x04 = tdi 24, 3, 4
0x7f,0x03,0x20,0x88 = td 24, 3, 4
0x0e,0x83,0x00,0x04 = twi 20, 3, 4
0x7e,0x83,0x20,0x08 = tw 20, 3, 4
0x0a,0x83,0x00,0x04 = tdi 20, 3, 4
0x7e,0x83,0x20,0x88 = td 20, 3, 4
0x0c,0x43,0x00,0x04 = twi 2, 3, 4
0x7c,0x43,0x20,0x08 = tw 2, 3, 4
0x08,0x43,0x00,0x04 = tdi 2, 3, 4
0x7c,0x43,0x20,0x88 = td 2, 3, 4
0x0c,0xc3,0x00,0x04 = twi 6, 3, 4
0x7c,0xc3,0x20,0x08 = tw 6, 3, 4
0x08,0xc3,0x00,0x04 = tdi 6, 3, 4
0x7c,0xc3,0x20,0x88 = td 6, 3, 4
0x0c,0xa3,0x00,0x04 = twi 5, 3, 4
0x7c,0xa3,0x20,0x08 = tw 5, 3, 4
0x08,0xa3,0x00,0x04 = tdi 5, 3, 4
0x7c,0xa3,0x20,0x88 = td 5, 3, 4
0x0c,0x23,0x00,0x04 = twi 1, 3, 4
0x7c,0x23,0x20,0x08 = tw 1, 3, 4
0x08,0x23,0x00,0x04 = tdi 1, 3, 4
0x7c,0x23,0x20,0x88 = td 1, 3, 4
0x0c,0xa3,0x00,0x04 = twi 5, 3, 4
0x7c,0xa3,0x20,0x08 = tw 5, 3, 4
0x08,0xa3,0x00,0x04 = tdi 5, 3, 4
0x7c,0xa3,0x20,0x88 = td 5, 3, 4
0x0c,0xc3,0x00,0x04 = twi 6, 3, 4
0x7c,0xc3,0x20,0x08 = tw 6, 3, 4
0x08,0xc3,0x00,0x04 = tdi 6, 3, 4
0x7c,0xc3,0x20,0x88 = td 6, 3, 4
0x0f,0xe3,0x00,0x04 = twi 31, 3, 4
0x7f,0xe3,0x20,0x08 = tw 31, 3, 4
0x0b,0xe3,0x00,0x04 = tdi 31, 3, 4
0x7f,0xe3,0x20,0x88 = td 31, 3, 4
0x7f,0xe0,0x00,0x08 = trap
0x78,0x62,0x28,0xc4 = rldicr 2, 3, 5, 3
0x78,0x62,0x28,0xc5 = rldicr. 2, 3, 5, 3
0x78,0x62,0x4f,0x20 = rldicl 2, 3, 9, 60
0x78,0x62,0x4f,0x21 = rldicl. 2, 3, 9, 60
0x78,0x62,0xb9,0x4e = rldimi 2, 3, 55, 5
0x78,0x62,0xb9,0x4f = rldimi. 2, 3, 55, 5
0x78,0x62,0x20,0x00 = rldicl 2, 3, 4, 0
0x78,0x62,0x20,0x01 = rldicl. 2, 3, 4, 0
0x78,0x62,0xe0,0x02 = rldicl 2, 3, 60, 0
0x78,0x62,0xe0,0x03 = rldicl. 2, 3, 60, 0
0x78,0x62,0x20,0x10 = rldcl 2, 3, 4, 0
0x78,0x62,0x20,0x11 = rldcl. 2, 3, 4, 0
0x78,0x62,0x26,0xe4 = sldi 2, 3, 4
0x78,0x62,0x26,0xe5 = rldicr. 2, 3, 4, 59
0x78,0x62,0xe1,0x02 = rldicl 2, 3, 60, 4
0x78,0x62,0xe1,0x03 = rldicl. 2, 3, 60, 4
0x78,0x62,0x01,0x00 = rldicl 2, 3, 0, 4
0x78,0x62,0x01,0x01 = rldicl. 2, 3, 0, 4
0x78,0x62,0x06,0xe4 = rldicr 2, 3, 0, 59
0x78,0x62,0x06,0xe5 = rldicr. 2, 3, 0, 59
0x78,0x62,0x20,0x48 = rldic 2, 3, 4, 1
0x78,0x62,0x20,0x49 = rldic. 2, 3, 4, 1
0x54,0x62,0x28,0x06 = rlwinm 2, 3, 5, 0, 3
0x54,0x62,0x28,0x07 = rlwinm. 2, 3, 5, 0, 3
0x54,0x62,0x4f,0x3e = rlwinm 2, 3, 9, 28, 31
0x54,0x62,0x4f,0x3f = rlwinm. 2, 3, 9, 28, 31
0x50,0x62,0xd9,0x50 = rlwimi 2, 3, 27, 5, 8
0x50,0x62,0xd9,0x51 = rlwimi. 2, 3, 27, 5, 8
0x50,0x62,0xb9,0x50 = rlwimi 2, 3, 23, 5, 8
0x50,0x62,0xb9,0x51 = rlwimi. 2, 3, 23, 5, 8
0x54,0x62,0x20,0x3e = rlwinm 2, 3, 4, 0, 31
0x54,0x62,0x20,0x3f = rlwinm. 2, 3, 4, 0, 31
0x54,0x62,0xe0,0x3e = rlwinm 2, 3, 28, 0, 31
0x54,0x62,0xe0,0x3f = rlwinm. 2, 3, 28, 0, 31
0x5c,0x62,0x20,0x3e = rlwnm 2, 3, 4, 0, 31
0x5c,0x62,0x20,0x3f = rlwnm. 2, 3, 4, 0, 31
0x54,0x62,0x20,0x36 = slwi 2, 3, 4
0x54,0x62,0x20,0x37 = rlwinm. 2, 3, 4, 0, 27
0x54,0x62,0xe1,0x3e = srwi 2, 3, 4
0x54,0x62,0xe1,0x3f = rlwinm. 2, 3, 28, 4, 31
0x54,0x62,0x01,0x3e = rlwinm 2, 3, 0, 4, 31
0x54,0x62,0x01,0x3f = rlwinm. 2, 3, 0, 4, 31
0x54,0x62,0x00,0x36 = rlwinm 2, 3, 0, 0, 27
0x54,0x62,0x00,0x37 = rlwinm. 2, 3, 0, 0, 27
0x54,0x62,0x20,0x76 = rlwinm 2, 3, 4, 1, 27
0x54,0x62,0x20,0x77 = rlwinm. 2, 3, 4, 1, 27
0x7c,0x41,0x03,0xa6 = mtspr 1, 2
0x7c,0x41,0x02,0xa6 = mfspr 2, 1
0x7c,0x48,0x03,0xa6 = mtlr 2
0x7c,0x48,0x02,0xa6 = mflr 2
0x7c,0x49,0x03,0xa6 = mtctr 2
0x7c,0x49,0x02,0xa6 = mfctr 2
0x60,0x00,0x00,0x00 = nop
0x68,0x00,0x00,0x00 = xori 0, 0, 0
0x38,0x40,0x00,0x80 = li 2, 128
0x3c,0x40,0x00,0x80 = lis 2, 128
0x7c,0x62,0x1b,0x78 = mr 2, 3
0x7c,0x62,0x1b,0x79 = or. 2, 3, 3
0x7c,0x62,0x18,0xf8 = nor 2, 3, 3
0x7c,0x62,0x18,0xf9 = nor. 2, 3, 3
0x7c,0x4f,0xf1,0x20 = mtcrf 255, 2
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Net;
using Azure.Core;
using Azure.Core.TestFramework;
using Azure.Data.Tables.Sas;
using NUnit.Framework;
using Parms = Azure.Data.Tables.TableConstants.Sas.Parameters;
namespace Azure.Data.Tables.Tests
{
public class TableClientTests : ClientTestBase
{
public TableClientTests(bool isAsync) : base(isAsync)
{ }
private const string TableName = "someTableName";
private const string AccountName = "someaccount";
private readonly Uri _url = new Uri($"https://someaccount.table.core.windows.net");
private readonly Uri _urlHttp = new Uri($"http://someaccount.table.core.windows.net");
private TableClient client { get; set; }
private const string Secret = "Kg==";
private TableEntity entityWithoutPK = new TableEntity { { TableConstants.PropertyNames.RowKey, "row" } };
private TableEntity entityWithoutRK = new TableEntity { { TableConstants.PropertyNames.PartitionKey, "partition" } };
private TableEntity validEntity = new TableEntity { { TableConstants.PropertyNames.PartitionKey, "partition" }, { TableConstants.PropertyNames.RowKey, "row" } };
[SetUp]
public void TestSetup()
{
var service_Instrumented = InstrumentClient(new TableServiceClient(new Uri("https://example.com"), new AzureSasCredential("sig"), new TableClientOptions()));
client = service_Instrumented.GetTableClient(TableName);
}
/// <summary>
/// Validates the functionality of the TableServiceClient.
/// </summary>
[Test]
public void ConstructorValidatesArguments()
{
Assert.That(() => new TableClient(_url, null, new TableSharedKeyCredential(AccountName, string.Empty)), Throws.InstanceOf<ArgumentNullException>(), "The constructor should validate the tableName.");
Assert.That(() => new TableClient(null, TableName, new TableSharedKeyCredential(AccountName, string.Empty)), Throws.InstanceOf<ArgumentNullException>(), "The constructor should validate the url.");
Assert.That(() => new TableClient(_url, TableName, new TableSharedKeyCredential(AccountName, string.Empty), new TableClientOptions()), Throws.Nothing, "The constructor should accept valid arguments.");
Assert.That(() => new TableClient(_url, TableName, credential: null), Throws.InstanceOf<ArgumentNullException>(), "The constructor should validate the TablesSharedKeyCredential.");
Assert.That(() => new TableClient(_urlHttp, TableName, new AzureSasCredential("sig")), Throws.InstanceOf<ArgumentException>(), "The constructor should validate the Uri is https when using a SAS token.");
Assert.That(() => new TableClient(_urlHttp, TableName, null), Throws.InstanceOf<ArgumentException>(), "The constructor should not accept a null credential");
Assert.That(() => new TableClient(_url, TableName, new TableSharedKeyCredential(AccountName, string.Empty)), Throws.Nothing, "The constructor should accept valid arguments.");
Assert.That(() => new TableClient(_urlHttp, TableName, new TableSharedKeyCredential(AccountName, string.Empty)), Throws.Nothing, "The constructor should accept an http url.");
}
public static IEnumerable<object[]> ValidConnStrings()
{
yield return new object[] { $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.com:443/;" };
yield return new object[] { $"AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.com:443/;" };
yield return new object[] { $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret};EndpointSuffix=core.windows.net" };
yield return new object[] { $"AccountName={AccountName};AccountKey={Secret};EndpointSuffix=core.windows.net" };
yield return new object[] { $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret}" };
yield return new object[] { $"AccountName={AccountName};AccountKey={Secret}" };
}
[Test]
[TestCaseSource(nameof(ValidConnStrings))]
public void AccountNameAndNameForConnStringCtor(string connString)
{
var client = new TableClient(connString, TableName, new TableClientOptions());
Assert.AreEqual(AccountName, client.AccountName);
Assert.AreEqual(TableName, client.Name);
}
[Test]
public void AccountNameAndNameForUriCtor()
{
var client = new TableClient(_url, TableName, new TableSharedKeyCredential(AccountName, string.Empty), new TableClientOptions());
Assert.AreEqual(AccountName, client.AccountName);
Assert.AreEqual(TableName, client.Name);
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public void ServiceMethodsValidateArguments()
{
Assert.That(async () => await client.AddEntityAsync<TableEntity>(null), Throws.InstanceOf<ArgumentNullException>(), "The method should validate the entity is not null.");
Assert.That(async () => await client.UpsertEntityAsync<TableEntity>(null, TableUpdateMode.Replace), Throws.InstanceOf<ArgumentNullException>(), "The method should validate the entity is not null.");
Assert.That(async () => await client.UpsertEntityAsync(new TableEntity { PartitionKey = null, RowKey = "row" }, TableUpdateMode.Replace), Throws.InstanceOf<ArgumentException>(), $"The method should validate the entity has a {TableConstants.PropertyNames.PartitionKey}.");
Assert.That(async () => await client.UpsertEntityAsync(new TableEntity { PartitionKey = "partition", RowKey = null }, TableUpdateMode.Replace), Throws.InstanceOf<ArgumentException>(), $"The method should validate the entity has a {TableConstants.PropertyNames.RowKey}.");
Assert.That(async () => await client.UpdateEntityAsync<TableEntity>(null, new ETag("etag"), TableUpdateMode.Replace), Throws.InstanceOf<ArgumentNullException>(), "The method should validate the entity is not null.");
Assert.That(async () => await client.UpdateEntityAsync(validEntity, default, TableUpdateMode.Replace), Throws.InstanceOf<ArgumentException>(), "The method should validate the eTag is not null.");
Assert.That(async () => await client.UpdateEntityAsync(entityWithoutPK, new ETag("etag"), TableUpdateMode.Replace), Throws.InstanceOf<ArgumentException>(), $"The method should validate the entity has a {TableConstants.PropertyNames.PartitionKey}.");
Assert.That(async () => await client.UpdateEntityAsync(entityWithoutRK, new ETag("etag"), TableUpdateMode.Replace), Throws.InstanceOf<ArgumentException>(), $"The method should validate the entity has a {TableConstants.PropertyNames.RowKey}.");
}
[Test]
public void GetSasBuilderPopulatesPermissionsAndExpiry()
{
var expiry = DateTimeOffset.Now.AddDays(1);
var permissions = TableSasPermissions.All;
var sas = client.GetSasBuilder(permissions, expiry);
Assert.That(sas.Permissions, Is.EqualTo(permissions.ToPermissionsString()));
Assert.That(sas.ExpiresOn, Is.EqualTo(expiry));
}
[Test]
public void GetSasBuilderPopulatesRawPermissionsAndExpiry()
{
var expiry = DateTimeOffset.Now.AddDays(1);
var permissions = TableSasPermissions.All;
var sas = client.GetSasBuilder(permissions.ToPermissionsString(), expiry);
Assert.That(sas.Permissions, Is.EqualTo(permissions.ToPermissionsString()));
Assert.That(sas.ExpiresOn, Is.EqualTo(expiry));
}
[Test]
public void GetSasBuilderGeneratesCorrectUri()
{
var expiry = new DateTimeOffset(2020, 1, 1, 1, 1, 1, TimeSpan.Zero);
var permissions = TableSasPermissions.All;
var sas = client.GetSasBuilder(permissions.ToPermissionsString(), expiry);
const string startIP = "123.45.67.89";
const string endIP = "123.65.43.21";
sas.IPRange = new TableSasIPRange(IPAddress.Parse(startIP), IPAddress.Parse(endIP));
sas.PartitionKeyEnd = "PKEND";
sas.PartitionKeyStart = "PKSTART";
sas.RowKeyEnd = "PKEND";
sas.RowKeyStart = "RKSTART";
sas.StartsOn = expiry.AddHours(-1);
string token = sas.Sign(new TableSharedKeyCredential("foo", "Kg=="));
Assert.That(
token,
Is.EqualTo(
$"{Parms.TableName}={TableName}&{Parms.StartPartitionKey}={sas.PartitionKeyStart}&{Parms.EndPartitionKey}={sas.PartitionKeyEnd}&{Parms.StartRowKey}={sas.RowKeyStart}&{Parms.EndRowKey}={sas.RowKeyEnd}&{Parms.Version}=2019-02-02&{Parms.StartTime}=2020-01-01T00%3A01%3A01Z&{Parms.ExpiryTime}=2020-01-01T01%3A01%3A01Z&{Parms.IPRange}=123.45.67.89-123.65.43.21&{Parms.Permissions}=raud&{Parms.Signature}=nUfFBSzJ7NckYoHxSeX5nKcVbqJDBJQfPpGffr5Ui2M%3D"));
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public void CreatedTableEntityEnumEntitiesThrowNotSupported()
{
var entityToCreate = new TableEntity { PartitionKey = "partitionKey", RowKey = "01" };
entityToCreate["MyFoo"] = Foo.Two;
// Create the new entities.
Assert.ThrowsAsync<NotSupportedException>(async () => await client.AddEntityAsync(entityToCreate).ConfigureAwait(false));
}
[Test]
public void CreatedTableEntityPropertiesAreSerializedProperly()
{
var entity = new TableEntity { PartitionKey = "partitionKey", RowKey = "01", Timestamp = DateTime.Now, ETag = ETag.All };
entity["MyFoo"] = "Bar";
var dictEntity = entity.ToOdataAnnotatedDictionary();
Assert.That(dictEntity["PartitionKey"], Is.EqualTo(entity.PartitionKey), "The entities should be equivalent");
Assert.That(dictEntity["RowKey"], Is.EqualTo(entity.RowKey), "The entities should be equivalent");
Assert.That(dictEntity["MyFoo"], Is.EqualTo(entity["MyFoo"].ToString()), "The entities should be equivalent");
Assert.That(dictEntity.Keys, Is.EquivalentTo(new[] { "PartitionKey", "RowKey", "MyFoo" }), "Only PK, RK, and user properties should be sent");
}
[Test]
public void CreatedEnumPropertiesAreSerializedProperly()
{
var entity = new EnumEntity { PartitionKey = "partitionKey", RowKey = "01", Timestamp = DateTime.Now, MyFoo = Foo.Two, MyNullableFoo = null, ETag = ETag.All };
// Create the new entities.
var dictEntity = entity.ToOdataAnnotatedDictionary();
Assert.That(dictEntity["PartitionKey"], Is.EqualTo(entity.PartitionKey), "The entities should be equivalent");
Assert.That(dictEntity["RowKey"], Is.EqualTo(entity.RowKey), "The entities should be equivalent");
Assert.That(dictEntity["MyFoo"], Is.EqualTo(entity.MyFoo.ToString()), "The entities should be equivalent");
Assert.That(dictEntity["MyNullableFoo"], Is.EqualTo(entity.MyNullableFoo), "The entities should be equivalent");
Assert.That(dictEntity.TryGetValue(TableConstants.PropertyNames.Timestamp, out var _), Is.False, "Only PK, RK, and user properties should be sent");
}
[Test]
public void EnumPropertiesAreDeSerializedProperly()
{
var entity = new EnumEntity { PartitionKey = "partitionKey", RowKey = "01", Timestamp = DateTime.Now, MyFoo = Foo.Two, MyNullableFoo = null, MyNullableFoo2 = NullableFoo.Two, ETag = ETag.All };
// Create the new entities.
var dictEntity = entity.ToOdataAnnotatedDictionary();
var deserializedEntity = dictEntity.ToTableEntity<EnumEntity>();
Assert.That(deserializedEntity.PartitionKey, Is.EqualTo(entity.PartitionKey), "The entities should be equivalent");
Assert.That(deserializedEntity.RowKey, Is.EqualTo(entity.RowKey), "The entities should be equivalent");
Assert.That(deserializedEntity.MyFoo.ToString(), Is.EqualTo(entity.MyFoo.ToString()), "The entities should be equivalent");
Assert.That(deserializedEntity.MyNullableFoo.ToString(), Is.EqualTo(entity.MyNullableFoo.ToString()), "The entities should be equivalent");
Assert.That(deserializedEntity.MyNullableFoo2.ToString(), Is.EqualTo(entity.MyNullableFoo2.ToString()), "The entities should be equivalent");
Assert.That(dictEntity.TryGetValue(TableConstants.PropertyNames.Timestamp, out var _), Is.False, "Only PK, RK, and user properties should be sent");
}
[Test]
public void RoundTripContinuationTokenWithPartitionKeyAndRowKey()
{
var response = new MockResponse(200);
(string NextPartitionKey, string NextRowKey) expected = ("next-pk", "next-rk");
response.AddHeader(new HttpHeader("x-ms-continuation-NextPartitionKey", expected.NextPartitionKey));
response.AddHeader(new HttpHeader("x-ms-continuation-NextRowKey", expected.NextRowKey));
var headers = new TableQueryEntitiesHeaders(response);
var continuationToken = TableClient.CreateContinuationTokenFromHeaders(headers);
var actual = TableClient.ParseContinuationToken(continuationToken);
Assert.That(continuationToken, Is.EqualTo("next-pk next-rk"));
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void RoundTripContinuationTokenWithPartitionKeyAndNoRowKey()
{
var response = new MockResponse(200);
(string NextPartitionKey, string NextRowKey) expected = ("next-pk", null);
response.AddHeader(new HttpHeader("x-ms-continuation-NextPartitionKey", expected.NextPartitionKey));
var headers = new TableQueryEntitiesHeaders(response);
var continuationToken = TableClient.CreateContinuationTokenFromHeaders(headers);
var actual = TableClient.ParseContinuationToken(continuationToken);
Assert.That(continuationToken, Is.EqualTo("next-pk "));
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void NullContinuationTokenReturnsWhenWithNoPartitionKeyAndNoRowKey()
{
var response = new MockResponse(200);
(string NextPartitionKey, string NextRowKey) expected = (null, null);
var headers = new TableQueryEntitiesHeaders(response);
var continuationToken = TableClient.CreateContinuationTokenFromHeaders(headers);
var actual = TableClient.ParseContinuationToken(continuationToken);
Assert.That(continuationToken, Is.Null);
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void HandlesEmptyStringContinuationToken()
{
(string NextPartitionKey, string NextRowKey) expected = (null, null);
var actual = TableClient.ParseContinuationToken(" ");
Assert.That(actual, Is.EqualTo(expected));
}
public class EnumEntity : ITableEntity
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTimeOffset? Timestamp { get; set; }
public ETag ETag { get; set; }
public Foo MyFoo { get; set; }
public NullableFoo? MyNullableFoo { get; set; }
public NullableFoo? MyNullableFoo2 { get; set; }
}
public enum Foo
{
One,
Two
}
public enum NullableFoo
{
One,
Two
}
}
}
| |
// analyze.c
#region OMIT_ANALYZE
#if !OMIT_ANALYZE
using System;
using System.Diagnostics;
using System.Text;
using tRowcnt = System.UInt32; // 32-bit is the default
namespace Core.Command
{
public class Analyze
{
public struct Table_t
{
public string Name;
public string Cols;
public Table_t(string name, string cols)
{
Name = name;
Cols = cols;
}
}
static Table_t[] _tables = new Table_t[]
{
new Table_t("sqlite_stat1", "tbl,idx,stat"),
#if ENABLE_STAT3
new Table_t( "sqlite_stat3", "tbl,idx,new,sampleno,sample" ),
#endif
};
static void OpenStatTable(Parse parse, int db, int statCur, string where_, string whereType)
{
int[] roots = new int[] { 0, 0 };
byte[] createTbls = new byte[] { 0, 0 };
Context ctx = parse.Ctx;
Vdbe v = parse.GetVdbe();
if (v == null) return;
Debug.Assert(Btree.HoldsAllMutexes(ctx));
Debug.Assert(v.Ctx == ctx);
Context.DB dbObj = ctx.DBs[db];
for (int i = 0; i < _tables.Length; i++)
{
string tableName = _tables[i].Name;
Table stat;
if ((stat = Parse.FindTable(ctx, tableName, dbObj.Name)) == null)
{
// The sqlite_stat[12] table does not exist. Create it. Note that a side-effect of the CREATE TABLE statement is to leave the rootpage
// of the new table in register pParse.regRoot. This is important because the OpenWrite opcode below will be needing it.
parse.NestedParse("CREATE TABLE %Q.%s(%s)", dbObj.Name, tableName, _tables[i].Cols);
roots[i] = parse.RegRoot;
createTbls[i] = Vdbe::OPFLAG_P2ISREG;
}
else
{
// The table already exists. If zWhere is not NULL, delete all entries associated with the table zWhere. If zWhere is NULL, delete the
// entire contents of the table.
roots[i] = stat.Id;
sqlite3TableLock(parse, db, roots[i], 1, tableName);
if (where_ == null)
parse.NestedParse("DELETE FROM %Q.%s WHERE %s=%Q", dbObj.Name, tableName, whereType, where_);
else
v.AddOp2(OP.Clear, roots[i], db); // The sqlite_stat[12] table already exists. Delete all rows.
}
}
// Open the sqlite_stat[12] tables for writing.
for (int i = 0; i < _tables.Length; i++)
{
v.AddOp3(OP.OpenWrite, statCur + i, roots[i], db);
v.ChangeP4(-1, 3, Vdbe.P4T.INT32);
v.ChangeP5(createTbls[i]);
}
}
const int STAT3_SAMPLES = 24;
class Stat3Accum
{
public tRowcnt Rows; // Number of rows in the entire table
public tRowcnt PSamples; // How often to do a periodic sample
public int Min; // Index of entry with minimum nEq and hash
public int MaxSamples; // Maximum number of samples to accumulate
public uint Prn; // Pseudo-random number used for sampling
public class Stat3Sample
{
public long Rowid; // Rowid in main table of the key
public tRowcnt Eq; // sqlite_stat3.nEq
public tRowcnt Lt; // sqlite_stat3.nLt
public tRowcnt DLt; // sqlite_stat3.nDLt
public bool IsPSample; // True if a periodic sample
public uint Hash; // Tiebreaker hash
};
public array_t<Stat3Sample> a; // An array of samples
};
#if ENABLE_STAT3
static void Stat3Init_(FuncContext fctx, int argc, Mem[][] argv)
{
tRowcnt rows = (tRowcnt)Vdbe.Value_Int64(argv[0]);
int maxSamples = Vdbe.Value_Int(argv[1]);
int n = maxSamples;
Stat3Accum p = new Stat3Accum
{
a = new array_t<Stat3Accum.Stat3Sample>(new Stat3Accum.Stat3Sample[n]),
Rows = rows,
MaxSamples = maxSamples,
PSamples = (uint)(rows / (maxSamples / 3 + 1) + 1),
};
if (p == null)
{
Vdbe.Result_ErrorNoMem(fctx);
return;
}
SysEx.Randomness(-1, p.Prn);
Vdbe.Result_Blob(fctx, p, -1, C._free);
}
static const FuncDef stat3InitFuncdef = new FuncDef
{
2, // nArg
TEXTENCODE.UTF8, // iPrefEnc
(FUNC)0, // flags
null, // pUserData
null, // pNext
Stat3Init_, // xFunc
null, // xStep
null, // xFinalize
"stat3_init", // zName
null, // pHash
null // pDestructor
};
static void Stat3Push_(FuncContext fctx, int argc, Mem[] argv)
{
tRowcnt eq = (tRowcnt)Vdbe.Value_Int64(argv[0]);
if (eq == 0) return;
tRowcnt lt = (tRowcnt)Vdbe.Value_Int64(argv[1]);
tRowcnt dLt = (tRowcnt)Vdbe.Value_Int64(argv[2]);
long rowid = Vdbe.Value_Int64(argv[3]);
Stat3Accum p = (Stat3Accum)Vdbe.Value_Blob(argv[4]);
bool isPSample = false;
bool doInsert = false;
int min = p.Min;
uint h = p.Prn = p.Prn*1103515245 + 12345;
if ((lt/p.PSamples) != ((eq+lt)/p.PSamples)) doInsert = isPSample = true;
else if (p.a.length < p.MaxSamples) doInsert = true;
else if (eq > p.a[min].Eq || (eq == p.a[min].Eq && h > p.a[min].Hash)) doInsert = true;
if (!doInsert) return;
Stat3Accum.Stat3Sample sample;
if (p.a.length == p.MaxSamples)
{
Debug.Assert(p.a.length - min - 1 >= 0);
C._memmove(p.a[min], p.a[min+1], sizeof(p.a[0])*(p.a.length-min-1));
sample = p.a[p.a.length-1];
}
else
sample = p.a[p.a.length++];
sample.Rowid = rowid;
sample.Eq = eq;
sample.Lt = lt;
sample.DLt = dLt;
sample.Hash = h;
sample.IsPSample = isPSample;
// Find the new minimum
if (p.a.length == p.MaxSamples)
{
int sampleIdx = 0; sample = p.a[sampleIdx];
int i = 0;
while (sample.IsPSample)
{
i++;
sampleIdx++; sample = p.a[sampleIdx];
Debug.Assert(i < p.a.length);
}
eq = sample.Eq;
h = sample.Hash;
min = i;
for (i++, sampleIdx++; i < p.a.length; i++, sampleIdx++)
{
sample = p.a[sampleIdx];
if (sample.IsPSample) continue;
if (sample.Eq < eq || (sample.Eq == eq && sample.Hash < h))
{
min = i;
eq = sample.Eq;
h = sample.Hash;
}
}
p.Min = min;
}
}
static const FuncDef Stat3PushFuncdef = new FuncDef
{
5, // nArg
TEXTENCODE.UTF8, // iPrefEnc
(FUNC)0, // flags
null, // pUserData
null, // pNext
Stat3Push_, // xFunc
null, // xStep
null, // xFinalize
"stat3_push", // zName
null, // pHash
null // pDestructor
};
static void Stat3Get_(FuncContext fctx, int argc, Mem[] argv)
{
int n = Vdbe.Value_Int(argv[1]);
Stat3Accum p = (Stat3Accum)Vdbe.Value_Blob(argv[0]);
Debug.Assert(p != null);
if (p.a.length <= n) return;
switch (argc)
{
case 2: Vdbe.Result_Int64(fctx, p.a[n].Rowid); break;
case 3: Vdbe.Result_Int64(fctx, p.a[n].Eq); break;
case 4: Vdbe.Result_Int64(fctx, p.a[n].Lt); break;
default: Vdbe.Result_Int64(fctx, p.a[n].DLt); break;
}
}
static const FuncDef _stat3GetFuncdef = new FuncDef
{
-1, // nArg
TEXTENCODE.UTF8, // iPrefEnc
(FUNC)0, // flags
null, // pUserData
null, // pNext
Stat3Get_, // xFunc
null, // xStep
null, // xFinalize
"stat3_get", // zName
null, // pHash
null // pDestructor
};
#endif
static void AnalyzeOneTable(Parse parse, Table table, Index onlyIdx, int statCurId, int memId)
{
Context ctx = parse.Ctx; // Database handle
int i; // Loop counter
int regTabname = memId++; // Register containing table name
int regIdxname = memId++; // Register containing index name
int regSampleno = memId++; // Register containing next sample number
int regCol = memId++; // Content of a column analyzed table
int regRec = memId++; // Register holding completed record
int regTemp = memId++; // Temporary use register
int regRowid = memId++; // Rowid for the inserted record
Vdbe v = parse.GetVdbe(); // The virtual machine being built up
if (v == null || C._NEVER(table == null))
return;
// Do not gather statistics on views or virtual tables or system tables
if (table.Id == 0 || table.Name.StartsWith("sqlite_", StringComparison.OrdinalIgnoreCase))
return;
Debug.Assert(Btree.HoldsAllMutexes(ctx));
int db = sqlite3SchemaToIndex(ctx, table.Schema); // Index of database containing pTab
Debug.Assert(db >= 0);
Debug.Assert(Btree.SchemaMutexHeld(ctx, db, null));
#if !OMIT_AUTHORIZATION
if (Auth.Check(parse, AUTH.ANALYZE, table.Name, 0, ctx.DBs[db].Name))
return;
#endif
// Establish a read-lock on the table at the shared-cache level.
sqlite3TableLock(parse, db, table.Id, 0, table.Name);
int zeroRows = -1; // Jump from here if number of rows is zero
int idxCurId = parse.Tabs++; // Cursor open on index being analyzed
v.AddOp4(OP.String8, 0, regTabname, 0, table.Name, 0);
for (Index idx = table.Index; idx != null; idx = idx.Next) // An index to being analyzed
{
if (onlyIdx != null && onlyIdx != idx) continue;
v.NoopComment("Begin analysis of %s", idx.Name);
int cols = idx.Columns.length;
int[] chngAddrs = C._tagalloc<int>(ctx, cols); // Array of jump instruction addresses
if (chngAddrs == null) continue;
KeyInfo key = sqlite3IndexKeyinfo(parse, idx);
if (memId + 1 + (cols * 2) > parse.Mems)
parse.Mems = memId + 1 + (cols * 2);
// Open a cursor to the index to be analyzed.
Debug.Assert(db == sqlite3SchemaToIndex(ctx, idx.Schema));
v.AddOp4(OP.OpenRead, idxCurId, idx.Id, db, key, Vdbe.P4T.KEYINFO_HANDOFF);
v.VdbeComment("%s", idx.Name);
// Populate the registers containing the index names.
v.AddOp4(OP.String8, 0, regIdxname, 0, idx.Name, 0);
#if ENABLE_STAT3
bool once = false; // One-time initialization
if (once)
{
once = false;
sqlite3OpenTable(parse, tabCurId, db, table, OP.OpenRead);
}
v.AddOp2(OP.Count, idxCurId, regCount);
v.AddOp2(OP.Integer, STAT3_SAMPLES, regTemp1);
v.AddOp2(OP.Integer, 0, regNumEq);
v.AddOp2(OP.Integer, 0, regNumLt);
v.AddOp2(OP.Integer, -1, regNumDLt);
v.AddOp3(OP.Null, 0, regSample, regAccum);
v.AddOp4(OP.Function, 1, regCount, regAccum, (object)_stat3InitFuncdef, Vdbe.P4T.FUNCDEF);
v.ChangeP5(2);
#endif
// The block of memory cells initialized here is used as follows.
//
// iMem:
// The total number of rows in the table.
//
// iMem+1 .. iMem+nCol:
// Number of distinct entries in index considering the left-most N columns only, where N is between 1 and nCol,
// inclusive.
//
// iMem+nCol+1 .. Mem+2*nCol:
// Previous value of indexed columns, from left to right.
//
// Cells iMem through iMem+nCol are initialized to 0. The others are initialized to contain an SQL NULL.
for (i = 0; i <= cols; i++)
v.AddOp2(OP.Integer, 0, memId + i);
for (i = 0; i < cols; i++)
v.AddOp2(OP.Null, 0, memId + cols + i + 1);
// Start the analysis loop. This loop runs through all the entries in the index b-tree.
int endOfLoop = v.MakeLabel(); // The end of the loop
v.AddOp2(OP.Rewind, idxCurId, endOfLoop);
int topOfLoop = v.CurrentAddr(); // The top of the loop
v.AddOp2(OP.AddImm, memId, 1);
int addrIfNot = 0; // address of OP_IfNot
for (i = 0; i < cols; i++)
{
v.AddOp3(OP.Column, idxCurId, i, regCol);
if (i == 0) // Always record the very first row
addrIfNot = v.AddOp1(OP.IfNot, memId + 1);
Debug.Assert(idx.CollNames != null && idx.CollNames[i] != null);
CollSeq coll = sqlite3LocateCollSeq(parse, idx.CollNames[i]);
chngAddrs[i] = v.AddOp4(OP.Ne, regCol, 0, memId + cols + i + 1, coll, Vdbe.P4T.COLLSEQ);
v.ChangeP5(SQLITE_NULLEQ);
v.VdbeComment("jump if column %d changed", i);
#if ENABLE_STAT3
if (i == 0)
{
v.AddOp2(OP.AddImm, regNumEq, 1);
v.VdbeComment("incr repeat count");
}
#endif
}
v.AddOp2(OP.Goto, 0, endOfLoop);
for (i = 0; i < cols; i++)
{
v.JumpHere(chngAddrs[i]); // Set jump dest for the OP_Ne
if (i == 0)
{
v.JumpHere(addrIfNot); // Jump dest for OP_IfNot
#if ENABLE_STAT3
v.AddOp4(OP.Function, 1, regNumEq, regTemp2, (object)Stat3PushFuncdef, Vdbe.P4T.FUNCDEF);
v.ChangeP5(5);
v.AddOp3(OP.Column, idxCurId, idx.Columns.length, regRowid);
v.AddOp3(OP.Add, regNumEq, regNumLt, regNumLt);
v.AddOp2(OP.AddImm, regNumDLt, 1);
v.AddOp2(OP.Integer, 1, regNumEq);
#endif
}
v.AddOp2(OP.AddImm, memId + i + 1, 1);
v.AddOp3(OP.Column, idxCurId, i, memId + cols + i + 1);
}
C._tagfree(ctx, chngAddrs);
// Always jump here after updating the iMem+1...iMem+1+nCol counters
v.ResolveLabel(endOfLoop);
v.AddOp2(OP.Next, idxCurId, topOfLoop);
v.AddOp1(OP.Close, idxCurId);
#if ENABLE_STAT3
v.AddOp4(OP.Function, 1, regNumEq, regTemp2, (object)Stat3PushFuncdef, Vdbe.P4T.FUNCDEF);
v.ChangeP5(5);
v.AddOp2(OP.Integer, -1, regLoop);
int shortJump = v.AddOp2(OP_AddImm, regLoop, 1); // Instruction address
v.AddOp4(OP.Function, 1, regAccum, regTemp1, (object)Stat3GetFuncdef, Vdbe.P4T.FUNCDEF);
v.ChangeP5(2);
v.AddOp1(OP.IsNull, regTemp1);
v.AddOp3(OP.NotExists, tabCurId, shortJump, regTemp1);
v.AddOp3(OP.Column, tabCurId, idx->Columns[0], regSample);
sqlite3ColumnDefault(v, table, idx->Columns[0], regSample);
v.AddOp4(OP.Function, 1, regAccum, regNumEq, (object)Stat3GetFuncdef, Vdbe.P4T.FUNCDEF);
v.ChangeP5(3);
v.AddOp4(OP.Function, 1, regAccum, regNumLt, (object)Stat3GetFuncdef, Vdbe.P4T.FUNCDEF);
v.ChangeP5(4);
v.AddOp4(OP.Function, 1, regAccum, regNumDLt, (object)Stat3GetFuncdef, Vdbe.P4T.FUNCDEF);
v.ChangeP5(5);
v.AddOp4(OP.MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
v.AddOp2(OP.NewRowid, statCurId + 1, regNewRowid);
v.AddOp3(OP.Insert, statCurId + 1, regRec, regNewRowid);
v.AddOp2(OP.Goto, 0, shortJump);
v.JumpHere(shortJump + 2);
#endif
// Store the results in sqlite_stat1.
//
// The result is a single row of the sqlite_stat1 table. The first two columns are the names of the table and index. The third column
// is a string composed of a list of integer statistics about the index. The first integer in the list is the total number of entries
// in the index. There is one additional integer in the list for each column of the table. This additional integer is a guess of how many
// rows of the table the index will select. If D is the count of distinct values and K is the total number of rows, then the integer is computed
// as:
// I = (K+D-1)/D
// If K==0 then no entry is made into the sqlite_stat1 table.
// If K>0 then it is always the case the D>0 so division by zero is never possible.
v.AddOp2(OP_SCopy, memId, regStat1);
if (zeroRows < 0)
zeroRows = v.AddOp1(OP.IfNot, memId);
for (i = 0; i < cols; i++)
{
v.AddOp4(OP.String8, 0, regTemp, 0, " ", 0);
v.AddOp3(OP.Concat, regTemp, regStat1, regStat1);
v.AddOp3(OP.Add, memId, memId + i + 1, regTemp);
v.AddOp2(OP.AddImm, regTemp, -1);
v.AddOp3(OP.Divide, memId + i + 1, regTemp, regTemp);
v.AddOp1(OP.ToInt, regTemp);
v.AddOp3(OP.Concat, regTemp, regStat1, regStat1);
}
v.AddOp4(OP.MakeRecord, regTabname, 3, regRec, "aaa", 0);
v.AddOp2(OP.NewRowid, statCurId, regNewRowid);
v.AddOp3(OP.Insert, statCurId, regRec, regNewRowid);
v.ChangeP5(OPFLAG_APPEND);
}
// If the table has no indices, create a single sqlite_stat1 entry containing NULL as the index name and the row count as the content.
if (table.Index == null)
{
v.AddOp3(OP.OpenRead, idxCurId, table->Id, db);
v.VdbeComment("%s", table->Name);
v.AddOp2(OP.Count, idxCurId, regStat1);
v.AddOp1(OP.Close, idxCurId);
zeroRows = v.AddOp1(OP.IfNot, regStat1);
}
else
{
v.JumpHere(zeroRows);
zeroRows = v.AddOp0(OP_Goto);
}
v.AddOp2(OP.Null, 0, regIdxname);
v.AddOp4(OP.MakeRecord, regTabname, 3, regRec, "aaa", 0);
v.AddOp2(OP.NewRowid, statCurId, regNewRowid);
v.AddOp3(OP.Insert, statCurId, regRec, regNewRowid);
v.ChangeP5(OPFLAG_APPEND);
if (parse.Mems < regRec) parse.Mems = regRec;
v.JumpHere(zeroRows);
}
static void LoadAnalysis(Parse parse, int db)
{
Vdbe v = parse.GetVdbe();
if (v != null)
v.AddOp1(OP.LoadAnalysis, db);
}
static void AnalyzeDatabase(Parse parse, int db)
{
Context ctx = parse.Ctx;
Schema schema = ctx.DBs[db].Schema; // Schema of database iDb
parse.BeginWriteOperation(0, db);
int statCurId = parse.nTab;
parse.Tabs += 2;
openStatTable(parse, db, statCurId, null, null);
int memId = parse.Mems + 1;
Debug.Assert(Btree.SchemaMutexHeld(ctx, db, null));
for (HashElem k = schema.TableHash.First; k != null; k = k.Next)
{
Table table = (Table)k.Data;
AnalyzeOneTable(parse, table, null, statCurId, memId);
}
LoadAnalysis(parse, db);
}
static void AnalyzeTable(Parse parse, Table table, Index onlyIdx)
{
Debug.Assert(table != null && Btree.HoldsAllMutexes(parse.Ctx));
int db = Btree.SchemaToIndex(parse.db, table.pSchema);
parse.BeginWriteOperation(parse, 0, db);
int statCurId = parse.Tabs;
parse.Tabs += 2;
if (onlyIdx != null)
OpenStatTable(parse, db, statCurId, onlyIdx.Name, "idx");
else
OpenStatTable(parse, db, statCurId, table.Name, "tbl");
AnalyzeOneTable(parse, table, onlyIdx, statCurId, parse.Mems + 1);
LoadAnalysis(parse, db);
}
public static void Analyze(Parse parse, int null2, int null3) { Analyze(Parse, null, null); } // OVERLOADS, so I don't need to rewrite parse.c
public static void Analyze(Parse parse, Token name1, Token name2)
{
Context ctx = parse.Ctx;
// Read the database schema. If an error occurs, leave an error message and code in pParse and return NULL.
Debug.Assert(Btree.HoldsAllMutexes(parse.Ctx));
if (sqlite3ReadSchema(parse) != RC.OK)
return;
Debug.Assert(name2 != null || name1 == null);
if (name1 == null)
{
// Form 1: Analyze everything
for (int i = 0; i < ctx.DBs.length; i++)
{
if (i == 1) continue; // Do not analyze the TEMP database
AnalyzeDatabase(parse, i);
}
}
else if (name2.length == 0)
{
// Form 2: Analyze the database or table named
int db = sqlite3FindDb(ctx, name1);
if (db >= 0)
AnalyzeDatabase(parse, db);
else
{
string z = sqlite3NameFromToken(ctx, name1);
if (z != null)
{
Index idx;
Table table;
if ((idx = sqlite3FindIndex(ctx, z, null)) != null)
AnalyzeTable(parse, idx.Table, idx);
else if ((table = sqlite3LocateTable(parse, 0, z, null)) != null)
AnalyzeTable(parse, table, null);
C._tagfree(ctx, z);
}
}
}
else
{
// Form 3: Analyze the fully qualified table name
Token tableName = null;
int db = sqlite3TwoPartName(parse, pName1, pName2, ref tableName);
if (db >= 0)
{
string dbName = ctx.DBs[db].Name;
string z = sqlite3NameFromToken(ctx, tableName);
if (z != null)
{
Index idx;
Table table;
if ((idx = sqlite3FindIndex(ctx, z, dbName)) != null)
AnalyzeTable(parse, idx.pTable, idx);
else if ((table = sqlite3LocateTable(parse, 0, z, dbName)) != null)
AnalyzeTable(parse, table, null);
C._tagfree(ctx, z);
}
}
}
}
public struct AnalysisInfo
{
public Context Ctx;
public string Database;
};
static bool AnalysisLoader(object data, long argc, object Oargv, object notUsed)
{
string[] argv = (string[])Oargv;
AnalysisInfo info = (AnalysisInfo)data;
Debug.Assert(argc == 3);
if (argv == null || argv[0] == null || argv[2] == null)
return false;
Table table = sqlite3FindTable(info.Ctx, argv[0], info.Database);
if (table == null)
return false;
Index index = (!string.IsNullOrEmpty(argv[1]) ? sqlite3FindIndex(info.Ctx, argv[1], info.Database) : null);
int n = (index != null ? index.Columns.length : 0);
string z = argv[2];
int zIdx = 0;
for (int i = 0; z != null && i <= n; i++)
{
tRowcnt v = 0;
int c;
while (zIdx < z.Length && (c = z[zIdx]) >= '0' && c <= '9')
{
v = v * 10 + c - '0';
zIdx++;
}
if (i == 0) table.RowEst = v;
if (index == null) break;
index.RowEsts[i] = v;
if (zIdx < z.Length && z[zIdx] == ' ') zIdx++;
if (string.Equals(z.Substring(zIdx), "unordered", StringComparison.OrdinalIgnoreCase))
{
index.Unordered = true;
break;
}
}
return false;
}
public static void DeleteIndexSamples(Context ctx, Index idx)
{
#if ENABLE_STAT3
if (idx.Samples != null)
{
for (int j = 0; j < idx.Samples.length; j++)
{
IndexSample p = idx.Samples[j];
if (p.Type == TYPE.TEXT || p.Type == TYPE.BLOB)
C._tagfree(ctx, ref p.u.Z);
}
C._tagfree(ctx, ref idx.Samples);
}
if (ctx && ctx.BytesFreed == 0)
{
idx.Samples.length = 0;
idx.Samples.data = null;
}
#endif
}
#if ENABLE_STAT3
static RC LoadStat3(Context ctx, string dbName)
{
Debug.Assert(!ctx.Lookaside.Enabled);
if (sqlite3FindTable(ctx, "sqlite_stat3", dbName) == null)
return RC.OK;
string sql = SysEx.Mprintf(ctx, "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", dbName); // Text of the SQL statement
if (!sql)
return RC_NOMEM;
Vdbe stmt = null; // An SQL statement being run
RC rc = Vdbe.Prepare(ctx, sql, -1, stmt, 0); // Result codes from subroutines
C._tagfree(ctx, sql);
if (rc) return rc;
while (stmt.Step() == RC.ROW)
{
string indexName = (string)Vdbe.Column_Text(stmt, 0); // Index name
if (!indexName) continue;
int samplesLength = Vdbe.Column_Int(stmt, 1); // Number of samples
Index idx = sqlite3FindIndex(ctx, indexName, dbName); // Pointer to the index object
if (!idx) continue;
_assert(idx->Samples.length == 0);
idx.Samples.length = samplesLength;
idx.Samples.data = new IndexSample[samplesLength];
idx.AvgEq = idx.RowEsts[1];
if (!idx->Samples.data)
{
ctx->MallocFailed = true;
Vdbe.Finalize(stmt);
return RC.NOMEM;
}
}
rc = Vdbe.Finalize(stmt);
if (rc) return rc;
sql = C._mtagprintf(ctx, "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", dbName);
if (!sql)
return RC.NOMEM;
rc = Vdbe.Prepare(ctx, sql, -1, &stmt, 0);
C._tagfree(ctx, sql);
if (rc) return rc;
Index prevIdx = null; // Previous index in the loop
int idxId = 0; // slot in pIdx->aSample[] for next sample
while (stmt.Step() == RC.ROW)
{
string indexName = (string)Vdbe.Column_Text(stmt, 0); // Index name
if (indexName == null) continue;
Index idx = sqlite3FindIndex(ctx, indexName, dbName); // Pointer to the index object
if (idx == null) continue;
if (idx == prevIdx)
idxId++;
else
{
prevIdx = idx;
idxId = 0;
}
Debug.Assert(idxId < idx.Samples.length);
IndexSample sample = idx.Samples[idxId]; // A slot in pIdx->aSample[]
sample.Eq = (tRowcnt)Vdbe.Column_Int64(stmt, 1);
sample.Lt = (tRowcnt)Vdbe.Column_Int64(stmt, 2);
sample.DLt = (tRowcnt)Vdbe.Column_Int64(stmt, 3);
if (idxId == idx.Samples.length - 1)
{
tRowcnt sumEq; // Sum of the nEq values
if (sample.DLt > 0)
{
for (int i = 0, sumEq = 0; i <= idxId - 1; i++) sumEq += idx.Samples[i].Eq;
idx.AvgEq = (sample.Lt - sumEq) / sample.DLt;
}
if (idx.AvgEq <= 0) idx.AvgEq = 1;
}
TYPE type = Vdbe.Column_Type(stmt, 4); // Datatype of a sample
sample.Type = type;
switch (type)
{
case TYPE.INTEGER:
{
sample.u.I = Vdbe.Column_Int64(stmt, 4);
break;
}
case TYPE.FLOAT:
{
sample.u.R = Vdbe.Column_Double(stmt, 4);
break;
}
case TYPE.NULL:
{
break;
}
default: Debug.Assert(type == TYPE.TEXT || type == TYPE.BLOB);
{
string z = (string)(type == TYPE_BLOB ? Vdbe.Column_Blob(stmt, 4) : Vdbe.Column_Text(stmt, 4));
int n = (z ? Vdbe.Column_Bytes(stmt, 4) : 0);
sample.Bytes = n;
if (n < 1)
sample.u.Z = null;
else
{
sample.u.Z = C._tagalloc(ctx, n);
if (sample->u.Z == null)
{
ctx.MallocFailed = true;
Vdbe.Finalize(stmt);
return RC.NOMEM;
}
Buffer.BlockCopy(sample.u.Z, z, n);
}
}
}
}
return Vdbe.Finalize(stmt);
}
#endif
public static RC AnalysisLoad(Context ctx, int db)
{
Debug.Assert(db >= 0 && db < ctx.DBs.length);
Debug.Assert(ctx.DBs[db].Bt != null);
// Clear any prior statistics
Debug.Assert(Btree.SchemaMutexHeld(ctx, db, null));
for (HashElem i = ctx.DBs[db].Schema.IndexHash.First; i != null; i = i.Next)
{
Index idx = (Index)i.Data;
sqlite3DefaultRowEst(idx);
sqlite3DeleteIndexSamples(ctx, idx);
idx.Samples.data = null;
}
// Check to make sure the sqlite_stat1 table exists
AnalysisInfo sInfo = new AnalysisInfo();
sInfo.Ctx = ctx;
sInfo.Database = ctx.DBs[db].Name;
if (sqlite3FindTable(ctx, "sqlite_stat1", sInfo.Database) == null)
return RC.ERROR;
// Load new statistics out of the sqlite_stat1 table
string sql = C._mtagprintf(ctx, "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.Database);
if (sql == null)
rc = RC.NOMEM;
else
{
rc = Vdbe.Exec(ctx, sql, AnalysisLoader, sInfo, 0);
C._tagfree(ctx, ref sql);
}
// Load the statistics from the sqlite_stat3 table.
#if ENABLE_STAT3
if (rc == RC_OK)
{
bool lookasideEnabled = ctx.Lookaside.Enabled;
ctx.Lookaside.Enabled = false;
rc = LoadStat3(ctx, sInfo.Database);
ctx.Lookaside.Enabled = lookasideEnabled;
}
#endif
if (rc == RC.NOMEM)
db.MallocFailed = true;
return rc;
}
}
}
#endif
#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.AcceptanceTestsPaging
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for PagingOperations.
/// </summary>
public static partial class PagingOperationsExtensions
{
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetSinglePages(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetSinglePagesAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSinglePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesAsync(clientRequestId, pagingGetMultiplePagesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetOdataMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetOdataMultiplePagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetOdataMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetOdataMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesWithOffset(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesWithOffsetAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesWithOffsetAsync(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithOffsetWithHttpMessagesAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesRetryFirst(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesRetryFirstAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesRetrySecond(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesRetrySecondAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetSinglePagesFailure(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetSinglePagesFailureAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFailure(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFailureAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFailureUri(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFailureUriAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetSinglePagesNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetSinglePagesNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSinglePagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetOdataMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetOdataMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetOdataMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetOdataMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesWithOffsetNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesWithOffsetNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesWithOffsetNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesRetryFirstNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesRetryFirstNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesRetrySecondNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesRetrySecondNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetSinglePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetSinglePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFailureUriNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFailureUriNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Threading;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Processor;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
#pragma warning disable IDE0079 // remove unnecessary pragmas
#pragma warning disable IDE0063 // using can be simplified, we don't
namespace Thrift.Server
{
/// <summary>
/// Server that uses C# built-in ThreadPool to spawn threads when handling requests.
/// </summary>
public class TThreadPoolAsyncServer : TServer
{
private const int DEFAULT_MIN_THREADS = -1; // use .NET ThreadPool defaults
private const int DEFAULT_MAX_THREADS = -1; // use .NET ThreadPool defaults
private volatile bool stop = false;
private CancellationToken ServerCancellationToken;
public struct Configuration
{
public int MinWorkerThreads;
public int MaxWorkerThreads;
public int MinIOThreads;
public int MaxIOThreads;
public Configuration(int min = DEFAULT_MIN_THREADS, int max = DEFAULT_MAX_THREADS)
{
MinWorkerThreads = min;
MaxWorkerThreads = max;
MinIOThreads = min;
MaxIOThreads = max;
}
public Configuration(int minWork, int maxWork, int minIO, int maxIO)
{
MinWorkerThreads = minWork;
MaxWorkerThreads = maxWork;
MinIOThreads = minIO;
MaxIOThreads = maxIO;
}
}
public TThreadPoolAsyncServer(ITAsyncProcessor processor, TServerTransport serverTransport, ILogger logger = null)
: this(new TSingletonProcessorFactory(processor), serverTransport,
null, null, // defaults to TTransportFactory()
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
new Configuration(), logger)
{
}
public TThreadPoolAsyncServer(ITAsyncProcessor processor,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(new TSingletonProcessorFactory(processor), serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
new Configuration())
{
}
public TThreadPoolAsyncServer(ITProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(processorFactory, serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
new Configuration())
{
}
public TThreadPoolAsyncServer(ITProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
int minThreadPoolThreads, int maxThreadPoolThreads, ILogger logger = null)
: this(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory,
inputProtocolFactory, outputProtocolFactory,
new Configuration(minThreadPoolThreads, maxThreadPoolThreads),
logger)
{
}
public TThreadPoolAsyncServer(ITProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
Configuration threadConfig,
ILogger logger = null)
: base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory,
inputProtocolFactory, outputProtocolFactory, logger)
{
lock (typeof(TThreadPoolAsyncServer))
{
if ((threadConfig.MaxWorkerThreads > 0) || (threadConfig.MaxIOThreads > 0))
{
ThreadPool.GetMaxThreads(out int work, out int comm);
if (threadConfig.MaxWorkerThreads > 0)
work = threadConfig.MaxWorkerThreads;
if (threadConfig.MaxIOThreads > 0)
comm = threadConfig.MaxIOThreads;
if (!ThreadPool.SetMaxThreads(work, comm))
throw new Exception("Error: could not SetMaxThreads in ThreadPool");
}
if ((threadConfig.MinWorkerThreads > 0) || (threadConfig.MinIOThreads > 0))
{
ThreadPool.GetMinThreads(out int work, out int comm);
if (threadConfig.MinWorkerThreads > 0)
work = threadConfig.MinWorkerThreads;
if (threadConfig.MinIOThreads > 0)
comm = threadConfig.MinIOThreads;
if (!ThreadPool.SetMinThreads(work, comm))
throw new Exception("Error: could not SetMinThreads in ThreadPool");
}
}
}
/// <summary>
/// Use new ThreadPool thread for each new client connection.
/// </summary>
public override async Task ServeAsync(CancellationToken cancellationToken)
{
ServerCancellationToken = cancellationToken;
try
{
try
{
ServerTransport.Listen();
}
catch (TTransportException ttx)
{
LogError("Error, could not listen on ServerTransport: " + ttx);
return;
}
//Fire the preServe server event when server is up but before any client connections
if (ServerEventHandler != null)
await ServerEventHandler.PreServeAsync(cancellationToken);
while (!(stop || ServerCancellationToken.IsCancellationRequested))
{
try
{
TTransport client = await ServerTransport.AcceptAsync(cancellationToken);
_ = Task.Run(async () => await ExecuteAsync(client), cancellationToken); // intentionally ignoring retval
}
catch (TaskCanceledException)
{
stop = true;
}
catch (TTransportException ttx)
{
if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted)
{
LogError(ttx.ToString());
}
}
}
if (stop)
{
try
{
ServerTransport.Close();
}
catch (TTransportException ttx)
{
LogError("TServerTransport failed on close: " + ttx.Message);
}
stop = false;
}
}
finally
{
ServerCancellationToken = default;
}
}
/// <summary>
/// Loops on processing a client forever
/// client will be a TTransport instance
/// </summary>
/// <param name="client"></param>
private async Task ExecuteAsync(TTransport client)
{
var cancellationToken = ServerCancellationToken;
using (client)
{
ITAsyncProcessor processor = ProcessorFactory.GetAsyncProcessor(client, this);
TTransport inputTransport = null;
TTransport outputTransport = null;
TProtocol inputProtocol = null;
TProtocol outputProtocol = null;
object connectionContext = null;
try
{
try
{
inputTransport = InputTransportFactory.GetTransport(client);
outputTransport = OutputTransportFactory.GetTransport(client);
inputProtocol = InputProtocolFactory.GetProtocol(inputTransport);
outputProtocol = OutputProtocolFactory.GetProtocol(outputTransport);
//Recover event handler (if any) and fire createContext server event when a client connects
if (ServerEventHandler != null)
connectionContext = await ServerEventHandler.CreateContextAsync(inputProtocol, outputProtocol, cancellationToken);
//Process client requests until client disconnects
while (!(stop || cancellationToken.IsCancellationRequested))
{
if (!await inputTransport.PeekAsync(cancellationToken))
break;
//Fire processContext server event
//N.B. This is the pattern implemented in C++ and the event fires provisionally.
//That is to say it may be many minutes between the event firing and the client request
//actually arriving or the client may hang up without ever makeing a request.
if (ServerEventHandler != null)
await ServerEventHandler.ProcessContextAsync(connectionContext, inputTransport, cancellationToken);
//Process client request (blocks until transport is readable)
if (!await processor.ProcessAsync(inputProtocol, outputProtocol, cancellationToken))
break;
}
}
catch (TTransportException)
{
//Usually a client disconnect, expected
}
catch (Exception x)
{
//Unexpected
LogError("Error: " + x);
}
//Fire deleteContext server event after client disconnects
if (ServerEventHandler != null)
await ServerEventHandler.DeleteContextAsync(connectionContext, inputProtocol, outputProtocol, cancellationToken);
}
finally
{
//Close transports
inputTransport?.Close();
outputTransport?.Close();
// disposable stuff should be disposed
inputProtocol?.Dispose();
outputProtocol?.Dispose();
inputTransport?.Dispose();
outputTransport?.Dispose();
}
}
}
public override void Stop()
{
stop = true;
ServerTransport?.Close();
}
}
}
| |
using System.Text.RegularExpressions;
using System.Diagnostics;
using System;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI;
using Microsoft.Win32;
using WeifenLuo;
using System.ComponentModel;
namespace SoftLogik.Win
{
namespace UI
{
[Description("Data Aware MenuStrip Component")][ToolboxBitmap(typeof(SPMenuStrip), "SPMenuStrip")]public partial class SPMenuStrip
{
protected override void OnPaint(PaintEventArgs pe)
{
// Calling the base class OnPaint
base.OnPaint(pe);
}
private bool m_autoBuild = true;
public bool AutoBuildTree
{
get
{
return this.m_autoBuild;
}
set
{
this.m_autoBuild = value;
}
}
#region Data Binding
private CurrencyManager m_currencyManager = null;
private string m_ValueMember;
private string m_DisplayMember;
private object m_oDataSource;
[Category("Data")]public object DataSource
{
get
{
return m_oDataSource;
}
set
{
if (value == null)
{
this.m_currencyManager = null;
this.Items.Clear();
}
else
{
if (!(value is IList|| m_oDataSource is IListSource))
{
throw (new System.Exception("Invalid DataSource"));
}
else
{
if (value is IListSource)
{
IListSource myListSource = (IListSource) value;
if (myListSource.ContainsListCollection == true)
{
throw (new System.Exception("Invalid DataSource"));
}
}
this.m_oDataSource = value;
this.m_currencyManager = (CurrencyManager) (this.BindingContext[value]);
if (this.AutoBuildTree)
{
BuildTree();
}
}
}
}
} // end of DataSource property
[Category("Data")]public string ValueMember
{
get
{
return this.m_ValueMember;
}
set
{
this.m_ValueMember = value;
}
}
[Category("Data")]public string DisplayMember
{
get
{
return this.m_DisplayMember;
}
set
{
this.m_DisplayMember = value;
}
}
public object GetValue(int index)
{
IList innerList = this.m_currencyManager.List;
if (innerList != null)
{
if ((this.ValueMember != "") && (index >= 0 && 0 < innerList.Count))
{
PropertyDescriptor pdValueMember;
pdValueMember = this.m_currencyManager.GetItemProperties()[this.ValueMember];
return pdValueMember.GetValue(innerList[index]);
}
}
return null;
}
public object GetDisplay(int index)
{
IList innerList = this.m_currencyManager.List;
if (innerList != null)
{
if ((this.DisplayMember != "") && (index >= 0 && 0 < innerList.Count))
{
PropertyDescriptor pdDisplayMember;
pdDisplayMember = this.m_currencyManager.GetItemProperties()[this.ValueMember];
return pdDisplayMember.GetValue(innerList[index]);
}
}
return null;
}
#endregion
#region Building the Tree
private ArrayList treeGroups = new ArrayList();
public void BuildTree()
{
this.Items.Clear();
if ((this.m_currencyManager != null) && (this.m_currencyManager.List != null))
{
IList innerList = this.m_currencyManager.List;
ToolStripItemCollection currNode = this.Items;
int currGroupIndex = 0;
int currListIndex = 0;
if (this.treeGroups.Count > currGroupIndex)
{
SPTreeNodeGroup currGroup = (SPTreeNodeGroup) (treeGroups[currGroupIndex]);
SPMenuStripItem myFirstNode = null;
PropertyDescriptor pdGroupBy;
PropertyDescriptor pdValue;
PropertyDescriptor pdDisplay;
pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy];
pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember];
pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember];
string currGroupBy = null;
if (innerList.Count > currListIndex)
{
object currObject;
while (currListIndex < innerList.Count)
{
currObject = innerList[currListIndex];
if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy)
{
currGroupBy = pdGroupBy.GetValue(currObject).ToString();
myFirstNode = new SPMenuStripItem(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currListIndex]), currGroup.ImageIndex, currListIndex);
currNode.Add((ToolStripItem) myFirstNode);
}
else
{
AddMenuItems(currGroupIndex, ref currListIndex, this.Items, currGroup.GroupBy);
}
} // end while
} // end if
}
else
{
while (currListIndex < innerList.Count)
{
AddMenuItems(currGroupIndex, ref currListIndex, this.Items, "");
}
} // end else
} // end if
}
private void AddMenuItems(int currGroupIndex, ref int currentListIndex, ToolStripItemCollection currNodes, string prevGroupByField)
{
IList innerList = this.m_currencyManager.List;
System.ComponentModel.PropertyDescriptor pdPrevGroupBy = null;
string prevGroupByValue = null;
SPTreeNodeGroup currGroup;
if (prevGroupByField != "")
{
pdPrevGroupBy = this.m_currencyManager.GetItemProperties()[prevGroupByField];
}
currGroupIndex++;
if (treeGroups.Count > currGroupIndex)
{
currGroup = (SPTreeNodeGroup) (treeGroups[currGroupIndex]);
PropertyDescriptor pdGroupBy = null;
PropertyDescriptor pdValue = null;
PropertyDescriptor pdDisplay = null;
pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy];
pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember];
pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember];
string currGroupBy = null;
if (innerList.Count > currentListIndex)
{
if (pdPrevGroupBy != null)
{
prevGroupByValue = pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString();
}
SPMenuStripItem myFirstNode = null;
object currObject = null;
while ((currentListIndex < innerList.Count) && (pdPrevGroupBy != null) && (pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString() == prevGroupByValue))
{
currObject = innerList[currentListIndex];
if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy)
{
currGroupBy = pdGroupBy.GetValue(currObject).ToString();
myFirstNode = new SPMenuStripItem(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currentListIndex]), currGroup.ImageIndex, currentListIndex);
currNodes.Add(myFirstNode);
}
else
{
AddMenuItems(currGroupIndex, ref currentListIndex, this.Items, currGroup.GroupBy);
}
}
}
}
else
{
SPMenuStripItem myNewLeafNode;
object currObject = this.m_currencyManager.List[currentListIndex];
if ((this.DisplayMember != null) && (this.ValueMember != null) && (this.DisplayMember != "") && (this.ValueMember != ""))
{
PropertyDescriptor pdDisplayloc = this.m_currencyManager.GetItemProperties()[this.DisplayMember];
PropertyDescriptor pdValueloc = this.m_currencyManager.GetItemProperties()[this.ValueMember];
if (this.Tag == null)
{
myNewLeafNode = new SPMenuStripItem("", pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex);
}
else
{
myNewLeafNode = new SPMenuStripItem(this.Tag.ToString(), pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex);
}
}
else
{
myNewLeafNode = new SPMenuStripItem("", currentListIndex.ToString(), currObject, currObject, currentListIndex, currentListIndex);
}
currNodes.Add(myNewLeafNode);
currentListIndex++;
}
}
#endregion
}
[Description("Specify Grouping for a collection of Menu Items in MenuStrip")]public class SPMenuStripItemGroup
{
private string groupName;
private string groupByMember;
private string groupByDisplayMember;
private string groupByValueMember;
private int groupImageIndex;
public SPMenuStripItemGroup(string name, string groupBy, string displayMember, string valueMember, int imageIndex)
{
this.ImageIndex = imageIndex;
this.Name = name;
this.GroupBy = groupBy;
this.DisplayMember = displayMember;
this.ValueMember = valueMember;
}
public SPMenuStripItemGroup(string name, string groupBy) : this(name, groupBy, groupBy, groupBy, - 1)
{
}
public int ImageIndex
{
get
{
return groupImageIndex;
}
set
{
groupImageIndex = value;
}
}
public string Name
{
get
{
return groupName;
}
set
{
groupName = value;
}
}
public string GroupBy
{
get
{
return groupByMember;
}
set
{
groupByMember = value;
}
}
public string DisplayMember
{
get
{
return groupByDisplayMember;
}
set
{
groupByDisplayMember = value;
}
}
public string ValueMember
{
get
{
return groupByValueMember;
}
set
{
groupByValueMember = value;
}
}
}
[Description("A menu item in the MenuStrip")]public class SPMenuStripItem : ToolStripMenuItem
{
private string m_groupName;
private object m_value;
private object m_item;
private int m_position;
public SPMenuStripItem()
{
}
public SPMenuStripItem(string GroupName, string text, object item, object value, int imageIndex, int position)
{
this.GroupName = GroupName;
this.Text = text;
this.Item = item;
this.Value = value;
this.ImageIndex = imageIndex;
this.m_position = position;
}
public SPMenuStripItem(string groupName, string text, object item, object value, int position)
{
this.GroupName = groupName;
this.Text = text;
this.Item = item;
this.Value = value;
this.m_position = position;
}
public string GroupName
{
get
{
return m_groupName;
}
set
{
this.m_groupName = value;
}
}
public object Item
{
get
{
return m_item;
}
set
{
m_item = value;
}
}
public object Value
{
get
{
return m_value;
}
set
{
m_value = value;
}
}
public int Position
{
get
{
return m_position;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Primitives;
namespace Microsoft.Net.Http.Headers
{
/// <summary>
/// Represents the <c>Cache-Control</c> HTTP header.
/// </summary>
public class CacheControlHeaderValue
{
/// <summary>
/// A constant for the <c>public</c> cache-control directive.
/// </summary>
public static readonly string PublicString = "public";
/// <summary>
/// A constant for the <c>private</c> cache-control directive.
/// </summary>
public static readonly string PrivateString = "private";
/// <summary>
/// A constant for the <c>max-age</c> cache-control directive.
/// </summary>
public static readonly string MaxAgeString = "max-age";
/// <summary>
/// A constant for the <c>s-maxage</c> cache-control directive.
/// </summary>
public static readonly string SharedMaxAgeString = "s-maxage";
/// <summary>
/// A constant for the <c>no-cache</c> cache-control directive.
/// </summary>
public static readonly string NoCacheString = "no-cache";
/// <summary>
/// A constant for the <c>no-store</c> cache-control directive.
/// </summary>
public static readonly string NoStoreString = "no-store";
/// <summary>
/// A constant for the <c>max-stale</c> cache-control directive.
/// </summary>
public static readonly string MaxStaleString = "max-stale";
/// <summary>
/// A constant for the <c>min-fresh</c> cache-control directive.
/// </summary>
public static readonly string MinFreshString = "min-fresh";
/// <summary>
/// A constant for the <c>no-transform</c> cache-control directive.
/// </summary>
public static readonly string NoTransformString = "no-transform";
/// <summary>
/// A constant for the <c>only-if-cached</c> cache-control directive.
/// </summary>
public static readonly string OnlyIfCachedString = "only-if-cached";
/// <summary>
/// A constant for the <c>must-revalidate</c> cache-control directive.
/// </summary>
public static readonly string MustRevalidateString = "must-revalidate";
/// <summary>
/// A constant for the <c>proxy-revalidate</c> cache-control directive.
/// </summary>
public static readonly string ProxyRevalidateString = "proxy-revalidate";
// The Cache-Control header is special: It is a header supporting a list of values, but we represent the list
// as _one_ instance of CacheControlHeaderValue. I.e we set 'SupportsMultipleValues' to 'true' since it is
// OK to have multiple Cache-Control headers in a request/response message. However, after parsing all
// Cache-Control headers, only one instance of CacheControlHeaderValue is created (if all headers contain valid
// values, otherwise we may have multiple strings containing the invalid values).
private static readonly HttpHeaderParser<CacheControlHeaderValue> Parser
= new GenericHeaderParser<CacheControlHeaderValue>(true, GetCacheControlLength);
private static readonly Action<StringSegment> CheckIsValidTokenAction = CheckIsValidToken;
private bool _noCache;
private ICollection<StringSegment>? _noCacheHeaders;
private bool _noStore;
private TimeSpan? _maxAge;
private TimeSpan? _sharedMaxAge;
private bool _maxStale;
private TimeSpan? _maxStaleLimit;
private TimeSpan? _minFresh;
private bool _noTransform;
private bool _onlyIfCached;
private bool _public;
private bool _private;
private ICollection<StringSegment>? _privateHeaders;
private bool _mustRevalidate;
private bool _proxyRevalidate;
private IList<NameValueHeaderValue>? _extensions;
/// <summary>
/// Initializes a new instance of <see cref="CacheControlHeaderValue"/>.
/// </summary>
public CacheControlHeaderValue()
{
// This type is unique in that there is no single required parameter.
}
/// <summary>
/// Gets or sets a value for the <c>no-cache</c> directive.
/// <para>
/// Configuring no-cache indicates that the client must re-validate cached responses with the original server
/// before using it.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.1.4</remarks>
public bool NoCache
{
get { return _noCache; }
set { _noCache = value; }
}
/// <summary>
/// Gets a collection of field names in the "no-cache" directive in a cache-control header field on an HTTP response.
/// </summary>
public ICollection<StringSegment> NoCacheHeaders
{
get
{
if (_noCacheHeaders == null)
{
_noCacheHeaders = new ObjectCollection<StringSegment>(CheckIsValidTokenAction);
}
return _noCacheHeaders;
}
}
/// <summary>
/// Gets or sets a value for the <c>no-store</c> directive.
/// <para>
/// Configuring no-store indicates that the response may not be stored in any cache.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.1.5</remarks>
public bool NoStore
{
get { return _noStore; }
set { _noStore = value; }
}
/// <summary>
/// Gets or sets a value for the <c>max-age</c> directive.
/// <para>
/// max-age specifies the maximum amount of time the response is considered fresh.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.1.1</remarks>
public TimeSpan? MaxAge
{
get { return _maxAge; }
set { _maxAge = value; }
}
/// <summary>
/// Gets or sets a value for the <c>s-maxage</c> directive.
/// <para>
/// Overrides <see cref="MaxAge">max-age</see>, but only for shared caches (such as proxies).
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.2.9</remarks>
public TimeSpan? SharedMaxAge
{
get { return _sharedMaxAge; }
set { _sharedMaxAge = value; }
}
/// <summary>
/// Gets or sets a value that determines if the <c>max-stale</c> is included.
/// <para>
/// <c>max-stale</c> that the client will accept stale responses. The maximum tolerance for staleness
/// is specified by <see cref="MaxStaleLimit"/>.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.1.2</remarks>
public bool MaxStale
{
get { return _maxStale; }
set { _maxStale = value; }
}
/// <summary>
/// Gets or sets a value for the <c>max-stale</c> directive.
/// <para>
/// Indicates the maximum duration an HTTP client is willing to accept a response that has exceeded its expiration time.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.1.2</remarks>
public TimeSpan? MaxStaleLimit
{
get { return _maxStaleLimit; }
set { _maxStaleLimit = value; }
}
/// <summary>
/// Gets or sets a value for the <c>min-fresh</c> directive.
/// <para>
/// Indicates the freshness lifetime that an HTTP client is willing to accept a response.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.1.3</remarks>
public TimeSpan? MinFresh
{
get { return _minFresh; }
set { _minFresh = value; }
}
/// <summary>
/// Gets or sets a value for the <c>no-transform</c> request directive.
/// <para>
/// Forbids intermediate caches or proxies from editing the response payload.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.1.6</remarks>
public bool NoTransform
{
get { return _noTransform; }
set { _noTransform = value; }
}
/// <summary>
/// Gets or sets a value for the <c>only-if-cached</c> request directive.
/// <para>
/// Indicates that the client only wishes to obtain a stored response
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.1.7</remarks>
public bool OnlyIfCached
{
get { return _onlyIfCached; }
set { _onlyIfCached = value; }
}
/// <summary>
/// Gets or sets a value that determines if the <c>public</c> response directive is included.
/// <para>
/// Indicates that the response may be stored by any cache.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.2.5</remarks>
public bool Public
{
get { return _public; }
set { _public = value; }
}
/// <summary>
/// Gets or sets a value that determines if the <c>private</c> response directive is included.
/// <para>
/// Indicates that the response may not be stored by a shared cache.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.2.6</remarks>
public bool Private
{
get { return _private; }
set { _private = value; }
}
/// <summary>
/// Gets a collection of field names in the "private" directive in a cache-control header field on an HTTP response.
/// </summary>
public ICollection<StringSegment> PrivateHeaders
{
get
{
if (_privateHeaders == null)
{
_privateHeaders = new ObjectCollection<StringSegment>(CheckIsValidTokenAction);
}
return _privateHeaders;
}
}
/// <summary>
/// Gets or sets a value that determines if the <c>must-revalidate</c> response directive is included.
/// <para>
/// Indicates that caches must revalidate the use of stale caches with the origin server before their use.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.2.1</remarks>
public bool MustRevalidate
{
get { return _mustRevalidate; }
set { _mustRevalidate = value; }
}
/// <summary>
/// Gets or sets a value that determines if the <c>proxy-validate</c> response directive is included.
/// <para>
/// Indicates that shared caches must revalidate the use of stale caches with the origin server before their use.
/// </para>
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc7234#section-5.2.2.1</remarks>
public bool ProxyRevalidate
{
get { return _proxyRevalidate; }
set { _proxyRevalidate = value; }
}
/// <summary>
/// Gets cache-extension tokens, each with an optional assigned value.
/// </summary>
public IList<NameValueHeaderValue> Extensions
{
get
{
if (_extensions == null)
{
_extensions = new ObjectCollection<NameValueHeaderValue>();
}
return _extensions;
}
}
/// <inheritdoc />
public override string ToString()
{
var sb = new StringBuilder();
AppendValueIfRequired(sb, _noStore, NoStoreString);
AppendValueIfRequired(sb, _noTransform, NoTransformString);
AppendValueIfRequired(sb, _onlyIfCached, OnlyIfCachedString);
AppendValueIfRequired(sb, _public, PublicString);
AppendValueIfRequired(sb, _mustRevalidate, MustRevalidateString);
AppendValueIfRequired(sb, _proxyRevalidate, ProxyRevalidateString);
if (_noCache)
{
AppendValueWithSeparatorIfRequired(sb, NoCacheString);
if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0))
{
sb.Append("=\"");
AppendValues(sb, _noCacheHeaders);
sb.Append('\"');
}
}
if (_maxAge.HasValue)
{
AppendValueWithSeparatorIfRequired(sb, MaxAgeString);
sb.Append('=');
sb.Append(((int)_maxAge.GetValueOrDefault().TotalSeconds).ToString(NumberFormatInfo.InvariantInfo));
}
if (_sharedMaxAge.HasValue)
{
AppendValueWithSeparatorIfRequired(sb, SharedMaxAgeString);
sb.Append('=');
sb.Append(((int)_sharedMaxAge.GetValueOrDefault().TotalSeconds).ToString(NumberFormatInfo.InvariantInfo));
}
if (_maxStale)
{
AppendValueWithSeparatorIfRequired(sb, MaxStaleString);
if (_maxStaleLimit.HasValue)
{
sb.Append('=');
sb.Append(((int)_maxStaleLimit.GetValueOrDefault().TotalSeconds).ToString(NumberFormatInfo.InvariantInfo));
}
}
if (_minFresh.HasValue)
{
AppendValueWithSeparatorIfRequired(sb, MinFreshString);
sb.Append('=');
sb.Append(((int)_minFresh.GetValueOrDefault().TotalSeconds).ToString(NumberFormatInfo.InvariantInfo));
}
if (_private)
{
AppendValueWithSeparatorIfRequired(sb, PrivateString);
if ((_privateHeaders != null) && (_privateHeaders.Count > 0))
{
sb.Append("=\"");
AppendValues(sb, _privateHeaders);
sb.Append('\"');
}
}
NameValueHeaderValue.ToString(_extensions, ',', false, sb);
return sb.ToString();
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
var other = obj as CacheControlHeaderValue;
if (other == null)
{
return false;
}
if ((_noCache != other._noCache) || (_noStore != other._noStore) || (_maxAge != other._maxAge) ||
(_sharedMaxAge != other._sharedMaxAge) || (_maxStale != other._maxStale) ||
(_maxStaleLimit != other._maxStaleLimit) || (_minFresh != other._minFresh) ||
(_noTransform != other._noTransform) || (_onlyIfCached != other._onlyIfCached) ||
(_public != other._public) || (_private != other._private) ||
(_mustRevalidate != other._mustRevalidate) || (_proxyRevalidate != other._proxyRevalidate))
{
return false;
}
if (!HeaderUtilities.AreEqualCollections(_noCacheHeaders, other._noCacheHeaders,
StringSegmentComparer.OrdinalIgnoreCase))
{
return false;
}
if (!HeaderUtilities.AreEqualCollections(_privateHeaders, other._privateHeaders,
StringSegmentComparer.OrdinalIgnoreCase))
{
return false;
}
if (!HeaderUtilities.AreEqualCollections(_extensions, other._extensions))
{
return false;
}
return true;
}
/// <inheritdoc />
public override int GetHashCode()
{
// Use a different bit for bool fields: bool.GetHashCode() will return 0 (false) or 1 (true). So we would
// end up having the same hash code for e.g. two instances where one has only noCache set and the other
// only noStore.
int result = _noCache.GetHashCode() ^ (_noStore.GetHashCode() << 1) ^ (_maxStale.GetHashCode() << 2) ^
(_noTransform.GetHashCode() << 3) ^ (_onlyIfCached.GetHashCode() << 4) ^
(_public.GetHashCode() << 5) ^ (_private.GetHashCode() << 6) ^
(_mustRevalidate.GetHashCode() << 7) ^ (_proxyRevalidate.GetHashCode() << 8);
// XOR the hashcode of timespan values with different numbers to make sure two instances with the same
// timespan set on different fields result in different hashcodes.
result = result ^ (_maxAge.HasValue ? _maxAge.GetValueOrDefault().GetHashCode() ^ 1 : 0) ^
(_sharedMaxAge.HasValue ? _sharedMaxAge.GetValueOrDefault().GetHashCode() ^ 2 : 0) ^
(_maxStaleLimit.HasValue ? _maxStaleLimit.GetValueOrDefault().GetHashCode() ^ 4 : 0) ^
(_minFresh.HasValue ? _minFresh.GetValueOrDefault().GetHashCode() ^ 8 : 0);
if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0))
{
foreach (var noCacheHeader in _noCacheHeaders)
{
result = result ^ StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(noCacheHeader);
}
}
if ((_privateHeaders != null) && (_privateHeaders.Count > 0))
{
foreach (var privateHeader in _privateHeaders)
{
result = result ^ StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(privateHeader);
}
}
if ((_extensions != null) && (_extensions.Count > 0))
{
foreach (var extension in _extensions)
{
result = result ^ extension.GetHashCode();
}
}
return result;
}
/// <summary>
/// Parses <paramref name="input"/> as a <see cref="CacheControlHeaderValue"/> value.
/// </summary>
/// <param name="input">The values to parse.</param>
/// <returns>The parsed values.</returns>
public static CacheControlHeaderValue Parse(StringSegment input)
{
var index = 0;
// Cache-Control is unusual because there are no required values so the parser will succeed for an empty string, but still return null.
var result = Parser.ParseValue(input, ref index);
if (result == null)
{
throw new FormatException("No cache directives found.");
}
return result;
}
/// <summary>
/// Attempts to parse the specified <paramref name="input"/> as a <see cref="CacheControlHeaderValue"/>.
/// </summary>
/// <param name="input">The value to parse.</param>
/// <param name="parsedValue">The parsed value.</param>
/// <returns><see langword="true"/> if input is a valid <see cref="SetCookieHeaderValue"/>, otherwise <see langword="false"/>.</returns>
public static bool TryParse(StringSegment input, [NotNullWhen(true)] out CacheControlHeaderValue? parsedValue)
{
var index = 0;
// Cache-Control is unusual because there are no required values so the parser will succeed for an empty string, but still return null.
if (Parser.TryParseValue(input, ref index, out parsedValue) && parsedValue != null)
{
return true;
}
parsedValue = null;
return false;
}
private static int GetCacheControlLength(StringSegment input, int startIndex, out CacheControlHeaderValue? parsedValue)
{
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Cache-Control header consists of a list of name/value pairs, where the value is optional. So use an
// instance of NameValueHeaderParser to parse the string.
var current = startIndex;
var nameValueList = new List<NameValueHeaderValue>();
while (current < input.Length)
{
if (!NameValueHeaderValue.MultipleValueParser.TryParseValue(input, ref current, out var nameValue))
{
return 0;
}
if (nameValue != null)
{
nameValueList.Add(nameValue);
}
}
// If we get here, we were able to successfully parse the string as list of name/value pairs. Now analyze
// the name/value pairs.
// Cache-Control is a header supporting lists of values. However, expose the header as an instance of
// CacheControlHeaderValue.
var result = new CacheControlHeaderValue();
if (!TrySetCacheControlValues(result, nameValueList))
{
return 0;
}
parsedValue = result;
// If we get here we successfully parsed the whole string.
return input.Length - startIndex;
}
private static bool TrySetCacheControlValues(
CacheControlHeaderValue cc,
List<NameValueHeaderValue> nameValueList)
{
for (var i = 0; i < nameValueList.Count; i++)
{
var nameValue = nameValueList[i];
var name = nameValue.Name;
var success = true;
switch (name.Length)
{
case 6:
if (StringSegment.Equals(PublicString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTokenOnlyValue(nameValue, ref cc._public);
}
else
{
goto default;
}
break;
case 7:
if (StringSegment.Equals(MaxAgeString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTimeSpan(nameValue, ref cc._maxAge);
}
else if(StringSegment.Equals(PrivateString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetOptionalTokenList(nameValue, ref cc._private, ref cc._privateHeaders);
}
else
{
goto default;
}
break;
case 8:
if (StringSegment.Equals(NoCacheString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetOptionalTokenList(nameValue, ref cc._noCache, ref cc._noCacheHeaders);
}
else if (StringSegment.Equals(NoStoreString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTokenOnlyValue(nameValue, ref cc._noStore);
}
else if (StringSegment.Equals(SharedMaxAgeString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTimeSpan(nameValue, ref cc._sharedMaxAge);
}
else
{
goto default;
}
break;
case 9:
if (StringSegment.Equals(MaxStaleString, name, StringComparison.OrdinalIgnoreCase))
{
success = ((nameValue.Value == null) || TrySetTimeSpan(nameValue, ref cc._maxStaleLimit));
if (success)
{
cc._maxStale = true;
}
}
else if (StringSegment.Equals(MinFreshString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTimeSpan(nameValue, ref cc._minFresh);
}
else
{
goto default;
}
break;
case 12:
if (StringSegment.Equals(NoTransformString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTokenOnlyValue(nameValue, ref cc._noTransform);
}
else
{
goto default;
}
break;
case 14:
if (StringSegment.Equals(OnlyIfCachedString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTokenOnlyValue(nameValue, ref cc._onlyIfCached);
}
else
{
goto default;
}
break;
case 15:
if (StringSegment.Equals(MustRevalidateString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTokenOnlyValue(nameValue, ref cc._mustRevalidate);
}
else
{
goto default;
}
break;
case 16:
if (StringSegment.Equals(ProxyRevalidateString, name, StringComparison.OrdinalIgnoreCase))
{
success = TrySetTokenOnlyValue(nameValue, ref cc._proxyRevalidate);
}
else
{
goto default;
}
break;
default:
cc.Extensions.Add(nameValue); // success is always true
break;
}
if (!success)
{
return false;
}
}
return true;
}
private static bool TrySetTokenOnlyValue(NameValueHeaderValue nameValue, ref bool boolField)
{
if (nameValue.Value != null)
{
return false;
}
boolField = true;
return true;
}
private static bool TrySetOptionalTokenList(
NameValueHeaderValue nameValue,
ref bool boolField,
ref ICollection<StringSegment>? destination)
{
if (nameValue.Value == null)
{
boolField = true;
return true;
}
// We need the string to be at least 3 chars long: 2x quotes and at least 1 character. Also make sure we
// have a quoted string. Note that NameValueHeaderValue will never have leading/trailing whitespaces.
var valueString = nameValue.Value;
if ((valueString.Length < 3) || (valueString[0] != '\"') || (valueString[valueString.Length - 1] != '\"'))
{
return false;
}
// We have a quoted string. Now verify that the string contains a list of valid tokens separated by ','.
var current = 1; // skip the initial '"' character.
var maxLength = valueString.Length - 1; // -1 because we don't want to parse the final '"'.
var separatorFound = false;
var originalValueCount = destination == null ? 0 : destination.Count;
while (current < maxLength)
{
current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(valueString, current, true,
out separatorFound);
if (current == maxLength)
{
break;
}
var tokenLength = HttpRuleParser.GetTokenLength(valueString, current);
if (tokenLength == 0)
{
// We already skipped whitespaces and separators. If we don't have a token it must be an invalid
// character.
return false;
}
if (destination == null)
{
destination = new ObjectCollection<StringSegment>(CheckIsValidTokenAction);
}
destination.Add(valueString.Subsegment(current, tokenLength));
current = current + tokenLength;
}
// After parsing a valid token list, we expect to have at least one value
if ((destination != null) && (destination.Count > originalValueCount))
{
boolField = true;
return true;
}
return false;
}
private static bool TrySetTimeSpan(NameValueHeaderValue nameValue, ref TimeSpan? timeSpan)
{
if (nameValue.Value == null)
{
return false;
}
int seconds;
if (!HeaderUtilities.TryParseNonNegativeInt32(nameValue.Value, out seconds))
{
return false;
}
timeSpan = new TimeSpan(0, 0, seconds);
return true;
}
private static void AppendValueIfRequired(StringBuilder sb, bool appendValue, string value)
{
if (appendValue)
{
AppendValueWithSeparatorIfRequired(sb, value);
}
}
private static void AppendValueWithSeparatorIfRequired(StringBuilder sb, string value)
{
if (sb.Length > 0)
{
sb.Append(", ");
}
sb.Append(value);
}
private static void AppendValues(StringBuilder sb, IEnumerable<StringSegment> values)
{
var first = true;
foreach (var value in values)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.Append(value.AsSpan());
}
}
private static void CheckIsValidToken(StringSegment item)
{
HeaderUtilities.CheckValidToken(item, nameof(item));
}
}
}
| |
#region Using directives
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Security.Principal;
using System.Management.Automation.SecurityAccountsManager;
using System.Management.Automation.SecurityAccountsManager.Extensions;
using Microsoft.PowerShell.LocalAccounts;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The Remove-LocalGroupMember cmdlet removes one or more members (users or
/// groups) from a local security group.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "LocalGroupMember",
SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717989")]
[Alias("rlgm")]
public class RemoveLocalGroupMemberCommand : PSCmdlet
{
#region Instance Data
private Sam sam = null;
#endregion Instance Data
#region Parameter Properties
/// <summary>
/// The following is the definition of the input parameter "Group".
/// Specifies a security group from the local Security Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ParameterSetName = "Group")]
[ValidateNotNull]
public Microsoft.PowerShell.Commands.LocalGroup Group
{
get { return this.group;}
set { this.group = value; }
}
private Microsoft.PowerShell.Commands.LocalGroup group;
/// <summary>
/// The following is the definition of the input parameter "Member".
/// Specifies one or more users or groups to remove from this local group. You can
/// identify users or groups by specifying their names or SIDs, or by passing
/// Microsoft.PowerShell.Commands.LocalPrincipal objects.
/// </summary>
[Parameter(Mandatory = true,
Position = 1,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Microsoft.PowerShell.Commands.LocalPrincipal[] Member
{
get { return this.member;}
set { this.member = value; }
}
private Microsoft.PowerShell.Commands.LocalPrincipal[] member;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// The security group from the local Security Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ParameterSetName = "Default")]
[ValidateNotNullOrEmpty]
public string Name
{
get { return this.name;}
set { this.name = value; }
}
private string name;
/// <summary>
/// The following is the definition of the input parameter "SID".
/// Specifies a security group from the local Security Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ParameterSetName = "SecurityIdentifier")]
[ValidateNotNull]
public System.Security.Principal.SecurityIdentifier SID
{
get { return this.sid;}
set { this.sid = value; }
}
private System.Security.Principal.SecurityIdentifier sid;
#endregion Parameter Properties
#region Cmdlet Overrides
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
sam = new Sam();
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
try
{
if (Group != null)
ProcessGroup(Group);
else if (Name != null)
ProcessName(Name);
else if (SID != null)
ProcessSid(SID);
}
catch (GroupNotFoundException ex)
{
WriteError(ex.MakeErrorRecord());
}
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
if (sam != null)
{
sam.Dispose();
sam = null;
}
}
#endregion Cmdlet Overrides
#region Private Methods
/// <summary>
/// Creates a list of <see cref="LocalPrincipal"/> objects
/// ready to be processed by the cmdlet.
/// </summary>
/// <param name="groupId">
/// Name or SID (as a string) of the group we'll be removing from.
/// This string is used primarily for specifying the target
/// in WhatIf scenarios.
/// </param>
/// <param name="member">
/// LocalPrincipal object to be processed
/// </param>
/// <returns>
/// LocalPrincipal object processed and ready to be removed
/// </returns>
/// <remarks>
/// <para>
/// LocalPrincipal object in the Member parameter may not be complete,
/// particularly those created from a name or a SID string given to the
/// Member cmdlet parameter. The object returned from this method contains at the very least, contain a valid SID.
/// </para>
/// <para>
/// Any Member object provided by name or SID string will be looked up
/// to ensure that such an object exists. If an object is not found,
/// an error message is displayed by PowerShell and null will be returned from this method
/// </para>
/// <para>
/// This method also handles the WhatIf scenario. If the Cmdlet's
/// <b>ShouldProcess</b> method returns false on any Member object
/// </para>
/// </remarks>
private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member)
{
LocalPrincipal principal = null;
// if the member has a SID, we can use it directly
if (member.SID != null)
{
principal = member;
}
else // otherwise it must have been constructed by name
{
SecurityIdentifier sid = this.TrySid(member.Name);
if (sid != null)
{
member.SID = sid;
principal = member;
}
else
{
try
{
principal = sam.LookupAccount(member.Name);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
if (CheckShouldProcess(principal, groupId))
return principal;
return null;
}
/// <summary>
/// Determine if a principal should be processed.
/// Just a wrapper around Cmdlet.ShouldProcess, with localized string
/// formatting.
/// </summary>
/// <param name="principal">Name of the principal to be removed.</param>
/// <param name="groupName">
/// Name of the group from which the members will be removed.
/// </param>
/// <returns>
/// True if the principal should be processed, false otherwise.
/// </returns>
private bool CheckShouldProcess(LocalPrincipal principal, string groupName)
{
if (principal == null)
return false;
string msg = StringUtil.Format(Strings.ActionRemoveGroupMember, principal.ToString());
return ShouldProcess(groupName, msg);
}
/// <summary>
/// Remove members from a group.
/// </summary>
/// <param name="group">
/// A <see cref="LocalGroup"/> object representing the group from which
/// the members will be removed.
/// </param>
private void ProcessGroup(LocalGroup group)
{
string groupId = group.Name ?? group.SID.ToString();
foreach (var member in this.Member)
{
LocalPrincipal principal = MakePrincipal(groupId, member);
if (null != principal)
{
var ex = sam.RemoveLocalGroupMember(group, principal);
if (null != ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
/// <summary>
/// Remove members from a group specified by name.
/// </summary>
/// <param name="name">
/// The name of the group from which the members will be removed.
/// </param>
private void ProcessName(string name)
{
ProcessGroup(sam.GetLocalGroup(name));
}
/// <summary>
/// Remove members from a group specified by SID.
/// </summary>
/// <param name="groupSid">
/// A <see cref="SecurityIdentifier"/> object identifying the group
/// from which the members will be removed.
/// </param>
private void ProcessSid(SecurityIdentifier groupSid)
{
foreach (var member in this.Member)
{
LocalPrincipal principal = MakePrincipal(groupSid.ToString(), member);
if (null != principal)
{
var ex = sam.RemoveLocalGroupMember(groupSid, principal);
if (null != ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
#endregion Private Methods
}//End Class
}//End namespace
| |
/*
* 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.IO;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
{
public class LLRAW : ITerrainLoader
{
public struct HeightmapLookupValue : IComparable<HeightmapLookupValue>
{
public ushort Index;
public float Value;
public HeightmapLookupValue(ushort index, float value)
{
Index = index;
Value = value;
}
public int CompareTo(HeightmapLookupValue val)
{
return Value.CompareTo(val.Value);
}
}
/// <summary>Lookup table to speed up terrain exports</summary>
HeightmapLookupValue[] LookupHeightTable;
public LLRAW()
{
LookupHeightTable = new HeightmapLookupValue[256 * 256];
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
LookupHeightTable[i + (j * 256)] = new HeightmapLookupValue((ushort)(i + (j * 256)), (float)((double)i * ((double)j / 128.0d)));
}
}
Array.Sort<HeightmapLookupValue>(LookupHeightTable);
}
#region ITerrainLoader Members
public ITerrainChannel LoadFile(string filename)
{
FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Open, FileAccess.Read);
ITerrainChannel retval = LoadStream(s);
s.Close();
return retval;
}
public ITerrainChannel LoadFile(string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int sectionWidth, int sectionHeight)
{
TerrainChannel retval = new TerrainChannel(sectionWidth, sectionHeight);
FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Open, FileAccess.Read);
BinaryReader bs = new BinaryReader(s);
int currFileYOffset = fileHeight - 1;
// if our region isn't on the first Y section of the areas to be landscaped, then
// advance to our section of the file
while (currFileYOffset > offsetY)
{
// read a whole strip of regions
int heightsToRead = sectionHeight * (fileWidth * sectionWidth);
bs.ReadBytes(heightsToRead * 13); // because there are 13 fun channels
currFileYOffset--;
}
// got to the Y start offset within the file of our region
// so read the file bits associated with our region
int y;
// for each Y within our Y offset
for (y = sectionHeight - 1; y >= 0; y--)
{
int currFileXOffset = 0;
// if our region isn't the first X section of the areas to be landscaped, then
// advance the stream to the X start pos of our section in the file
// i.e. eat X upto where we start
while (currFileXOffset < offsetX)
{
bs.ReadBytes(sectionWidth * 13);
currFileXOffset++;
}
// got to our X offset, so write our regions X line
int x;
for (x = 0; x < sectionWidth; x++)
{
// Read a strip and continue
retval[x, y] = bs.ReadByte() * (bs.ReadByte() / 128.0);
bs.ReadBytes(11);
}
// record that we wrote it
currFileXOffset++;
// if our region isn't the last X section of the areas to be landscaped, then
// advance the stream to the end of this Y column
while (currFileXOffset < fileWidth)
{
// eat the next regions x line
bs.ReadBytes(sectionWidth * 13); //The 13 channels again
currFileXOffset++;
}
}
bs.Close();
s.Close();
return retval;
}
public ITerrainChannel LoadStream(Stream s)
{
TerrainChannel retval = new TerrainChannel();
BinaryReader bs = new BinaryReader(s);
int y;
for (y = 0; y < retval.Height; y++)
{
int x;
for (x = 0; x < retval.Width; x++)
{
retval[x, (retval.Height - 1) - y] = bs.ReadByte() * (bs.ReadByte() / 128.0);
bs.ReadBytes(11); // Advance the stream to next bytes.
}
}
bs.Close();
return retval;
}
public void SaveFile(string filename, ITerrainChannel map)
{
FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write);
SaveStream(s, map);
s.Close();
}
public void SaveStream(Stream s, ITerrainChannel map)
{
BinaryWriter binStream = new BinaryWriter(s);
// Output the calculated raw
for (int y = 0; y < map.Height; y++)
{
for (int x = 0; x < map.Width; x++)
{
double t = map[x, (map.Height - 1) - y];
//if height is less than 0, set it to 0 as
//can't save -ve values in a LLRAW file
if (t < 0d)
{
t = 0d;
}
int index = 0;
// The lookup table is pre-sorted, so we either find an exact match or
// the next closest (smaller) match with a binary search
index = Array.BinarySearch<HeightmapLookupValue>(LookupHeightTable, new HeightmapLookupValue(0, (float)t));
if (index < 0)
index = ~index - 1;
index = LookupHeightTable[index].Index;
byte red = (byte) (index & 0xFF);
byte green = (byte) ((index >> 8) & 0xFF);
const byte blue = 20;
const byte alpha1 = 0;
const byte alpha2 = 0;
const byte alpha3 = 0;
const byte alpha4 = 0;
const byte alpha5 = 255;
const byte alpha6 = 255;
const byte alpha7 = 255;
const byte alpha8 = 255;
byte alpha9 = red;
byte alpha10 = green;
binStream.Write(red);
binStream.Write(green);
binStream.Write(blue);
binStream.Write(alpha1);
binStream.Write(alpha2);
binStream.Write(alpha3);
binStream.Write(alpha4);
binStream.Write(alpha5);
binStream.Write(alpha6);
binStream.Write(alpha7);
binStream.Write(alpha8);
binStream.Write(alpha9);
binStream.Write(alpha10);
}
}
binStream.Close();
}
public string FileExtension
{
get { return ".raw"; }
}
#endregion
public override string ToString()
{
return "LL/SL RAW";
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gctv = Google.Cloud.Talent.V4Beta1;
using sys = System;
namespace Google.Cloud.Talent.V4Beta1
{
/// <summary>Resource name for the <c>Tenant</c> resource.</summary>
public sealed partial class TenantName : gax::IResourceName, sys::IEquatable<TenantName>
{
/// <summary>The possible contents of <see cref="TenantName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/tenants/{tenant}</c>.</summary>
ProjectTenant = 1,
}
private static gax::PathTemplate s_projectTenant = new gax::PathTemplate("projects/{project}/tenants/{tenant}");
/// <summary>Creates a <see cref="TenantName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="TenantName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static TenantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TenantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="TenantName"/> with the pattern <c>projects/{project}/tenants/{tenant}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TenantName"/> constructed from the provided ids.</returns>
public static TenantName FromProjectTenant(string projectId, string tenantId) =>
new TenantName(ResourceNameType.ProjectTenant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), tenantId: gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TenantName"/> with pattern
/// <c>projects/{project}/tenants/{tenant}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TenantName"/> with pattern
/// <c>projects/{project}/tenants/{tenant}</c>.
/// </returns>
public static string Format(string projectId, string tenantId) => FormatProjectTenant(projectId, tenantId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TenantName"/> with pattern
/// <c>projects/{project}/tenants/{tenant}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TenantName"/> with pattern
/// <c>projects/{project}/tenants/{tenant}</c>.
/// </returns>
public static string FormatProjectTenant(string projectId, string tenantId) =>
s_projectTenant.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)));
/// <summary>Parses the given resource name string into a new <see cref="TenantName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/tenants/{tenant}</c></description></item>
/// </list>
/// </remarks>
/// <param name="tenantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TenantName"/> if successful.</returns>
public static TenantName Parse(string tenantName) => Parse(tenantName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TenantName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/tenants/{tenant}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tenantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="TenantName"/> if successful.</returns>
public static TenantName Parse(string tenantName, bool allowUnparsed) =>
TryParse(tenantName, allowUnparsed, out TenantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TenantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/tenants/{tenant}</c></description></item>
/// </list>
/// </remarks>
/// <param name="tenantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TenantName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string tenantName, out TenantName result) => TryParse(tenantName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TenantName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/tenants/{tenant}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tenantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TenantName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string tenantName, bool allowUnparsed, out TenantName result)
{
gax::GaxPreconditions.CheckNotNull(tenantName, nameof(tenantName));
gax::TemplatedResourceName resourceName;
if (s_projectTenant.TryParseName(tenantName, out resourceName))
{
result = FromProjectTenant(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(tenantName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TenantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string tenantId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
TenantId = tenantId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TenantName"/> class from the component parts of pattern
/// <c>projects/{project}/tenants/{tenant}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param>
public TenantName(string projectId, string tenantId) : this(ResourceNameType.ProjectTenant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), tenantId: gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Tenant</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TenantId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectTenant: return s_projectTenant.Expand(ProjectId, TenantId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as TenantName);
/// <inheritdoc/>
public bool Equals(TenantName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TenantName a, TenantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TenantName a, TenantName b) => !(a == b);
}
public partial class Tenant
{
/// <summary>
/// <see cref="gctv::TenantName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::TenantName TenantName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::TenantName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace ZXing.Common.Detector
{
/// <summary>
/// Detects a candidate barcode-like rectangular region within an image. It
/// starts around the center of the image, increases the size of the candidate
/// region until it finds a white rectangular region. By keeping track of the
/// last black points it encountered, it determines the corners of the barcode.
/// </summary>
/// <author>David Olivier</author>
public sealed class WhiteRectangleDetector
{
private const int INIT_SIZE = 10;
private const int CORR = 1;
private readonly BitMatrix image;
private readonly int height;
private readonly int width;
private readonly int leftInit;
private readonly int rightInit;
private readonly int downInit;
private readonly int upInit;
/// <summary>
/// Creates a WhiteRectangleDetector instance
/// </summary>
/// <param name="image">The image.</param>
/// <returns>null, if image is too small, otherwise a WhiteRectangleDetector instance</returns>
public static WhiteRectangleDetector Create(BitMatrix image)
{
if (image == null)
return null;
var instance = new WhiteRectangleDetector(image);
if (instance.upInit < 0 || instance.leftInit < 0 || instance.downInit >= instance.height || instance.rightInit >= instance.width)
{
return null;
}
return instance;
}
/// <summary>
/// Creates a WhiteRectangleDetector instance
/// </summary>
/// <param name="image">barcode image to find a rectangle in</param>
/// <param name="initSize">initial size of search area around center</param>
/// <param name="x">x position of search center</param>
/// <param name="y">y position of search center</param>
/// <returns>
/// null, if image is too small, otherwise a WhiteRectangleDetector instance
/// </returns>
public static WhiteRectangleDetector Create(BitMatrix image, int initSize, int x, int y)
{
var instance = new WhiteRectangleDetector(image, initSize, x, y);
if (instance.upInit < 0 || instance.leftInit < 0 || instance.downInit >= instance.height || instance.rightInit >= instance.width)
{
return null;
}
return instance;
}
/// <summary>
/// Initializes a new instance of the <see cref="WhiteRectangleDetector"/> class.
/// </summary>
/// <param name="image">The image.</param>
/// <exception cref="ArgumentException">if image is too small</exception>
internal WhiteRectangleDetector(BitMatrix image)
: this(image, INIT_SIZE, image.Width / 2, image.Height / 2)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WhiteRectangleDetector"/> class.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="initSize">Size of the init.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
internal WhiteRectangleDetector(BitMatrix image, int initSize, int x, int y)
{
this.image = image;
height = image.Height;
width = image.Width;
int halfsize = initSize / 2;
leftInit = x - halfsize;
rightInit = x + halfsize;
upInit = y - halfsize;
downInit = y + halfsize;
}
/// <summary>
/// Detects a candidate barcode-like rectangular region within an image. It
/// starts around the center of the image, increases the size of the candidate
/// region until it finds a white rectangular region.
/// </summary>
/// <returns><see cref="ResultPoint" />[] describing the corners of the rectangular
/// region. The first and last points are opposed on the diagonal, as
/// are the second and third. The first point will be the topmost
/// point and the last, the bottommost. The second point will be
/// leftmost and the third, the rightmost</returns>
public ResultPoint[] detect()
{
int left = leftInit;
int right = rightInit;
int up = upInit;
int down = downInit;
bool sizeExceeded = false;
bool aBlackPointFoundOnBorder = true;
bool atLeastOneBlackPointFoundOnRight = false;
bool atLeastOneBlackPointFoundOnBottom = false;
bool atLeastOneBlackPointFoundOnLeft = false;
bool atLeastOneBlackPointFoundOnTop = false;
while (aBlackPointFoundOnBorder)
{
aBlackPointFoundOnBorder = false;
// .....
// . |
// .....
bool rightBorderNotWhite = true;
while ((rightBorderNotWhite || !atLeastOneBlackPointFoundOnRight) && right < width)
{
rightBorderNotWhite = containsBlackPoint(up, down, right, false);
if (rightBorderNotWhite)
{
right++;
aBlackPointFoundOnBorder = true;
atLeastOneBlackPointFoundOnRight = true;
}
else if (!atLeastOneBlackPointFoundOnRight)
{
right++;
}
}
if (right >= width)
{
sizeExceeded = true;
break;
}
// .....
// . .
// .___.
bool bottomBorderNotWhite = true;
while ((bottomBorderNotWhite || !atLeastOneBlackPointFoundOnBottom) && down < height)
{
bottomBorderNotWhite = containsBlackPoint(left, right, down, true);
if (bottomBorderNotWhite)
{
down++;
aBlackPointFoundOnBorder = true;
atLeastOneBlackPointFoundOnBottom = true;
}
else if (!atLeastOneBlackPointFoundOnBottom)
{
down++;
}
}
if (down >= height)
{
sizeExceeded = true;
break;
}
// .....
// | .
// .....
bool leftBorderNotWhite = true;
while ((leftBorderNotWhite || !atLeastOneBlackPointFoundOnLeft) && left >= 0)
{
leftBorderNotWhite = containsBlackPoint(up, down, left, false);
if (leftBorderNotWhite)
{
left--;
aBlackPointFoundOnBorder = true;
atLeastOneBlackPointFoundOnLeft = true;
}
else if (!atLeastOneBlackPointFoundOnLeft)
{
left--;
}
}
if (left < 0)
{
sizeExceeded = true;
break;
}
// .___.
// . .
// .....
bool topBorderNotWhite = true;
while ((topBorderNotWhite || !atLeastOneBlackPointFoundOnTop) && up >= 0)
{
topBorderNotWhite = containsBlackPoint(left, right, up, true);
if (topBorderNotWhite)
{
up--;
aBlackPointFoundOnBorder = true;
atLeastOneBlackPointFoundOnTop = true;
}
else if (!atLeastOneBlackPointFoundOnTop)
{
up--;
}
}
if (up < 0)
{
sizeExceeded = true;
break;
}
}
if (!sizeExceeded)
{
int maxSize = right - left;
ResultPoint z = null;
for (int i = 1; z == null && i < maxSize; i++)
{
z = getBlackPointOnSegment(left, down - i, left + i, down);
}
if (z == null)
{
return null;
}
ResultPoint t = null;
//go down right
for (int i = 1; t == null && i < maxSize; i++)
{
t = getBlackPointOnSegment(left, up + i, left + i, up);
}
if (t == null)
{
return null;
}
ResultPoint x = null;
//go down left
for (int i = 1; x == null && i < maxSize; i++)
{
x = getBlackPointOnSegment(right, up + i, right - i, up);
}
if (x == null)
{
return null;
}
ResultPoint y = null;
//go up left
for (int i = 1; y == null && i < maxSize; i++)
{
y = getBlackPointOnSegment(right, down - i, right - i, down);
}
if (y == null)
{
return null;
}
return centerEdges(y, z, x, t);
}
return null;
}
private ResultPoint getBlackPointOnSegment(float aX, float aY, float bX, float bY)
{
int dist = MathUtils.round(MathUtils.distance(aX, aY, bX, bY));
float xStep = (bX - aX) / dist;
float yStep = (bY - aY) / dist;
for (int i = 0; i < dist; i++)
{
int x = MathUtils.round(aX + i * xStep);
int y = MathUtils.round(aY + i * yStep);
if (image[x, y])
{
return new ResultPoint(x, y);
}
}
return null;
}
/// <summary>
/// recenters the points of a constant distance towards the center
/// </summary>
/// <param name="y">bottom most point</param>
/// <param name="z">left most point</param>
/// <param name="x">right most point</param>
/// <param name="t">top most point</param>
/// <returns><see cref="ResultPoint"/>[] describing the corners of the rectangular
/// region. The first and last points are opposed on the diagonal, as
/// are the second and third. The first point will be the topmost
/// point and the last, the bottommost. The second point will be
/// leftmost and the third, the rightmost</returns>
private ResultPoint[] centerEdges(ResultPoint y, ResultPoint z,
ResultPoint x, ResultPoint t)
{
//
// t t
// z x
// x OR z
// y y
//
float yi = y.X;
float yj = y.Y;
float zi = z.X;
float zj = z.Y;
float xi = x.X;
float xj = x.Y;
float ti = t.X;
float tj = t.Y;
if (yi < width / 2.0f)
{
return new[]
{
new ResultPoint(ti - CORR, tj + CORR),
new ResultPoint(zi + CORR, zj + CORR),
new ResultPoint(xi - CORR, xj - CORR),
new ResultPoint(yi + CORR, yj - CORR)
};
}
else
{
return new[]
{
new ResultPoint(ti + CORR, tj + CORR),
new ResultPoint(zi + CORR, zj - CORR),
new ResultPoint(xi - CORR, xj + CORR),
new ResultPoint(yi - CORR, yj - CORR)
};
}
}
/// <summary>
/// Determines whether a segment contains a black point
/// </summary>
/// <param name="a">min value of the scanned coordinate</param>
/// <param name="b">max value of the scanned coordinate</param>
/// <param name="fixed">value of fixed coordinate</param>
/// <param name="horizontal">set to true if scan must be horizontal, false if vertical</param>
/// <returns>
/// true if a black point has been found, else false.
/// </returns>
private bool containsBlackPoint(int a, int b, int @fixed, bool horizontal)
{
if (horizontal)
{
for (int x = a; x <= b; x++)
{
if (image[x, @fixed])
{
return true;
}
}
}
else
{
for (int y = a; y <= b; y++)
{
if (image[@fixed, y])
{
return true;
}
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using RadialMenuControl.UserControl;
namespace RadialMenuControl.Components
{
public partial class RadialMenuButton : Button
{
public enum ButtonType
{
Simple = 0,
Radio,
Toggle,
Custom
};
// SubMenu
public static readonly DependencyProperty SubmenuProperty =
DependencyProperty.Register("Submenu", typeof (RadialMenu), typeof (RadialMenuButton), null);
public RadialMenuButton()
{
InitializeComponent();
}
/// <summary>
/// A RadialMenu that is opened when the user presses the button
/// </summary>
public RadialMenu Submenu
{
get { return (RadialMenu) GetValue(SubmenuProperty); }
set { SetValue(SubmenuProperty, value); }
}
/// <summary>
/// Allows the use of key/value pairs to set the colors
/// </summary>
/// <param name="colors">Dictionary containing colors in a key/value pair</param>
public void SetColors(Dictionary<string, Color> colors)
{
foreach (var colorVariable in colors)
{
if (GetType().GetProperty(colorVariable.Key) != null)
{
var prop = GetType().GetProperty(colorVariable.Key);
prop.SetValue(this, colorVariable.Value);
}
}
}
# region properties
// Label
public static readonly DependencyProperty LabelProperty =
DependencyProperty.Register("Label", typeof (string), typeof (RadialMenuButton), new PropertyMetadata(""));
public static readonly DependencyProperty LabelSizeProperty =
DependencyProperty.Register("LabelSize", typeof (int), typeof (RadialMenuButton), new PropertyMetadata(10));
public static readonly DependencyProperty IsLabelHiddenProperty =
DependencyProperty.Register("IsLabelHidden", typeof (bool), typeof (RadialMenuButton), null);
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register("Icon", typeof (string), typeof (RadialMenuButton), new PropertyMetadata(""));
public static readonly DependencyProperty IconFontFamilyProperty =
DependencyProperty.Register("IconFontFamily", typeof (FontFamily), typeof (RadialMenuButton),
new PropertyMetadata(new FontFamily("Segoe UI")));
public static readonly DependencyProperty IconForegroundBrushProperty =
DependencyProperty.Register("IconForegroundBrush", typeof (Brush), typeof (RadialMenuButton),
new PropertyMetadata(new SolidColorBrush(Colors.Black)));
public static readonly DependencyProperty IconSizeProperty =
DependencyProperty.Register("IconSize", typeof (int), typeof (RadialMenuButton), new PropertyMetadata(26));
public static readonly DependencyProperty IconImageProperty =
DependencyProperty.Register("IconImage", typeof (ImageSource), typeof (RadialMenuButton), null);
public static readonly DependencyProperty MenuSeletedProperty =
DependencyProperty.Register("MenuSelected", typeof (bool), typeof (RadialMenuButton), null);
public static readonly DependencyProperty ButtonTypeProperty =
DependencyProperty.Register("ButtonType", typeof (ButtonType), typeof (RadialMenuButton),
new PropertyMetadata(ButtonType.Simple));
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof (object), typeof (RadialMenuButton), null);
/// <summary>
/// Label, displayed in the inner portion of the button
/// </summary>
public string Label
{
get { return (string) GetValue(LabelProperty) ?? ""; }
set { SetValue(LabelProperty, value); }
}
/// <summary>
/// Font Size for the label
/// </summary>
public int LabelSize
{
get { return (int) GetValue(LabelSizeProperty); }
set { SetValue(LabelProperty, value); }
}
/// <summary>
/// Should the label be hidden?
/// </summary>
public bool IsLabelHidden
{
get { return (bool) GetValue(IsLabelHiddenProperty); }
set { SetValue(IsLabelHiddenProperty, value); }
}
/// <summary>
/// Text-based icon, displayed in a TextBox (usually used with icon fonts)
/// </summary>
public string Icon
{
get { return (string) GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
/// <summary>
/// Font for the text-based icon
/// </summary>
public FontFamily IconFontFamily
{
get { return (FontFamily) GetValue(IconFontFamilyProperty); }
set { SetValue(IconFontFamilyProperty, value); }
}
/// <summary>
/// Font size for the text-based icon
/// </summary>
public int IconSize
{
get { return (int) GetValue(IconSizeProperty); }
set { SetValue(IconProperty, value); }
}
/// <summary>
/// ForegroundBrush for the text-based icon
/// </summary>
public Brush IconForegroundBrush
{
get { return (Brush) GetValue(IconForegroundBrushProperty); }
set { SetValue(IconForegroundBrushProperty, value); }
}
/// <summary>
/// A ImageSource for the icon. If set, the text-based icon will be hidden.
/// </summary>
public ImageSource IconImage
{
get { return (ImageSource) GetValue(IconImageProperty); }
set { SetValue(IconImageProperty, value); }
}
// Values & Button Type
/// <summary>
/// If the button is a radio button and selected on behalf of the whole RadialMenu, this value will be true (false
/// otherwise)
/// </summary>
public bool MenuSelected
{
get { return (bool) GetValue(MenuSeletedProperty); }
set { SetValue(MenuSeletedProperty, value); }
}
/// <summary>
/// Value of this button
/// </summary>
public object Value
{
get { return GetValue(ValueProperty); }
set
{
if (Type == ButtonType.Simple)
{
throw new Exception("A button of type SIMPLE should not have any value.");
}
SetValue(ValueProperty, value);
}
}
/// <summary>
/// Button type, indicating the way users can interact with this button
/// </summary>
public ButtonType Type
{
get { return (ButtonType) GetValue(ButtonTypeProperty); }
set { SetValue(ButtonTypeProperty, value); }
}
// Inner Arc Colors
public static readonly DependencyProperty InnerNormalColorProperty =
DependencyProperty.Register("InnerNormalColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty InnerHoverColorProperty =
DependencyProperty.Register("InnerHoverColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty InnerTappedColorProperty =
DependencyProperty.Register("InnerTappedColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty InnerReleasedColorProperty =
DependencyProperty.Register("InnerReleasedColor", typeof (Color?), typeof (RadialMenuButton), null);
/// <summary>
/// Hover color for the inner portion of the button
/// </summary>
public Color? InnerHoverColor
{
get { return (Color?) GetValue(InnerHoverColorProperty); }
set { SetValue(InnerHoverColorProperty, value); }
}
/// <summary>
/// Normal color for the inner portion of the button
/// </summary>
public Color? InnerNormalColor
{
get { return (Color?) GetValue(InnerNormalColorProperty); }
set { SetValue(InnerNormalColorProperty, value); }
}
/// <summary>
/// Tapped color for the inner portion of the button
/// </summary>
public Color? InnerTappedColor
{
get { return (Color?) GetValue(InnerTappedColorProperty); }
set { SetValue(InnerTappedColorProperty, value); }
}
/// <summary>
/// Released color for the inner portion of the button
/// </summary>
public Color? InnerReleasedColor
{
get { return (Color?) GetValue(InnerReleasedColorProperty); }
set { SetValue(InnerReleasedColorProperty, value); }
}
// Outer Arc Colors
public static readonly DependencyProperty OuterNormalColorProperty =
DependencyProperty.Register("OuterNormalColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty OuterDisabledColorProperty =
DependencyProperty.Register("OuterDisabledColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty OuterHoverColorProperty =
DependencyProperty.Register("OuterHoverColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty OuterTappedColorProperty =
DependencyProperty.Register("OuterTappedColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty OuterThicknessProperty =
DependencyProperty.Register("OuterThickness", typeof (double?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty StrokeColorProperty =
DependencyProperty.Register("StrokeColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty StrokeThicknessProperty =
DependencyProperty.Register("StrokeThickness", typeof (double?), typeof (RadialMenuButton), null);
// Indication Arc
public static readonly DependencyProperty UseIndicationArcProperty =
DependencyProperty.Register("UseIndicationArcProperty", typeof (bool?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty IndicationArcColorProperty =
DependencyProperty.Register("IndicationArcColor", typeof (Color?), typeof (RadialMenuButton), null);
public static readonly DependencyProperty IndicationArcStrokeThicknessProperty =
DependencyProperty.Register("IndicationArcStrokeThickness", typeof (double?), typeof (RadialMenuButton),
null);
public static readonly DependencyProperty IndicationArcDistanceFromEdgeProperty =
DependencyProperty.Register("IndicationArcDistanceFromEdge", typeof (double?), typeof (RadialMenuButton),
null);
/// <summary>
/// Distance from the inner part of the outer band to the indication arc
/// </summary>
public double? IndicationArcDistanceFromEdge
{
get { return (double?) GetValue(IndicationArcDistanceFromEdgeProperty); }
set { SetValue(IndicationArcDistanceFromEdgeProperty, value); }
}
/// <summary>
/// When set to true, an indication arc will be placed on this button
/// </summary>
public bool? UseIndicationArc
{
get { return (bool?) GetValue(UseIndicationArcProperty); }
set { SetValue(UseIndicationArcProperty, value); }
}
public Color? IndicationArcColor
{
get { return (Color?) GetValue(IndicationArcColorProperty); }
set { SetValue(IndicationArcColorProperty, value); }
}
/// <summary>
/// The Stroke thickness of the indication arc
/// </summary>
public double? IndicationArcStrokeThickness
{
get { return (double?) GetValue(IndicationArcStrokeThicknessProperty); }
set { SetValue(IndicationArcStrokeThicknessProperty, value); }
}
/// <summary>
/// Hover color for the outer portion of the button
/// </summary>
public Color? OuterHoverColor
{
get { return (Color?) GetValue(OuterHoverColorProperty); }
set { SetValue(OuterHoverColorProperty, value); }
}
/// <summary>
/// Normal color for the outer portion of the button
/// </summary>
public Color? OuterNormalColor
{
get { return (Color?) GetValue(OuterNormalColorProperty); }
set { SetValue(OuterNormalColorProperty, value); }
}
/// <summary>
/// Disabled color for the outer portion of the button
/// </summary>
public Color? OuterDisabledColor
{
get { return (Color?) GetValue(OuterDisabledColorProperty); }
set { SetValue(OuterDisabledColorProperty, value); }
}
/// <summary>
/// Tapped color for the outer portion of the button
/// </summary>
public Color? OuterTappedColor
{
get { return (Color?) GetValue(OuterTappedColorProperty); }
set { SetValue(OuterTappedColorProperty, value); }
}
// Stroke
/// <summary>
/// Color of the stroke around the PieSLice
/// </summary>
public Color? StrokeColor
{
get { return (Color?) GetValue(StrokeColorProperty); }
set { SetValue(StrokeColorProperty, value); }
}
/// <summary>
/// Thickness of the stroke around the PieSlice
/// </summary>
public double? StrokeThickness
{
get { return (double?) GetValue(StrokeThicknessProperty); }
set { SetValue(StrokeThicknessProperty, value); }
}
/// <summary>
/// Thickness of the outer arc, on the outer side of the button
/// </summary>
public double? OuterThickness
{
get { return (double?) GetValue(OuterThicknessProperty); }
set { SetValue(OuterThicknessProperty, value); }
}
// CustomMenu
public static readonly DependencyProperty CustomMenuProperty =
DependencyProperty.Register("Submenu", typeof (MenuBase), typeof (RadialMenuButton), null);
/// <summary>
/// CustomMenu behind the button
/// </summary>
public MenuBase CustomMenu
{
get { return (MenuBase) GetValue(CustomMenuProperty); }
set { SetValue(CustomMenuProperty, value); }
}
// Access Keys
/// <summary>
/// Outer slice path access key
/// </summary>
public string OuterAccessKey
{
get { return (string)GetValue(OuterAccessKeyProperty); }
set { SetValue(OuterAccessKeyProperty, value); }
}
/// <summary>
/// Inner slice path access key
/// </summary>
public string InnerAccessKey
{
get { return (string)GetValue(InnerAccessKeyProperty); }
set { SetValue(InnerAccessKeyProperty, value); }
}
#endregion properties
#region events
/// <summary>
/// Delegate for the ValueChangedEvent, fired whenever the value of this button is changed
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public delegate void ValueChangedHandler(object sender, RoutedEventArgs args);
public event ValueChangedHandler ValueChanged;
public void OnValueChanged(RoutedEventArgs e)
{
ValueChanged?.Invoke(this, e);
}
public static readonly DependencyProperty InnerAccessKeyProperty =
DependencyProperty.Register("InnerAccessKey", typeof (string), typeof (RadialMenuButton), null);
public static readonly DependencyProperty OuterAccessKeyProperty =
DependencyProperty.Register("OuterAccessKey", typeof (string), typeof (RadialMenuButton), null);
/// <summary>
/// Does this radial menu button have events on the outer arc?
/// </summary>
/// <returns></returns>
public bool HasOuterArcEvents => (OuterArcPressed != null || OuterArcReleased != null);
/// <summary>
/// Does this radial menu button have actions on the outer arc?
/// </summary>
/// <returns></returns>
public bool HasOuterArcAction => (Submenu != null || CustomMenu != null || HasOuterArcEvents);
public delegate void InnerArcPressedEventHandler(object sender, PointerRoutedEventArgs e);
/// <summary>
/// Invoked when the inner arc of the button has been pressed (mouse, touch, stylus)
/// </summary>
public event InnerArcPressedEventHandler InnerArcPressed;
public void OnInnerArcPressed(PointerRoutedEventArgs e)
{
InnerArcPressed?.Invoke(this, e);
if (Type != ButtonType.Simple)
{
MenuSelected = true;
}
if (Type == ButtonType.Toggle)
{
Value = (Value == null || !(bool) Value);
}
}
public delegate void OuterArcPressedEventHandler(object sender, PointerRoutedEventArgs e);
/// <summary>
/// Invoked when the outer arc of the button has been pressed (mouse, touch, stylus)
/// </summary>
public event OuterArcPressedEventHandler OuterArcPressed;
public void OnOuterArcPressed(PointerRoutedEventArgs e)
{
OuterArcPressed?.Invoke(this, e);
}
public delegate void InnerArcReleasedEventHandler(object sender, PointerRoutedEventArgs e);
/// <summary>
/// Invoked when the inner arc of the button has been released (mouse, touch, stylus)
/// </summary>
public event InnerArcReleasedEventHandler InnerArcReleased;
public void OnInnerArcReleased(PointerRoutedEventArgs e)
{
InnerArcReleased?.Invoke(this, e);
}
public delegate void OuterArcReleasedEventHandler(object sender, PointerRoutedEventArgs e);
/// <summary>
/// Invoked when the outer arc of the button has been pressed (mouse, touch, stylus)
/// </summary>
public event OuterArcReleasedEventHandler OuterArcReleased;
public void OnOuterArcReleased(PointerRoutedEventArgs e)
{
OuterArcReleased?.Invoke(this, e);
}
#endregion
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using AgentInterface;
namespace Agent
{
///////////////////////////////////////////////////////////////////////////
/**
* Implementation of the messaging subsystem in the Agent
*/
public partial class Agent : MarshalByRefObject, IAgentInternalInterface, IAgentInterface
{
///////////////////////////////////////////////////////////////////////////
/**
* The agent's private message queues with SendMessage using SM, and
* ProcessMessage using PM, and swapping the two when we start a new
* loop through ProcessMessage
*/
private Queue<AgentMessage> MessageQueueSM = new Queue<AgentMessage>();
private Queue<AgentMessage> MessageQueuePM = new Queue<AgentMessage>();
private AutoResetEvent MessageQueueReady = new AutoResetEvent( false );
private Object MessageQueueLock = new Object();
/**
* Used to control access to the SendMessageInteranl routine, used
* when we need to ensure all messages have been processed
*/
ReaderWriterLock SendMessageLock = new ReaderWriterLock();
///////////////////////////////////////////////////////////////////////////
private class DisconnectionSignalMessage : AgentSignalMessage
{
public DisconnectionSignalMessage( Connection InConnectionToDisconnect )
{
ConnectionToDisconnect = InConnectionToDisconnect;
}
public Connection ConnectionToDisconnect;
};
///////////////////////////////////////////////////////////////////////////
/**
* Tags incoming messages with the proper routing information and places it
* into the agent's private message queue. For all actual message processing,
* see ProcessMessage.
*/
private Int32 SendMessage_1_0( Int32 ConnectionHandle, Hashtable InParameters, ref Hashtable OutParameters )
{
StartTiming( "SendMessage_1_0-Internal", true );
Int32 ErrorCode = Constants.INVALID;
// Unpack the input parameters
AgentMessage NewMessage = InParameters["Message"] as AgentMessage;
// Treat standard calls to this API as "readers" only because we can
// have many of them at a time
SendMessageLock.AcquireReaderLock( Timeout.Infinite );
// First, validate the connection being used to interact with the Swarm,
// and only allow the message through if it's still alive
Connection Sender;
if( ( Connections.TryGetValue( ConnectionHandle, out Sender ) ) &&
( Sender.CurrentState != ConnectionState.DISCONNECTED ) )
{
// Call through to the internal routine
ErrorCode = SendMessageInternal( Sender, NewMessage );
}
else
{
string NewLogMessage = String.Format( "SendMessage: Message sent from unrecognized sender ({0:X8}), ignoring \"{1}\"", ConnectionHandle, NewMessage.Type );
Log( EVerbosityLevel.Verbose, ELogColour.Orange, NewLogMessage );
ErrorCode = Constants.ERROR_CONNECTION_NOT_FOUND;
}
// Release our "reader" lock
SendMessageLock.ReleaseReaderLock();
StopTiming();
return ( ErrorCode );
}
/**
* Actual work performed by SendMessage happens here
*/
public Int32 SendMessageInternal( Connection Sender, AgentMessage NewMessage )
{
Int32 ErrorCode = Constants.INVALID;
// We assume the message is valid, but if somewhere below we change our
// mind, this value will be set to false and we'll eat the message
bool bMessageIsValid = true;
// Logic for the setting of the To and From fields (if not already set)
//
// All connections sending messages are implicitly sending them to the
// Instigator of the Job they're working on. Depending on where the
// message is coming from, we might need to patch up the To field a
// little bit to ensure it's heading to a Local connection when it
// needs to be. The only case this applies is when we receive a message
// from a Remote connection, directed toward a Remote connection, which
// happens when we get a message from a Remote Agent from an even more
// Remote connection (i.e. a Job connection on the remote machine):
//
// To Local, From Local -> routing of main message and replies are ok
// To Local, From Remote -> routing of main message and replies are ok
// To Remote, From Local -> routing of main message and replies are ok
// To Remote, From Remote -> routing of replies is ok, but the main
// message is in trouble if it's not completely handled within the
// Agent's ProcessMessages routine. It would be forwarded on to the
// To field connection which is Remote and we'd end up bouncing the
// message back and forth forever. Need to adjust the To field to
// point to the parent of the To connection (which is where it's
// intended to go anyway). See further below for where we handle
// this case.
// If the From field is not set, give it the connection handle value by
// default so that any response message will automatically be routed back
// to it whether it's the sender or the recipient
if( NewMessage.From == Constants.INVALID )
{
NewMessage.From = Sender.Handle;
}
// If the connection used to send the message is Remote, check for the
// Remote -> Remote case described above
else if( Sender is RemoteConnection )
{
// If the From field is already set, see if we've already registered
// the connection this message is being sent from
Connection FromConnection;
if( !Connections.TryGetValue( NewMessage.From, out FromConnection ) )
{
// This is a new one - make it an alias for the sender so that any
// responses will be directed back via its sending interface
RemoteConnection RemoteSender = Sender as RemoteConnection;
RemoteSender.Aliases.Add( NewMessage.From );
// There are times we want to ensure no new connections are coming online
// where we'll lock the Connections dictionary (see MaintainCache)
lock( Connections )
{
Connections.Add( NewMessage.From, RemoteSender );
}
FromConnection = RemoteSender;
string LogMessage = String.Format( "[SendMessage] Added alias for remote connection: {0:X8} is an alias for {1:X8}",
NewMessage.From,
Sender.Handle );
Log( EVerbosityLevel.Informative, ELogColour.Green, LogMessage );
}
// If this is a Remote -> Remote situation, the proper place to route
// the message to the parent of the remote connection since the Agents
// generally act as glue between connections
if( FromConnection is RemoteConnection )
{
Debug.Assert( NewMessage.To != Constants.INVALID );
Connection ToConnection;
if( (Connections.TryGetValue( NewMessage.To, out ToConnection )) &&
(ToConnection is RemoteConnection) )
{
Connection ToConnectionParent = ToConnection.Parent;
if( ToConnectionParent != null )
{
NewMessage.To = ToConnectionParent.Handle;
}
}
}
}
// If the To field is not set, assign it based on the message type
if( NewMessage.To == Constants.INVALID )
{
// TODO: As we add additional versions, convert to a switch rather than if-else.
// For now, just use a simple if since we only have one version and a switch is
// overkill.
if( NewMessage.Version == ESwarmVersionValue.VER_1_0 )
{
// The default is for messages to be ultimately routed to the Instigator
// unless the message is one of a certain set of types that route
// directly to the connection specified
switch( NewMessage.Type )
{
// These message types need to be routed to the connection specified
// either because they are meant to be simple round-trip messages or
// because they are sent from within Swarm directly to the connection
// and should not be routed anywhere else
case EMessageType.QUIT:
case EMessageType.PING:
case EMessageType.SIGNAL:
NewMessage.To = Sender.Handle;
break;
// These message types need to be routed eventually to the Instigator
// connection, which is the ultimate ancestor up the parent chain, so
// simply assign the most senior parent we have
case EMessageType.INFO:
case EMessageType.ALERT:
case EMessageType.TIMING:
case EMessageType.TASK_REQUEST:
case EMessageType.TASK_STATE:
case EMessageType.JOB_STATE:
// By default, make the sender the recipient for these cases, in
// case the parent is no longer active
NewMessage.To = Sender.Handle;
Connection SenderParent = Sender.Parent;
if( SenderParent != null )
{
// If we have a parent connection and it's active, then
// assign it as the recipient
if( SenderParent.CurrentState == ConnectionState.CONNECTED )
{
NewMessage.To = SenderParent.Handle;
}
}
break;
// These message types are not expected and are each error cases
case EMessageType.NONE: // Should never be set to this
case EMessageType.JOB_SPECIFICATION: // Only used for messages going directly into OpenJob
case EMessageType.TASK_REQUEST_RESPONSE: // Should always have the To field set already
default:
Log( EVerbosityLevel.Informative, ELogColour.Orange, "SendMessage: Invalid message type received, ignoring " + NewMessage.Type.ToString() );
break;
}
// If still no assigned To field, consider it an error
if( NewMessage.To == Constants.INVALID )
{
Log( EVerbosityLevel.Informative, ELogColour.Orange, "SendMessage: No proper recipient found, ignoring " + NewMessage.Type.ToString() );
bMessageIsValid = false;
}
}
}
// If the message remains valid, post it to the queue
if( bMessageIsValid )
{
lock( MessageQueueLock )
{
Debug.Assert( NewMessage != null );
MessageQueueSM.Enqueue( NewMessage );
string NewLogMessage = String.Format( "Step 1 of N for message: ({0:X8} -> {1:X8}), {2}, Message Count {3} (Agent)",
NewMessage.To,
NewMessage.From,
NewMessage.Type,
MessageQueueSM.Count );
Log( EVerbosityLevel.SuperVerbose, ELogColour.Green, NewLogMessage );
MessageQueueReady.Set();
}
ErrorCode = Constants.SUCCESS;
}
else
{
Log( EVerbosityLevel.Informative, ELogColour.Orange, String.Format( "SendMessage: Discarded message \"{0}\"", NewMessage.Type ) );
}
return ( ErrorCode );
}
/*
* Get the machine name from the connection structure
*/
public string MachineNameFromConnection( Connection RequestingConnection )
{
string Name = "";
RemoteConnection Remote = RequestingConnection as RemoteConnection;
if( Remote == null )
{
Name = Environment.MachineName;
}
else
{
Name = Remote.Info.Name;
}
return ( Name );
}
/*
* Get the machine IP address from the connection structure
*/
public string MachineIPAddressFromConnection( Connection RequestingConnection )
{
string MachineIPAddress = "";
RemoteConnection Remote = RequestingConnection as RemoteConnection;
if( Remote == null )
{
MachineIPAddress = "127.0.0.1";
}
else
{
MachineIPAddress = Remote.Interface.RemoteAgentIPAddress;
}
return ( MachineIPAddress );
}
/**
* Flush the message queue - note this does not assure that it's empty, it just
* makes sure that all messages that are in the queue at the time of this method
* call are processed. This call is blocking.
*/
public bool FlushMessageQueue( Connection RequestingConnection, bool WithDisconnect )
{
Log( EVerbosityLevel.ExtraVerbose, ELogColour.Green, String.Format( "[FlushMessageQueue] Draining message queue for {0:X8}", RequestingConnection.Handle ) );
// This special call will act as a "writer" since we only want to
// allow one of these to act at a time. By doing this, we ensure
// that all "readers" that use this lock are finished.
SendMessageLock.AcquireWriterLock( Timeout.Infinite );
Log( EVerbosityLevel.ExtraVerbose, ELogColour.Green, String.Format( "[FlushMessageQueue] Lock acquired for {0:X8}", RequestingConnection.Handle ) );
// Flush the message queue with a signal message, optionally with a disconnection event
AgentSignalMessage SignalMessage;
if( WithDisconnect )
{
SignalMessage = new DisconnectionSignalMessage( RequestingConnection );
}
else
{
SignalMessage = new AgentSignalMessage();
}
Int32 SignalMessageSent = SendMessageInternal( RequestingConnection, SignalMessage );
// Release our "writer" lock
SendMessageLock.ReleaseWriterLock();
Log( EVerbosityLevel.ExtraVerbose, ELogColour.Green, String.Format( "[FlushMessageQueue] Lock released for {0:X8}", RequestingConnection.Handle ) );
if( SignalMessageSent == Constants.SUCCESS )
{
SignalMessage.ResetEvent.WaitOne( Timeout.Infinite );
Log( EVerbosityLevel.ExtraVerbose, ELogColour.Green, String.Format( "[FlushMessageQueue] Drain complete for {0:X8}", RequestingConnection.Handle ) );
return true;
}
else
{
Log( EVerbosityLevel.ExtraVerbose, ELogColour.Green, "[FlushMessageQueue] Drain failed because of an error sending the signal message" );
return false;
}
}
/**
* Takes messages off the internal message queue and handles them by either
* sending responses, forwarding the message on, or processing it internally
*/
private void ProcessMessagesThreadProc()
{
// A response message queue used to send messages back to the one which sent it
Queue<AgentMessage> ResponseMessageQueue = new Queue<AgentMessage>();
while( AgentHasShutDown == false )
{
StartTiming( "ProcessMessage-Internal", true );
lock( MessageQueueLock )
{
// Swap the SM and PM message queue to keep things moving at full speed
Queue<AgentMessage> Temp = MessageQueuePM;
MessageQueuePM = MessageQueueSM;
MessageQueueSM = Temp;
}
// Process all messages currently in the queue
while( MessageQueuePM.Count > 0 )
{
Debug.Assert( ResponseMessageQueue.Count == 0 );
// Get and process the next message
AgentMessage NextMessage = MessageQueuePM.Dequeue();
Debug.Assert( NextMessage != null );
bool bMessageHandled = false;
switch( NextMessage.Type )
{
case EMessageType.SIGNAL:
{
if( NextMessage is DisconnectionSignalMessage )
{
// Mark the connection as inactive
DisconnectionSignalMessage DisconnectMessage = NextMessage as DisconnectionSignalMessage;
Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[CloseConnection] Connection disconnected {0:X8}", DisconnectMessage.ConnectionToDisconnect.Handle ) );
DisconnectMessage.ConnectionToDisconnect.CurrentState = ConnectionState.DISCONNECTED;
DisconnectMessage.ConnectionToDisconnect.DisconnectedTime = DateTime.UtcNow;
}
// Signal the message and move on
AgentSignalMessage SignalMessage = NextMessage as AgentSignalMessage;
SignalMessage.ResetEvent.Set();
bMessageHandled = true;
}
break;
case EMessageType.TIMING:
{
Connection FromConnection;
if( ( Connections.TryGetValue( NextMessage.From, out FromConnection ) ) )
{
Connection ToConnection;
if( ( Connections.TryGetValue( NextMessage.To, out ToConnection ) ) &&
( ToConnection is LocalConnection ) )
{
// Handle message
AgentTimingMessage TimingMessage = NextMessage as AgentTimingMessage;
AgentApplication.UpdateMachineState( MachineNameFromConnection( FromConnection ), TimingMessage.ThreadNum, TimingMessage.State );
bMessageHandled = true;
}
}
}
break;
case EMessageType.TASK_REQUEST:
{
// Look up the requesting connection
Debug.Assert( NextMessage.From != Constants.INVALID );
Connection RequestingConnection;
if( Connections.TryGetValue( NextMessage.From, out RequestingConnection ) )
{
// Look up the specified Job
AgentJob JobToAskForTasks = RequestingConnection.Job;
if( JobToAskForTasks != null )
{
// If we get a valid response back, add it to the queue
AgentTaskRequestResponse Response = JobToAskForTasks.GetNextTask( RequestingConnection );
if( Response != null )
{
ResponseMessageQueue.Enqueue( Response );
// Specifications and releases are always handled here, but
// reservations are special in that we will send a reservation
// back to local connections but we'll need to make sure the
// message continues on to remote connections.
if( ( Response.ResponseType == ETaskRequestResponseType.SPECIFICATION ) ||
( Response.ResponseType == ETaskRequestResponseType.RELEASE ) ||
( ( Response.ResponseType == ETaskRequestResponseType.RESERVATION ) &&
( JobToAskForTasks.Owner is LocalConnection ) ) )
{
bMessageHandled = true;
}
}
}
else
{
// Unable to find the Job, just send back a release message
Log( EVerbosityLevel.Verbose, ELogColour.Orange, "[ProcessMessage] Unable to find Job for Task Request; may have been closed" );
//ResponseMessageQueue.Enqueue( new AgentTaskRequestResponse( RequestingConnection.Job.JobGuid,
// ETaskRequestResponseType.RELEASE ) );
bMessageHandled = true;
}
}
else
{
// Unable to find the connection, swallow the request
Log( EVerbosityLevel.Verbose, ELogColour.Orange, "[ProcessMessage] Unable to find owning Connection for Task Request" );
bMessageHandled = true;
}
}
break;
case EMessageType.TASK_STATE:
{
// Look up the sending connection
Debug.Assert( NextMessage.From != Constants.INVALID );
Connection SendingConnection;
if( ( Connections.TryGetValue( NextMessage.From, out SendingConnection ) ) &&
( SendingConnection.Job != null ) )
{
// Look up the specified Job
AgentJob UpdatedJob;
if( ActiveJobs.TryGetValue( SendingConnection.Job.JobGuid, out UpdatedJob ) )
{
AgentTaskState UpdatedTaskState = NextMessage as AgentTaskState;
UpdatedJob.UpdateTaskState( UpdatedTaskState );
if( UpdatedJob.Owner is LocalConnection )
{
// If the Task state change is of a type potentially interesting to
// the Instigator, return it
switch( UpdatedTaskState.TaskState )
{
case EJobTaskState.TASK_STATE_INVALID:
case EJobTaskState.TASK_STATE_COMPLETE_SUCCESS:
case EJobTaskState.TASK_STATE_COMPLETE_FAILURE:
// For these message types, allow the message to continue on
break;
default:
// Nothing to do otherwise, mark the message as handled
bMessageHandled = true;
break;
}
}
else
{
// Always send messages on for remote connections
}
}
else
{
// Unable to find the Job, swallow the request
Log( EVerbosityLevel.Verbose, ELogColour.Orange, "[ProcessMessage] Unable to find Job for Task Request" );
bMessageHandled = true;
}
}
else
{
// Unable to find the connection, swallow the request
Log( EVerbosityLevel.Verbose, ELogColour.Orange, "[ProcessMessage] Unable to find owning Connection for Task Request" );
bMessageHandled = true;
}
}
break;
}
// If the message was not handled completely, send it on
if( bMessageHandled == false )
{
// Look up who the message is being sent to and make sure they're
// still active and if not, ignore the message
Connection Recipient;
Debug.Assert( NextMessage.To != Constants.INVALID );
if( Connections.TryGetValue( NextMessage.To, out Recipient ) )
{
if( Recipient is LocalConnection )
{
// If the recipient is local, place it in the proper queue
// and signal that a message is ready
LocalConnection LocalRecipient = Recipient as LocalConnection;
lock( LocalRecipient.MessageQueue )
{
LocalRecipient.MessageQueue.Enqueue( NextMessage );
string NewLogMessage = String.Format( "Step 2 of 4 for message: ({0:X8} -> {1:X8}), {2}, Message Count {3} (Local Connection)",
NextMessage.To,
NextMessage.From,
NextMessage.Type,
LocalRecipient.MessageQueue.Count );
Log( EVerbosityLevel.SuperVerbose, ELogColour.Green, NewLogMessage );
LocalRecipient.MessageAvailableSignal();
}
}
else
{
Debug.Assert( Recipient is RemoteConnection );
// If the recipient is remote, send the message via SendMessage
// unless the message is a Task being sent back, which is sent
// via the dedicated Task API
RemoteConnection RemoteRecipient = Recipient as RemoteConnection;
if( NextMessage is AgentTaskSpecification )
{
// All new Tasks are sent via the dedicated Task API
AgentTaskSpecification TaskSpecification = NextMessage as AgentTaskSpecification;
Hashtable RemoteInParameters = new Hashtable();
RemoteInParameters["Version"] = ESwarmVersionValue.VER_1_0;
RemoteInParameters["Specification"] = TaskSpecification;
Hashtable RemoteOutParameters = null;
Int32 Error = RemoteRecipient.Interface.AddTask( RemoteRecipient.Handle, RemoteInParameters, ref RemoteOutParameters );
if( Error >= 0 )
{
// Perhaps we should be sending an accept message back?
}
else
{
AgentTaskState UpdateMessage;
if( Error == Constants.ERROR_CONNECTION_DISCONNECTED )
{
// Special case of the connection dropping while we're adding the
// task, say it's been killed to requeue
UpdateMessage = new AgentTaskState( TaskSpecification.JobGuid,
TaskSpecification.TaskGuid,
EJobTaskState.TASK_STATE_KILLED );
}
else
{
// All other error cases will be rejections
UpdateMessage = new AgentTaskState( TaskSpecification.JobGuid,
TaskSpecification.TaskGuid,
EJobTaskState.TASK_STATE_REJECTED );
}
AgentJob Job;
if( ActiveJobs.TryGetValue( TaskSpecification.JobGuid, out Job ) )
{
Job.UpdateTaskState( UpdateMessage );
}
}
}
else
{
// All standard messages are sent via the SendMessage API
Hashtable RemoteInParameters = new Hashtable();
RemoteInParameters["Version"] = ESwarmVersionValue.VER_1_0;
RemoteInParameters["Message"] = NextMessage;
Hashtable RemoteOutParameters = null;
RemoteRecipient.Interface.SendMessage( NextMessage.To, RemoteInParameters, ref RemoteOutParameters );
}
string NewLogMessage = String.Format( "Step 2 of 2 for message: ({0:X8} -> {1:X8}), {2}, (Remote Connection)",
NextMessage.To,
NextMessage.From,
NextMessage.Type );
Log( EVerbosityLevel.SuperVerbose, ELogColour.Green, NewLogMessage );
}
}
else
{
Log( EVerbosityLevel.Informative, ELogColour.Orange, "ProcessMessage: Message sent to invalid connection, ignoring: " + NextMessage.Type.ToString() );
}
}
// If there are any responses to the message, send them
if( ResponseMessageQueue.Count > 0 )
{
foreach( AgentMessage NextResponse in ResponseMessageQueue )
{
// For each one of the messages, set the routing fields properly
NextResponse.To = NextMessage.From;
NextResponse.From = NextMessage.To;
// And then queue the message back up immediately
MessageQueuePM.Enqueue( NextResponse );
}
ResponseMessageQueue.Clear();
}
}
StopTiming();
// Wait for a message to become available and once unlocked, swap the queues
// and check for messages to process. Set a timeout, so we'll wake up every
// now and then to check for a quit signal at least
MessageQueueReady.WaitOne( 500 );
}
}
/**
* Gets the next message in the queue, optionally blocking until a message is available
*/
private Int32 GetMessage_1_0( Int32 ConnectionHandle, Hashtable InParameters, ref Hashtable OutParameters )
{
StartTiming( "GetMessage_1_0-Internal", true );
Int32 ErrorCode = Constants.INVALID;
AgentMessage NextMessage = null;
// Unpack the input parameters
Int32 Timeout = ( Int32 )InParameters["Timeout"];
// First, validate the connection requesting the message by making sure it
// exists and is local
Connection Recipient;
if( ( Connections.TryGetValue( ConnectionHandle, out Recipient ) ) &&
( Recipient is LocalConnection ) )
{
// This should only ever be called by local connections since remote
// connections have a direct messaging link between Agents
LocalConnection ConnectionMessageSentTo = Recipient as LocalConnection;
StopTiming();
// If no message is available, wait for one for the specified amount of time
bool Signaled = ConnectionMessageSentTo.MessageAvailableWait( Timeout );
StartTiming( "GetMessage-Internal", true );
// If the semaphore was signaled, then check the queue and get the next message
if( Signaled )
{
// Thread-safe queue usage
lock( ConnectionMessageSentTo.MessageQueue )
{
// Check to see if we actually have any messages to dequeue (standard case)
if( ConnectionMessageSentTo.MessageQueue.Count > 0 )
{
// Dequeue and process the message
NextMessage = ConnectionMessageSentTo.MessageQueue.Dequeue();
OutParameters = new Hashtable();
OutParameters["Version"] = ESwarmVersionValue.VER_1_0;
OutParameters["Message"] = NextMessage;
string NewLogMessage = String.Format( "Step 3 of 4 for message: ({0:X8} -> {1:X8}), {2}, Message Count {3} (Local Connection)",
NextMessage.To,
NextMessage.From,
NextMessage.Type,
ConnectionMessageSentTo.MessageQueue.Count );
Log( EVerbosityLevel.SuperVerbose, ELogColour.Green, NewLogMessage );
ErrorCode = Constants.SUCCESS;
}
else
{
// If the semaphore was signaled and the message queue is empty, which
// is only true after CloseConnection is called, we're done
ErrorCode = Constants.ERROR_CONNECTION_DISCONNECTED;
}
}
}
else
{
// Otherwise, the timeout period has elapsed; this is still considered a
// success only without a message to send back
Log( EVerbosityLevel.Verbose, ELogColour.Green, String.Format( "[GetMessage] Message available timeout expired, safely returning to {0:X8} with no message", ConnectionHandle ) );
ErrorCode = Constants.SUCCESS;
}
}
else
{
string LogMessage = String.Format( "[GetMessage] Either connection doesn't exist or is not a local connection: {0:X8}", ConnectionHandle );
Log( EVerbosityLevel.Informative, ELogColour.Red, LogMessage );
ErrorCode = Constants.ERROR_CONNECTION_NOT_FOUND;
}
// Determine if we have a message to send back
if( NextMessage != null )
{
string NewLogMessage = String.Format( "Step 4 of 4 for message: ({0:X8} -> {1:X8}), {2}, Delivered (Local Connection)",
NextMessage.To,
NextMessage.From,
NextMessage.Type );
Log( EVerbosityLevel.SuperVerbose, ELogColour.Green, NewLogMessage );
}
else if( Timeout == -1 )
{
if( ( Recipient != null ) &&
( Recipient.CurrentState == ConnectionState.DISCONNECTED ) )
{
Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[GetMessage] Safely returning to {0:X8} with no message", ConnectionHandle ) );
}
else
{
Log( EVerbosityLevel.Informative, ELogColour.Orange, String.Format( "[GetMessage] Returning to {0:X8} with no message, possibly in error", ConnectionHandle ) );
}
}
StopTiming();
return ( ErrorCode );
}
}
}
| |
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
namespace Facebook.CSSLayout
{
/**
* Class representing CSS spacing (padding, margin, and borders). This is mostly necessary to
* properly implement interactions and updates for properties like margin, marginLeft, and
* marginHorizontal.
*/
sealed class Spacing
{
/**
* Spacing type that represents the left direction. E.g. {@code marginLeft}.
*/
internal const int LEFT = (int)CSSSpacingType.Left;
/**
* Spacing type that represents the top direction. E.g. {@code marginTop}.
*/
internal const int TOP = (int)CSSSpacingType.Top;
/**
* Spacing type that represents the right direction. E.g. {@code marginRight}.
*/
internal const int RIGHT = (int)CSSSpacingType.Right;
/**
* Spacing type that represents the bottom direction. E.g. {@code marginBottom}.
*/
internal const int BOTTOM = (int)CSSSpacingType.Bottom;
/**
* Spacing type that represents vertical direction (top and bottom). E.g. {@code marginVertical}.
*/
internal const int VERTICAL = (int)CSSSpacingType.Vertical;
/**
* Spacing type that represents horizontal direction (left and right). E.g.
* {@code marginHorizontal}.
*/
internal const int HORIZONTAL = (int)CSSSpacingType.Horizontal;
/**
* Spacing type that represents start direction e.g. left in left-to-right, right in right-to-left.
*/
internal const int START = (int)CSSSpacingType.Start;
/**
* Spacing type that represents end direction e.g. right in left-to-right, left in right-to-left.
*/
internal const int END = (int)CSSSpacingType.End;
/**
* Spacing type that represents all directions (left, top, right, bottom). E.g. {@code margin}.
*/
internal const int ALL = (int)CSSSpacingType.All;
static readonly int[] sFlagsMap = {
1, /*LEFT*/
2, /*TOP*/
4, /*RIGHT*/
8, /*BOTTOM*/
16, /*VERTICAL*/
32, /*HORIZONTAL*/
64, /*START*/
128, /*END*/
256 /*ALL*/
};
float[] mSpacing = newFullSpacingArray();
[Nullable] float[] mDefaultSpacing = null;
int mValueFlags = 0;
bool mHasAliasesSet;
/**
* Set a spacing value.
*
* @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM},
* {@link #VERTICAL}, {@link #HORIZONTAL}, {@link #ALL}
* @param value the value for this direction
* @return {@code true} if the spacing has changed, or {@code false} if the same value was already
* set
*/
internal bool set(int spacingType, float value)
{
if (!FloatUtil.floatsEqual(mSpacing[spacingType], value))
{
mSpacing[spacingType] = value;
if (CSSConstants.IsUndefined(value))
{
mValueFlags &= ~sFlagsMap[spacingType];
}
else
{
mValueFlags |= sFlagsMap[spacingType];
}
mHasAliasesSet =
(mValueFlags & sFlagsMap[ALL]) != 0 ||
(mValueFlags & sFlagsMap[VERTICAL]) != 0 ||
(mValueFlags & sFlagsMap[HORIZONTAL]) != 0;
return true;
}
return false;
}
/**
* Set a default spacing value. This is used as a fallback when no spacing has been set for a
* particular direction.
*
* @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM}
* @param value the default value for this direction
* @return
*/
internal bool setDefault(int spacingType, float value)
{
if (mDefaultSpacing == null)
mDefaultSpacing = newSpacingResultArray();
if (!FloatUtil.floatsEqual(mDefaultSpacing[spacingType], value))
{
mDefaultSpacing[spacingType] = value;
return true;
}
return false;
}
/**
* Get the spacing for a direction. This takes into account any default values that have been set.
*
* @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM}
*/
internal float get(int spacingType)
{
float defaultValue =
(mDefaultSpacing != null)
? mDefaultSpacing[spacingType]
: (spacingType == START || spacingType == END ? CSSConstants.Undefined : 0);
if (mValueFlags == 0)
{
return defaultValue;
}
if ((mValueFlags & sFlagsMap[spacingType]) != 0)
{
return mSpacing[spacingType];
}
if (mHasAliasesSet)
{
int secondType = spacingType == TOP || spacingType == BOTTOM ? VERTICAL : HORIZONTAL;
if ((mValueFlags & sFlagsMap[secondType]) != 0)
{
return mSpacing[secondType];
}
else if ((mValueFlags & sFlagsMap[ALL]) != 0)
{
return mSpacing[ALL];
}
}
return defaultValue;
}
/**
* Get the raw value (that was set using {@link #set(int, float)}), without taking into account
* any default values.
*
* @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM},
* {@link #VERTICAL}, {@link #HORIZONTAL}, {@link #ALL}
*/
internal float getRaw(int spacingType)
{
return mSpacing[spacingType];
}
/**
* Try to get start value and fallback to given type if not defined. This is used privately
* by the layout engine as a more efficient way to fetch direction-aware values by
* avoid extra method invocations.
*/
internal float getWithFallback(int spacingType, int fallbackType)
{
return
(mValueFlags & sFlagsMap[spacingType]) != 0
? mSpacing[spacingType]
: get(fallbackType);
}
static float[] newFullSpacingArray()
{
return new[]
{
CSSConstants.Undefined,
CSSConstants.Undefined,
CSSConstants.Undefined,
CSSConstants.Undefined,
CSSConstants.Undefined,
CSSConstants.Undefined,
CSSConstants.Undefined,
CSSConstants.Undefined,
CSSConstants.Undefined
};
}
static float[] newSpacingResultArray()
{
return newSpacingResultArray(0);
}
static float[] newSpacingResultArray(float defaultValue)
{
return new[]
{
defaultValue,
defaultValue,
defaultValue,
defaultValue,
defaultValue,
defaultValue,
CSSConstants.Undefined,
CSSConstants.Undefined,
defaultValue
};
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules
{
/// <summary>
/// Enables Prim limits for parcel.
/// </summary>
/// <remarks>
/// This module selectivly enables parcel prim limits.
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "PrimLimitsModule")]
public class PrimLimitsModule : INonSharedRegionModule
{
protected IDialogModule m_dialogModule;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_enabled;
public string Name { get { return "PrimLimitsModule"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource config)
{
string permissionModules = Util.GetConfigVarFromSections<string>(config, "permissionmodules",
new string[] { "Startup", "Permissions" }, "DefaultPermissionsModule");
List<string> modules = new List<string>(permissionModules.Split(',').Select(m => m.Trim()));
if(!modules.Contains("PrimLimitsModule"))
return;
m_log.DebugFormat("[PRIM LIMITS]: Initialized module");
m_enabled = true;
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
{
return;
}
scene.Permissions.OnRezObject += CanRezObject;
scene.Permissions.OnObjectEntry += CanObjectEnter;
scene.Permissions.OnDuplicateObject += CanDuplicateObject;
m_log.DebugFormat("[PRIM LIMITS]: Region {0} added", scene.RegionInfo.RegionName);
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
return;
}
scene.Permissions.OnRezObject -= CanRezObject;
scene.Permissions.OnObjectEntry -= CanObjectEnter;
scene.Permissions.OnDuplicateObject -= CanDuplicateObject;
}
public void RegionLoaded(Scene scene)
{
m_dialogModule = scene.RequestModuleInterface<IDialogModule>();
}
private bool CanRezObject(int objectCount, UUID ownerID, Vector3 objectPosition, Scene scene)
{
ILandObject lo = scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y);
string response = DoCommonChecks(objectCount, ownerID, lo, scene);
if (response != null)
{
m_dialogModule.SendAlertToUser(ownerID, response);
return false;
}
return true;
}
//OnDuplicateObject
private bool CanDuplicateObject(int objectCount, UUID objectID, UUID ownerID, Scene scene, Vector3 objectPosition)
{
ILandObject lo = scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y);
string response = DoCommonChecks(objectCount, ownerID, lo, scene);
if (response != null)
{
m_dialogModule.SendAlertToUser(ownerID, response);
return false;
}
return true;
}
private bool CanObjectEnter(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene)
{
if (newPoint.X < -1f || newPoint.X > (scene.RegionInfo.RegionSizeX + 1) ||
newPoint.Y < -1f || newPoint.Y > (scene.RegionInfo.RegionSizeY) )
return true;
SceneObjectPart obj = scene.GetSceneObjectPart(objectID);
if (obj == null)
return false;
// Prim counts are determined by the location of the root prim. if we're
// moving a child prim, just let it pass
if (!obj.IsRoot)
{
return true;
}
ILandObject newParcel = scene.LandChannel.GetLandObject(newPoint.X, newPoint.Y);
if (newParcel == null)
return true;
Vector3 oldPoint = obj.GroupPosition;
ILandObject oldParcel = scene.LandChannel.GetLandObject(oldPoint.X, oldPoint.Y);
// The prim hasn't crossed a region boundry so we don't need to worry
// about prim counts here
if(oldParcel != null && oldParcel.Equals(newParcel))
{
return true;
}
int objectCount = obj.ParentGroup.PrimCount;
int usedPrims = newParcel.PrimCounts.Total;
int simulatorCapacity = newParcel.GetSimulatorMaxPrimCount();
// TODO: Add Special Case here for temporary prims
string response = DoCommonChecks(objectCount, obj.OwnerID, newParcel, scene);
if (response != null)
{
m_dialogModule.SendAlertToUser(obj.OwnerID, response);
return false;
}
return true;
}
private string DoCommonChecks(int objectCount, UUID ownerID, ILandObject lo, Scene scene)
{
string response = null;
int simulatorCapacity = lo.GetSimulatorMaxPrimCount();
if ((objectCount + lo.PrimCounts.Total) > simulatorCapacity)
{
response = "Unable to rez object because the parcel is too full";
}
else
{
int maxPrimsPerUser = scene.RegionInfo.MaxPrimsPerUser;
if (maxPrimsPerUser >= 0)
{
// per-user prim limit is set
if (ownerID != lo.LandData.OwnerID || lo.LandData.IsGroupOwned)
{
// caller is not the sole Parcel owner
EstateSettings estateSettings = scene.RegionInfo.EstateSettings;
if (ownerID != estateSettings.EstateOwner)
{
// caller is NOT the Estate owner
List<UUID> mgrs = new List<UUID>(estateSettings.EstateManagers);
if (!mgrs.Contains(ownerID))
{
// caller is not an Estate Manager
if ((lo.PrimCounts.Users[ownerID] + objectCount) > maxPrimsPerUser)
{
response = "Unable to rez object because you have reached your limit";
}
}
}
}
}
}
return response;
}
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
namespace LibUdt
{
internal enum UdtSockHandle : int { }
internal enum SysSockHandle : int { }
public enum UdtState : int
{
Init = 1, Opened, Listening, Connecting, Connected, Broken, Closing, Closed, NonExist
}
public enum UdtOption : int
{
MaxTransferUnit, // the Maximum Transfer Unit
BlockingSend, // if sending is blocking
BlockingRecv, // if receiving is blocking
CongestionAlgorithm, // custom congestion control algorithm
WindowSize, // Flight flag size (window size)
SendBuf, // maximum buffer in sending queue
RecvBuf, // UDT receiving buffer size
Linger, // waiting for unsent data when closing
UdpSendBuf, // UDP sending buffer size
UdpRecvBuf, // UDP receiving buffer size
MaxMsg, // maximum datagram message size
MsgTtl, // time-to-live of a datagram message
RendezvousMode, // rendezvous connection mode
SendTimeout, // send() timeout
RecvTimeout, // recv() timeout
ReuseAddr, // reuse an existing port or create a new one
MaxBandwidth, // maximum bandwidth (bytes per second) that the connection can use
State, // current socket state, see UDTSTATUS, read only
Event, // current avalable events associated with the socket
SendData, // size of data in the sending buffer
RecvData // size of data available for recv
}
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct SockAddr
{
[StructLayout(LayoutKind.Sequential)]
private struct SockAddrV4
{
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)]
internal byte[] Address;
internal SockAddrV4(IPEndPoint endpoint)
{
this.Address = endpoint.Address.GetAddressBytes();
}
}
[StructLayout(LayoutKind.Sequential)]
private struct SockAddrV6
{
internal uint FlowInfo;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
internal byte[] Address;
private uint ScopeID;
internal SockAddrV6(IPEndPoint endpoint)
{
this.FlowInfo = 0;
this.Address = endpoint.Address.GetAddressBytes();
this.ScopeID = 0;
}
}
private ushort AF;
private ushort Port;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=24)] // sizeof(SockAddrV6)
private byte[] Address;
internal int Size
{
get
{
if (this.AF == (ushort)AddressFamily.InterNetwork)
{
return 16; // sizeof(sockaddr_in)
}
else if (this.AF == (ushort)AddressFamily.InterNetworkV6)
{
return 28; // sizeof(sockaddr_in6)
}
else
{
throw new NotSupportedException();
}
}
}
internal SockAddr(IPEndPoint endpoint)
{
this.AF = (ushort)endpoint.AddressFamily;
this.Port = (ushort)endpoint.Port;
byte[] address = new byte[28];
fixed (byte* p = address)
{
if (endpoint.AddressFamily == AddressFamily.InterNetwork)
{
Marshal.StructureToPtr(new SockAddrV4(endpoint), new IntPtr(p), false);
}
else if (endpoint.AddressFamily == AddressFamily.InterNetworkV6)
{
Marshal.StructureToPtr(new SockAddrV6(endpoint), new IntPtr(p), false);
}
else
{
throw new NotSupportedException();
}
}
this.Address = address;
}
internal IPEndPoint ToIPEndPoint()
{
fixed(byte* p = this.Address)
{
if (this.AF == (ushort)AddressFamily.InterNetwork)
{
SockAddrV4 addrV4 = Marshal.PtrToStructure<SockAddrV4>(new IntPtr(p));
return new IPEndPoint(new IPAddress(addrV4.Address), this.Port);
}
else if (this.AF == (ushort)AddressFamily.InterNetworkV6)
{
SockAddrV6 addrV6 = Marshal.PtrToStructure<SockAddrV6>(new IntPtr(p));
return new IPEndPoint(new IPAddress(addrV6.Address), this.Port);
}
else
{
throw new NotSupportedException();
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct UdtPerfInfo
{
// global measurements
public long msTimeStamp; // time since the UDT entity is started, in milliseconds
public long pktSentTotal; // total number of sent data packets, including retransmissions
public long pktRecvTotal; // total number of received packets
public int pktSndLossTotal; // total number of lost packets (sender side)
public int pktRcvLossTotal; // total number of lost packets (receiver side)
public int pktRetransTotal; // total number of retransmitted packets
public int pktSentACKTotal; // total number of sent ACK packets
public int pktRecvACKTotal; // total number of received ACK packets
public int pktSentNAKTotal; // total number of sent NAK packets
public int pktRecvNAKTotal; // total number of received NAK packets
public long usSndDurationTotal; // total time duration when UDT is sending data (idle time exclusive)
// local measurements
public long pktSent; // number of sent data packets, including retransmissions
public long pktRecv; // number of received packets
public int pktSndLoss; // number of lost packets (sender side)
public int pktRcvLoss; // number of lost packets (receiver side)
public int pktRetrans; // number of retransmitted packets
public int pktSentACK; // number of sent ACK packets
public int pktRecvACK; // number of received ACK packets
public int pktSentNAK; // number of sent NAK packets
public int pktRecvNAK; // number of received NAK packets
public double mbpsSendRate; // sending rate in Mb/s
public double mbpsRecvRate; // receiving rate in Mb/s
public long usSndDuration; // busy sending time (i.e., idle time exclusive)
// instant measurements
public double usPktSndPeriod; // packet sending period, in microseconds
public int pktFlowWindow; // flow window size, in number of packets
public int pktCongestionWindow; // congestion window size, in number of packets
public int pktFlightSize; // number of packets on flight
public double msRTT; // RTT, in milliseconds
public double mbpsBandwidth; // estimated bandwidth, in Mb/s
public int byteAvailSndBuf; // available UDT sender buffer size
public int byteAvailRcvBuf; // available UDT receiver buffer size
}
internal static class UDT
{
[DllImport("libudt", EntryPoint = "udt_startup")]
internal static extern int Startup();
[DllImport("libudt", EntryPoint = "udt_cleanup")]
internal static extern int Cleanup();
[DllImport("libudt", EntryPoint = "udt_socket")]
internal static extern UdtSockHandle CreateSocket(AddressFamily af, SocketType type, ProtocolType protocol);
[DllImport("libudt", EntryPoint = "udt_bind")]
internal static extern int Bind(UdtSockHandle u, ref SockAddr name, int namelen);
[DllImport("libudt", EntryPoint = "udt_listen")]
internal static extern int Listen(UdtSockHandle u, int backlog);
[DllImport("libudt", EntryPoint = "udt_accept")]
internal static extern UdtSockHandle Accept(UdtSockHandle u, out SockAddr name, out int namelen);
[DllImport("libudt", EntryPoint = "udt_connect")]
internal static extern int Connect(UdtSockHandle u, ref SockAddr name, int namelen);
[DllImport("libudt", EntryPoint = "udt_close")]
internal static extern int Close(UdtSockHandle u);
[DllImport("libudt", EntryPoint = "udt_getpeername")]
internal static extern int GetPeerName(UdtSockHandle u, out SockAddr name, out int namelen);
[DllImport("libudt", EntryPoint = "udt_getsockname")]
internal static extern int GetSockName(UdtSockHandle u, out SockAddr name, out int namelen);
[DllImport("libudt", EntryPoint = "udt_getsockopt")]
internal static extern int GetSockOpt(UdtSockHandle u, int level, UdtOption optname, out byte[] optval, out int optlen);
[DllImport("libudt", EntryPoint = "udt_setsockopt")]
internal static extern int SetSockOpt(UdtSockHandle u, int level, UdtOption optname, ref byte[] optval, int optlen);
[DllImport("libudt", EntryPoint = "udt_send")]
internal static extern int Send(UdtSockHandle u, byte[] buf, int len, int flags);
[DllImport("libudt", EntryPoint = "udt_recv")]
internal static extern int Recv(UdtSockHandle u, byte[] buf, int len, int flags);
// [DllImport("libudt", EntryPoint = "udt_sendmsg", CharSet = CharSet.Ansi)]
// internal static extern int SendMsg(UdtSockHandle u, string buf, int len, int ttl = -1, bool inorder = false);
// [DllImport("libudt", EntryPoint = "udt_recvmsg", CharSet = CharSet.Ansi)]
// internal static extern int RecvMsg(UdtSockHandle u, StringBuilder buf, int len);
[DllImport("libudt", EntryPoint = "udt_sendmsg")]
internal static extern int SendBytes(UdtSockHandle u, byte[] buf, int len, int ttl = -1, bool inorder = false);
[DllImport("libudt", EntryPoint = "udt_recvmsg")]
internal static extern int RecvBytes(UdtSockHandle u, byte[] buf, int len);
// [DllImport("libudt", EntryPoint = "udt_sendfile")]
// internal static extern long SendFile(UDTSOCKET u, std::fstream& ifs, long& offset, long size, int block = 364000);
// [DllImport("libudt", EntryPoint = "udt_recvfile")]
// internal static extern long RecvFile(UDTSOCKET u, std::fstream& ofs, long& offset, long size, int block = 7280000);
[DllImport("libudt", EntryPoint = "udt_sendfile2")]
internal static extern long SendFile(UdtSockHandle u, string path, ref long offset, long size, int block = 364000);
[DllImport("libudt", EntryPoint = "udt_recvfile2")]
internal static extern long RecvFile(UdtSockHandle u, string path, ref long offset, long size, int block = 7280000);
[DllImport("libudt", EntryPoint = "udt_epoll_create")]
internal static extern int EpollCreate();
// [DllImport("libudt", EntryPoint = "udt_epoll_add_usock")]
// internal static extern int EpollAddUdtSock(int eid, UdtSocketHandle u, const int* events = NULL);
// [DllImport("libudt", EntryPoint = "udt_epoll_add_ssock")]
// internal static extern int EpollAddSysSock(int eid, SysSocketHandle s, const int* events = NULL);
[DllImport("libudt", EntryPoint = "udt_epoll_remove_usock")]
internal static extern int EpollRemoveUdtSock(int eid, UdtSockHandle u);
[DllImport("libudt", EntryPoint = "udt_epoll_remove_ssock")]
internal static extern int EpollRemoveSysSock(int eid, SysSockHandle s);
// [DllImport("libudt", EntryPoint = "udt_epoll_wait")]
// internal static extern int epoll_wait(int eid, std::set<UDTSOCKET>* readfds, std::set<UDTSOCKET>* writefds, long msTimeOut,
// std::set<SYSSOCKET>* lrfds = NULL, std::set<SYSSOCKET>* wrfds = NULL);
// [DllImport("libudt", EntryPoint = "udt_epoll_wait2")]
// internal static extern int epoll_wait2(int eid, UDTSOCKET* readfds, int* rnum, UDTSOCKET* writefds, int* wnum, long msTimeOut,
// SYSSOCKET* lrfds = NULL, int* lrnum = NULL, SYSSOCKET* lwfds = NULL, int* lwnum = NULL);
[DllImport("libudt", EntryPoint = "udt_epoll_release")]
internal static extern int EpollRelease(int eid);
// [DllImport("libudt", EntryPoint = "udt_getlasterror")]
// internal static extern ERRORINFO& getlasterror();
[DllImport("libudt", EntryPoint = "udt_getlasterror_code")]
internal static extern int GetLastErrorCode();
[DllImport("libudt", EntryPoint = "udt_getlasterror_desc")]
internal static extern IntPtr GetLastErrorDesc();
[DllImport("libudt", EntryPoint = "udt_perfmon")]
internal static extern int PerfMon(UdtSockHandle u, out UdtPerfInfo perf, bool clear = true);
[DllImport("libudt", EntryPoint = "udt_getsockstate")]
internal static extern UdtState GetSockState(UdtSockHandle u);
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation.Internal;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace System.Management.Automation.Configuration
{
/// <summary>
/// The scope of the configuration file.
/// </summary>
public enum ConfigScope
{
/// <summary>
/// AllUsers configuration applies to all users.
/// </summary>
AllUsers = 0,
/// <summary>
/// CurrentUser configuration applies to the current user.
/// </summary>
CurrentUser = 1
}
/// <summary>
/// Reads from and writes to the JSON configuration files.
/// The config values were originally stored in the Windows registry.
/// </summary>
/// <remarks>
/// The config file access APIs are designed to avoid hitting the disk as much as possible.
/// - For the first read request targeting a config file, the config data is read from the file and then cached as a 'JObject' instance;
/// * the first read request happens very early during the startup of 'pwsh'.
/// - For the subsequent read requests targeting the same config file, they will then work with that 'JObject' instance;
/// - For the write request targeting a config file, the cached config data corresponding to that config file will be refreshed after the write operation is successfully done.
///
/// To summarize the expected behavior:
/// Once a 'pwsh' process starts up -
/// 1. any changes made to the config file from outside this 'pwsh' process is not guaranteed to be seen by it (most likely won't be seen).
/// 2. any changes to the config file by this 'pwsh' process via the config file access APIs will be seen by it, if it chooses to read those changes afterwards.
/// </remarks>
internal sealed class PowerShellConfig
{
private const string ConfigFileName = "powershell.config.json";
private const string ExecutionPolicyDefaultShellKey = "Microsoft.PowerShell:ExecutionPolicy";
private const string DisableImplicitWinCompatKey = "DisableImplicitWinCompat";
private const string WindowsPowerShellCompatibilityModuleDenyListKey = "WindowsPowerShellCompatibilityModuleDenyList";
private const string WindowsPowerShellCompatibilityNoClobberModuleListKey = "WindowsPowerShellCompatibilityNoClobberModuleList";
// Provide a singleton
internal static readonly PowerShellConfig Instance = new PowerShellConfig();
// The json file containing system-wide configuration settings.
// When passed as a pwsh command-line option, overrides the system wide configuration file.
private string systemWideConfigFile;
private string systemWideConfigDirectory;
// The json file containing the per-user configuration settings.
private readonly string perUserConfigFile;
private readonly string perUserConfigDirectory;
// Note: JObject and JsonSerializer are thread safe.
// Root Json objects corresponding to the configuration file for 'AllUsers' and 'CurrentUser' respectively.
// They are used as a cache to avoid hitting the disk for every read operation.
private readonly JObject[] configRoots;
private readonly JObject emptyConfig;
private readonly JsonSerializer serializer;
/// <summary>
/// Lock used to enable multiple concurrent readers and singular write locks within a single process.
/// TODO: This solution only works for IO from a single process.
/// A more robust solution is needed to enable ReaderWriterLockSlim behavior between processes.
/// </summary>
private readonly ReaderWriterLockSlim fileLock;
private PowerShellConfig()
{
// Sets the system-wide configuration file.
systemWideConfigDirectory = Utils.DefaultPowerShellAppBase;
systemWideConfigFile = Path.Combine(systemWideConfigDirectory, ConfigFileName);
// Sets the per-user configuration directory
// Note: This directory may or may not exist depending upon the execution scenario.
// Writes will attempt to create the directory if it does not already exist.
perUserConfigDirectory = Platform.ConfigDirectory;
perUserConfigFile = Path.Combine(perUserConfigDirectory, ConfigFileName);
emptyConfig = new JObject();
configRoots = new JObject[2];
serializer = JsonSerializer.Create(new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None, MaxDepth = 10 });
fileLock = new ReaderWriterLockSlim();
}
private string GetConfigFilePath(ConfigScope scope)
{
return (scope == ConfigScope.CurrentUser) ? perUserConfigFile : systemWideConfigFile;
}
/// <summary>
/// Sets the system wide configuration file path.
/// </summary>
/// <param name="value">A fully qualified path to the system wide configuration file.</param>
/// <exception cref="FileNotFoundException"><paramref name="value"/> is a null reference or the associated file does not exist.</exception>
/// <remarks>
/// This method is for use when processing the -SettingsFile configuration setting and should not be used for any other purpose.
/// </remarks>
internal void SetSystemConfigFilePath(string value)
{
if (!string.IsNullOrEmpty(value) && !File.Exists(value))
{
throw new FileNotFoundException(value);
}
FileInfo info = new FileInfo(value);
systemWideConfigFile = info.FullName;
systemWideConfigDirectory = info.Directory.FullName;
}
/// <summary>
/// Existing Key = HKLM:\System\CurrentControlSet\Control\Session Manager\Environment
/// Proposed value = %ProgramFiles%\PowerShell\Modules by default
/// Note: There is no setter because this value is immutable.
/// </summary>
/// <param name="scope">Whether this is a system-wide or per-user setting.</param>
/// <returns>Value if found, null otherwise. The behavior matches ModuleIntrinsics.GetExpandedEnvironmentVariable().</returns>
internal string GetModulePath(ConfigScope scope)
{
string modulePath = ReadValueFromFile<string>(scope, Constants.PSModulePathEnvVar);
if (!string.IsNullOrEmpty(modulePath))
{
modulePath = Environment.ExpandEnvironmentVariables(modulePath);
}
return modulePath;
}
/// <summary>
/// Existing Key = HKCU and HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
/// Proposed value = Existing default execution policy if not already specified
///
/// Schema:
/// {
/// "shell-ID-string:ExecutionPolicy" : "execution policy string"
/// }
///
/// TODO: In a single config file, it might be better to nest this. It is unnecessary complexity until a need arises for more nested values.
/// </summary>
/// <param name="scope">Whether this is a system-wide or per-user setting.</param>
/// <param name="shellId">The shell associated with this policy. Typically, it is "Microsoft.PowerShell".</param>
/// <returns>The execution policy if found. Null otherwise.</returns>
internal string GetExecutionPolicy(ConfigScope scope, string shellId)
{
string key = GetExecutionPolicySettingKey(shellId);
string execPolicy = ReadValueFromFile<string>(scope, key);
return string.IsNullOrEmpty(execPolicy) ? null : execPolicy;
}
internal void RemoveExecutionPolicy(ConfigScope scope, string shellId)
{
string key = GetExecutionPolicySettingKey(shellId);
RemoveValueFromFile<string>(scope, key);
}
internal void SetExecutionPolicy(ConfigScope scope, string shellId, string executionPolicy)
{
string key = GetExecutionPolicySettingKey(shellId);
WriteValueToFile<string>(scope, key, executionPolicy);
}
private static string GetExecutionPolicySettingKey(string shellId)
{
return string.Equals(shellId, Utils.DefaultPowerShellShellID, StringComparison.Ordinal)
? ExecutionPolicyDefaultShellKey
: string.Concat(shellId, ":", "ExecutionPolicy");
}
/// Get the names of experimental features enabled in the config file.
/// </summary>
internal string[] GetExperimentalFeatures()
{
string[] features = ReadValueFromFile(ConfigScope.CurrentUser, "ExperimentalFeatures", Array.Empty<string>());
if (features.Length == 0)
{
features = ReadValueFromFile(ConfigScope.AllUsers, "ExperimentalFeatures", Array.Empty<string>());
}
return features;
}
/// <summary>
/// Set the enabled list of experimental features in the config file.
/// </summary>
/// <param name="scope">The ConfigScope of the configuration file to update.</param>
/// <param name="featureName">The name of the experimental feature to change in the configuration.</param>
/// <param name="setEnabled">If true, add to configuration; otherwise, remove from configuration.</param>
internal void SetExperimentalFeatures(ConfigScope scope, string featureName, bool setEnabled)
{
var features = new List<string>(GetExperimentalFeatures());
bool containsFeature = features.Contains(featureName);
if (setEnabled && !containsFeature)
{
features.Add(featureName);
WriteValueToFile<string[]>(scope, "ExperimentalFeatures", features.ToArray());
}
else if (!setEnabled && containsFeature)
{
features.Remove(featureName);
WriteValueToFile<string[]>(scope, "ExperimentalFeatures", features.ToArray());
}
}
internal bool IsImplicitWinCompatEnabled()
{
bool settingValue = ReadValueFromFile<bool?>(ConfigScope.CurrentUser, DisableImplicitWinCompatKey)
?? ReadValueFromFile<bool?>(ConfigScope.AllUsers, DisableImplicitWinCompatKey)
?? false;
return !settingValue;
}
internal string[] GetWindowsPowerShellCompatibilityModuleDenyList()
{
return ReadValueFromFile<string[]>(ConfigScope.CurrentUser, WindowsPowerShellCompatibilityModuleDenyListKey)
?? ReadValueFromFile<string[]>(ConfigScope.AllUsers, WindowsPowerShellCompatibilityModuleDenyListKey);
}
internal string[] GetWindowsPowerShellCompatibilityNoClobberModuleList()
{
return ReadValueFromFile<string[]>(ConfigScope.CurrentUser, WindowsPowerShellCompatibilityNoClobberModuleListKey)
?? ReadValueFromFile<string[]>(ConfigScope.AllUsers, WindowsPowerShellCompatibilityNoClobberModuleListKey);
}
/// <summary>
/// Corresponding settings of the original Group Policies.
/// </summary>
internal PowerShellPolicies GetPowerShellPolicies(ConfigScope scope)
{
return ReadValueFromFile<PowerShellPolicies>(scope, nameof(PowerShellPolicies));
}
#if UNIX
/// <summary>
/// Gets the identity name to use for writing to syslog.
/// </summary>
/// <returns>
/// The string identity to use for writing to syslog. The default value is 'powershell'.
/// </returns>
internal string GetSysLogIdentity()
{
string identity = ReadValueFromFile<string>(ConfigScope.AllUsers, "LogIdentity");
if (string.IsNullOrEmpty(identity) ||
identity.Equals(LogDefaultValue, StringComparison.OrdinalIgnoreCase))
{
identity = "powershell";
}
return identity;
}
/// <summary>
/// Gets the log level filter.
/// </summary>
/// <returns>
/// One of the PSLevel values indicating the level to log. The default value is PSLevel.Informational.
/// </returns>
internal PSLevel GetLogLevel()
{
string levelName = ReadValueFromFile<string>(ConfigScope.AllUsers, "LogLevel");
PSLevel level;
if (string.IsNullOrEmpty(levelName) ||
levelName.Equals(LogDefaultValue, StringComparison.OrdinalIgnoreCase) ||
!Enum.TryParse<PSLevel>(levelName, true, out level))
{
level = PSLevel.Informational;
}
return level;
}
/// <summary>
/// The supported separator characters for listing channels and keywords in configuration.
/// </summary>
private static readonly char[] s_valueSeparators = new char[] {' ', ',', '|'};
/// <summary>
/// Provides a string name to indicate the default for a configuration setting.
/// </summary>
private const string LogDefaultValue = "default";
/// <summary>
/// Gets the bitmask of the PSChannel values to log.
/// </summary>
/// <returns>
/// A bitmask of PSChannel.Operational and/or PSChannel.Analytic. The default value is PSChannel.Operational.
/// </returns>
internal PSChannel GetLogChannels()
{
string values = ReadValueFromFile<string>(ConfigScope.AllUsers, "LogChannels");
PSChannel result = 0;
if (!string.IsNullOrEmpty(values))
{
string[] names = values.Split(s_valueSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (string name in names)
{
if (name.Equals(LogDefaultValue, StringComparison.OrdinalIgnoreCase))
{
result = 0;
break;
}
PSChannel value;
if (Enum.TryParse<PSChannel>(name, true, out value))
{
result |= value;
}
}
}
if (result == 0)
{
result = System.Management.Automation.Tracing.PSSysLogProvider.DefaultChannels;
}
return result;
}
/// <summary>
/// Gets the bitmask of keywords to log.
/// </summary>
/// <returns>
/// A bitmask of PSKeyword values. The default value is all keywords other than UseAlwaysAnalytic.
/// </returns>
internal PSKeyword GetLogKeywords()
{
string values = ReadValueFromFile<string>(ConfigScope.AllUsers, "LogKeywords");
PSKeyword result = 0;
if (!string.IsNullOrEmpty(values))
{
string[] names = values.Split(s_valueSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (string name in names)
{
if (name.Equals(LogDefaultValue, StringComparison.OrdinalIgnoreCase))
{
result = 0;
break;
}
PSKeyword value;
if (Enum.TryParse<PSKeyword>(name, true, out value))
{
result |= value;
}
}
}
if (result == 0)
{
result = System.Management.Automation.Tracing.PSSysLogProvider.DefaultKeywords;
}
return result;
}
#endif // UNIX
/// <summary>
/// Read a value from the configuration file.
/// </summary>
/// <typeparam name="T">The type of the value</typeparam>
/// <param name="scope">The ConfigScope of the configuration file to update.</param>
/// <param name="key">The string key of the value.</param>
/// <param name="defaultValue">The default value to return if the key is not present.</param>
private T ReadValueFromFile<T>(ConfigScope scope, string key, T defaultValue = default)
{
string fileName = GetConfigFilePath(scope);
JObject configData = configRoots[(int)scope];
if (configData == null)
{
if (File.Exists(fileName))
{
try
{
// Open file for reading, but allow multiple readers
fileLock.EnterReadLock();
using var stream = OpenFileStreamWithRetry(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var jsonReader = new JsonTextReader(new StreamReader(stream));
configData = serializer.Deserialize<JObject>(jsonReader) ?? emptyConfig;
}
catch (Exception exc)
{
throw PSTraceSource.NewInvalidOperationException(exc, PSConfigurationStrings.CanNotConfigurationFile, args: fileName);
}
finally
{
fileLock.ExitReadLock();
}
}
else
{
configData = emptyConfig;
}
// Set the configuration cache.
JObject originalValue = Interlocked.CompareExchange(ref configRoots[(int)scope], configData, null);
if (originalValue != null)
{
configData = originalValue;
}
}
if (configData != emptyConfig && configData.TryGetValue(key, StringComparison.OrdinalIgnoreCase, out JToken jToken))
{
return jToken.ToObject<T>(serializer) ?? defaultValue;
}
return defaultValue;
}
private static FileStream OpenFileStreamWithRetry(string fullPath, FileMode mode, FileAccess access, FileShare share)
{
const int MaxTries = 5;
for (int numTries = 0; numTries < MaxTries; numTries++)
{
try
{
return new FileStream(fullPath, mode, access, share);
}
catch (IOException)
{
if (numTries == (MaxTries - 1))
{
throw;
}
Thread.Sleep(50);
}
}
throw new IOException(nameof(OpenFileStreamWithRetry));
}
/// <summary>
/// Update a value in the configuration file.
/// </summary>
/// <typeparam name="T">The type of the value</typeparam>
/// <param name="scope">The ConfigScope of the configuration file to update.</param>
/// <param name="key">The string key of the value.</param>
/// <param name="value">The value to set.</param>
/// <param name="addValue">Whether the key-value pair should be added to or removed from the file.</param>
private void UpdateValueInFile<T>(ConfigScope scope, string key, T value, bool addValue)
{
try
{
string fileName = GetConfigFilePath(scope);
fileLock.EnterWriteLock();
// Since multiple properties can be in a single file, replacement is required instead of overwrite if a file already exists.
// Handling the read and write operations within a single FileStream prevents other processes from reading or writing the file while
// the update is in progress. It also locks out readers during write operations.
JObject jsonObject = null;
using FileStream fs = OpenFileStreamWithRetry(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
// UTF8, BOM detection, and bufferSize are the same as the basic stream constructor.
// The most important parameter here is the last one, which keeps underlying stream open after StreamReader is disposed
// so that it can be reused for the subsequent write operation.
using (StreamReader streamRdr = new StreamReader(fs, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
using (JsonTextReader jsonReader = new JsonTextReader(streamRdr))
{
// Safely determines whether there is content to read from the file
bool isReadSuccess = jsonReader.Read();
if (isReadSuccess)
{
// Read the stream into a root JObject for manipulation
jsonObject = serializer.Deserialize<JObject>(jsonReader);
JProperty propertyToModify = jsonObject.Property(key);
if (propertyToModify == null)
{
// The property doesn't exist, so add it
if (addValue)
{
jsonObject.Add(new JProperty(key, value));
}
// else the property doesn't exist so there is nothing to remove
}
else
{
// The property exists
if (addValue)
{
propertyToModify.Replace(new JProperty(key, value));
}
else
{
propertyToModify.Remove();
}
}
}
else
{
// The file doesn't already exist and we want to write to it or it exists with no content.
// A new file will be created that contains only this value.
// If the file doesn't exist and a we don't want to write to it, no action is needed.
if (addValue)
{
jsonObject = new JObject(new JProperty(key, value));
}
else
{
return;
}
}
}
// Reset the stream position to the beginning so that the
// changes to the file can be written to disk
fs.Seek(0, SeekOrigin.Begin);
// Update the file with new content
using (StreamWriter streamWriter = new StreamWriter(fs))
using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
{
// The entire document exists within the root JObject.
// I just need to write that object to produce the document.
jsonObject.WriteTo(jsonWriter);
// This trims the file if the file shrank. If the file grew,
// it is a no-op. The purpose is to trim extraneous characters
// from the file stream when the resultant JObject is smaller
// than the input JObject.
fs.SetLength(fs.Position);
}
// Refresh the configuration cache.
Interlocked.Exchange(ref configRoots[(int)scope], jsonObject);
}
finally
{
fileLock.ExitWriteLock();
}
}
/// <summary>
/// TODO: Should this return success, fail, or throw?
/// </summary>
/// <typeparam name="T">The type of value to write.</typeparam>
/// <param name="scope">The ConfigScope of the file to update.</param>
/// <param name="key">The string key of the value.</param>
/// <param name="value">The value to write.</param>
private void WriteValueToFile<T>(ConfigScope scope, string key, T value)
{
if (scope == ConfigScope.CurrentUser && !Directory.Exists(perUserConfigDirectory))
{
Directory.CreateDirectory(perUserConfigDirectory);
}
UpdateValueInFile<T>(scope, key, value, true);
}
/// <summary>
/// TODO: Should this return success, fail, or throw?
/// </summary>
/// <typeparam name="T">The type of value to remove.</typeparam>
/// <param name="scope">The ConfigScope of the file to update.</param>
/// <param name="key">The string key of the value.</param>
private void RemoveValueFromFile<T>(ConfigScope scope, string key)
{
string fileName = GetConfigFilePath(scope);
// Optimization: If the file doesn't exist, there is nothing to remove
if (File.Exists(fileName))
{
UpdateValueInFile<T>(scope, key, default(T), false);
}
}
}
#region GroupPolicy Configs
/// <summary>
/// The GroupPolicy related settings used in PowerShell are as follows in Registry:
/// - Software\Policies\Microsoft\PowerShellCore -- { EnableScripts (0 or 1); ExecutionPolicy (string) }
/// SubKeys Name-Value-Pairs
/// - ScriptBlockLogging { EnableScriptBlockLogging (0 or 1); EnableScriptBlockInvocationLogging (0 or 1) }
/// - ModuleLogging { EnableModuleLogging (0 or 1); ModuleNames (string[]) }
/// - Transcription { EnableTranscripting (0 or 1); OutputDirectory (string); EnableInvocationHeader (0 or 1) }
/// - UpdatableHelp { DefaultSourcePath (string) }
/// - ConsoleSessionConfiguration { EnableConsoleSessionConfiguration (0 or 1); ConsoleSessionConfigurationName (string) }
/// - Software\Policies\Microsoft\Windows\EventLog
/// SubKeys Name-Value-Pairs
/// - ProtectedEventLogging { EnableProtectedEventLogging (0 or 1); EncryptionCertificate (string[]) }
///
/// The JSON representation is in sync with the 'PowerShellPolicies' type. Here is an example:
/// {
/// "PowerShellPolicies": {
/// "ScriptExecution": {
/// "ExecutionPolicy": "RemoteSigned"
/// },
/// "ScriptBlockLogging": {
/// "EnableScriptBlockInvocationLogging": true,
/// "EnableScriptBlockLogging": false
/// },
/// "ProtectedEventLogging": {
/// "EnableProtectedEventLogging": false,
/// "EncryptionCertificate": [
/// "Joe"
/// ]
/// },
/// "Transcription": {
/// "EnableTranscripting": true,
/// "EnableInvocationHeader": true,
/// "OutputDirectory": "c:\\tmp"
/// },
/// "UpdatableHelp": {
/// "DefaultSourcePath": "f:\\temp"
/// },
/// "ConsoleSessionConfiguration": {
/// "EnableConsoleSessionConfiguration": true,
/// "ConsoleSessionConfigurationName": "name"
/// }
/// }
/// }
/// </summary>
internal sealed class PowerShellPolicies
{
public ScriptExecution ScriptExecution { get; set; }
public ScriptBlockLogging ScriptBlockLogging { get; set; }
public ModuleLogging ModuleLogging { get; set; }
public ProtectedEventLogging ProtectedEventLogging { get; set; }
public Transcription Transcription { get; set; }
public UpdatableHelp UpdatableHelp { get; set; }
public ConsoleSessionConfiguration ConsoleSessionConfiguration { get; set; }
}
internal abstract class PolicyBase { }
/// <summary>
/// Setting about ScriptExecution.
/// </summary>
internal sealed class ScriptExecution : PolicyBase
{
public string ExecutionPolicy { get; set; }
public bool? EnableScripts { get; set; }
}
/// <summary>
/// Setting about ScriptBlockLogging.
/// </summary>
internal sealed class ScriptBlockLogging : PolicyBase
{
public bool? EnableScriptBlockInvocationLogging { get; set; }
public bool? EnableScriptBlockLogging { get; set; }
}
/// <summary>
/// Setting about ModuleLogging.
/// </summary>
internal sealed class ModuleLogging : PolicyBase
{
public bool? EnableModuleLogging { get; set; }
public string[] ModuleNames { get; set; }
}
/// <summary>
/// Setting about Transcription.
/// </summary>
internal sealed class Transcription : PolicyBase
{
public bool? EnableTranscripting { get; set; }
public bool? EnableInvocationHeader { get; set; }
public string OutputDirectory { get; set; }
}
/// <summary>
/// Setting about UpdatableHelp.
/// </summary>
internal sealed class UpdatableHelp : PolicyBase
{
public bool? EnableUpdateHelpDefaultSourcePath { get; set; }
public string DefaultSourcePath { get; set; }
}
/// <summary>
/// Setting about ConsoleSessionConfiguration.
/// </summary>
internal sealed class ConsoleSessionConfiguration : PolicyBase
{
public bool? EnableConsoleSessionConfiguration { get; set; }
public string ConsoleSessionConfigurationName { get; set; }
}
/// <summary>
/// Setting about ProtectedEventLogging.
/// </summary>
internal sealed class ProtectedEventLogging : PolicyBase
{
public bool? EnableProtectedEventLogging { get; set; }
public string[] EncryptionCertificate { get; set; }
}
#endregion
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Yengine
{
public class ScriptConst
{
public static Dictionary<string, ScriptConst> scriptConstants = Init();
/**
* @brief look up the value of a given built-in constant.
* @param name = name of constant
* @returns null: no constant by that name defined
* else: pointer to ScriptConst struct
*/
public static ScriptConst Lookup(string name)
{
ScriptConst sc;
if(!scriptConstants.TryGetValue(name, out sc))
sc = null;
return sc;
}
private static Dictionary<string, ScriptConst> Init()
{
Dictionary<string, ScriptConst> sc = new Dictionary<string, ScriptConst>();
// For every event code, define XMREVENTCODE_<eventname> and XMREVENTMASKn_<eventname> symbols.
for(int i = 0; i < 64; i++)
{
try
{
string s = ((ScriptEventCode)i).ToString();
if((s.Length > 0) && (s[0] >= 'a') && (s[0] <= 'z'))
{
new ScriptConst(sc,
"XMREVENTCODE_" + s,
new CompValuInteger(new TokenTypeInt(null), i));
int n = i / 32 + 1;
int m = 1 << (i % 32);
new ScriptConst(sc,
"XMREVENTMASK" + n + "_" + s,
new CompValuInteger(new TokenTypeInt(null), m));
}
}
catch { }
}
// Also get all the constants from XMRInstAbstract and ScriptBaseClass etc as well.
for(Type t = typeof(XMRInstAbstract); t != typeof(object); t = t.BaseType)
{
AddInterfaceConstants(sc, t.GetFields());
}
return sc;
}
/**
* @brief Add all constants defined by the given interface.
*/
// this one accepts only upper-case named fields
public static void AddInterfaceConstants(Dictionary<string, ScriptConst> sc, FieldInfo[] allFields)
{
List<FieldInfo> ucfs = new List<FieldInfo>(allFields.Length);
foreach(FieldInfo f in allFields)
{
string fieldName = f.Name;
int i;
for(i = fieldName.Length; --i >= 0;)
{
if("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_".IndexOf(fieldName[i]) < 0)
break;
}
if(i < 0)
ucfs.Add(f);
}
AddInterfaceConstants(sc, ucfs.GetEnumerator());
}
// this one accepts all fields given to it
public static void AddInterfaceConstants(Dictionary<string, ScriptConst> sc, IEnumerator<FieldInfo> fields)
{
if(sc == null)
sc = scriptConstants;
for(fields.Reset(); fields.MoveNext();)
{
FieldInfo constField = fields.Current;
Type fieldType = constField.FieldType;
CompValu cv;
// The location of a simple number is the number itself.
// Access to the value gets compiled as an ldc instruction.
if(fieldType == typeof(double))
{
cv = new CompValuFloat(new TokenTypeFloat(null),
(double)(double)constField.GetValue(null));
}
else if(fieldType == typeof(int))
{
cv = new CompValuInteger(new TokenTypeInt(null),
(int)constField.GetValue(null));
}
else if(fieldType == typeof(LSL_Integer))
{
cv = new CompValuInteger(new TokenTypeInt(null),
((LSL_Integer)constField.GetValue(null)).value);
}
// The location of a string is the string itself.
// Access to the value gets compiled as an ldstr instruction.
else if(fieldType == typeof(string))
{
cv = new CompValuString(new TokenTypeStr(null),
(string)constField.GetValue(null));
}
else if(fieldType == typeof(LSL_String))
{
cv = new CompValuString(new TokenTypeStr(null),
(string)(LSL_String)constField.GetValue(null));
}
// The location of everything else (objects) is the static field in the interface definition.
// Access to the value gets compiled as an ldsfld instruction.
else
{
cv = new CompValuSField(TokenType.FromSysType(null, fieldType), constField);
}
// Add to dictionary.
new ScriptConst(sc, constField.Name, cv);
}
}
/**
* @brief Add arbitrary constant available to script compilation.
* CAUTION: These values get compiled-in to a script and must not
* change over time as previously compiled scripts will
* still have the old values.
*/
public static ScriptConst AddConstant(string name, object value)
{
CompValu cv = null;
if(value is char)
{
cv = new CompValuChar(new TokenTypeChar(null), (char)value);
}
if(value is double)
{
cv = new CompValuFloat(new TokenTypeFloat(null), (double)(double)value);
}
if(value is float)
{
cv = new CompValuFloat(new TokenTypeFloat(null), (double)(float)value);
}
if(value is int)
{
cv = new CompValuInteger(new TokenTypeInt(null), (int)value);
}
if(value is string)
{
cv = new CompValuString(new TokenTypeStr(null), (string)value);
}
if(value is LSL_Float)
{
cv = new CompValuFloat(new TokenTypeFloat(null), (double)((LSL_Float)value).value);
}
if(value is LSL_Integer)
{
cv = new CompValuInteger(new TokenTypeInt(null), ((LSL_Integer)value).value);
}
if(value is LSL_Rotation)
{
LSL_Rotation r = (LSL_Rotation)value;
CompValu x = new CompValuFloat(new TokenTypeFloat(null), r.x);
CompValu y = new CompValuFloat(new TokenTypeFloat(null), r.y);
CompValu z = new CompValuFloat(new TokenTypeFloat(null), r.z);
CompValu s = new CompValuFloat(new TokenTypeFloat(null), r.s);
cv = new CompValuRot(new TokenTypeRot(null), x, y, z, s);
}
if(value is LSL_String)
{
cv = new CompValuString(new TokenTypeStr(null), (string)(LSL_String)value);
}
if(value is LSL_Vector)
{
LSL_Vector v = (LSL_Vector)value;
CompValu x = new CompValuFloat(new TokenTypeFloat(null), v.x);
CompValu y = new CompValuFloat(new TokenTypeFloat(null), v.y);
CompValu z = new CompValuFloat(new TokenTypeFloat(null), v.z);
cv = new CompValuVec(new TokenTypeVec(null), x, y, z);
}
if(value is OpenMetaverse.Quaternion)
{
OpenMetaverse.Quaternion r = (OpenMetaverse.Quaternion)value;
CompValu x = new CompValuFloat(new TokenTypeFloat(null), r.X);
CompValu y = new CompValuFloat(new TokenTypeFloat(null), r.Y);
CompValu z = new CompValuFloat(new TokenTypeFloat(null), r.Z);
CompValu s = new CompValuFloat(new TokenTypeFloat(null), r.W);
cv = new CompValuRot(new TokenTypeRot(null), x, y, z, s);
}
if(value is OpenMetaverse.UUID)
{
cv = new CompValuString(new TokenTypeKey(null), value.ToString());
}
if(value is OpenMetaverse.Vector3)
{
OpenMetaverse.Vector3 v = (OpenMetaverse.Vector3)value;
CompValu x = new CompValuFloat(new TokenTypeFloat(null), v.X);
CompValu y = new CompValuFloat(new TokenTypeFloat(null), v.Y);
CompValu z = new CompValuFloat(new TokenTypeFloat(null), v.Z);
cv = new CompValuVec(new TokenTypeVec(null), x, y, z);
}
if(cv == null)
throw new Exception("bad type " + value.GetType().Name);
return new ScriptConst(scriptConstants, name, cv);
}
/*
* Instance variables
*/
public string name;
public CompValu rVal;
private ScriptConst(Dictionary<string, ScriptConst> lc, string name, CompValu rVal)
{
lc.Add(name, this);
this.name = name;
this.rVal = rVal;
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira 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.Collections.Generic;
using System.Linq;
using System.Text;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.Services;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Environments;
using Boo.Lang.Resources;
namespace Boo.Lang.Compiler
{
public static class CompilerErrorFactory
{
public static CompilerError CustomError(Node anchor, string msg)
{
return CustomError(AstUtil.SafeLexicalInfo(anchor), msg);
}
public static CompilerError CustomError(LexicalInfo lexicalInfo, string msg)
{
return new CompilerError(lexicalInfo, msg);
}
public static CompilerError CustomError(string msg)
{
return new CompilerError(msg);
}
public static CompilerError ClassAlreadyHasBaseType(Node node, string className, IType baseType)
{
return Instantiate("BCE0001", node, className, baseType);
}
public static CompilerError NamedParameterMustBeIdentifier(ExpressionPair pair)
{
return Instantiate("BCE0002", pair.First);
}
public static CompilerError NamedArgumentsNotAllowed(Node node)
{
return Instantiate("BCE0003", node);
}
public static CompilerError AmbiguousReference(ReferenceExpression reference, System.Reflection.MemberInfo[] members)
{
return Instantiate("BCE0004", reference, reference.Name, ToNameList(members));
}
public static CompilerError AmbiguousReference(Node node, string name, IEnumerable<IEntity> entities)
{
return Instantiate("BCE0004", node, name, ToStringList(entities));
}
public static CompilerError UnknownIdentifier(Node node, string name)
{
return Instantiate("BCE0005", node, name);
}
public static CompilerError CantCastToValueType(Node node, IType typeName)
{
return Instantiate("BCE0006", node, typeName);
}
public static CompilerError NotAPublicFieldOrProperty(Node node, string name, IType type)
{
return Instantiate("BCE0007", node, name, type);
}
public static CompilerError MissingConstructor(Exception error, Node node, Type type, object[] parameters)
{
return Instantiate("BCE0008", node, error, type, GetSignature(parameters));
}
public static CompilerError AttributeApplicationError(Exception error, Ast.Attribute attribute, Type attributeType)
{
return Instantiate("BCE0009", attribute, error, attributeType, error.Message);
}
public static CompilerError AstAttributeMustBeExternal(Node node, IType attributeType)
{
return Instantiate("BCE0010", node, attributeType);
}
public static CompilerError StepExecutionError(Exception error, ICompilerStep step)
{
return Instantiate("BCE0011", error, step, error.Message);
}
public static CompilerError TypeMustImplementICompilerStep(string typeName)
{
return Instantiate("BCE0012", LexicalInfo.Empty, typeName);
}
public static CompilerError AttributeNotFound(string elementName, string attributeName)
{
return Instantiate("BCE0013", LexicalInfo.Empty, elementName, attributeName);
}
public static CompilerError InvalidAssemblySetUp(Node node)
{
return Instantiate("BCE0014", node);
}
public static CompilerError InvalidNode(Node node)
{
return Instantiate("BCE0015", node, node);
}
public static CompilerError MethodArgumentCount(Node node, string name, int count)
{
return Instantiate("BCE0016", node, name, count);
}
public static CompilerError MethodSignature(Node node, IEntity expectedSignature, string actualSignature)
{
return Instantiate("BCE0017", node, expectedSignature, actualSignature);
}
public static CompilerError NameNotType(Node node, string typeName, IEntity whatItIs, string suggestion)
{
return Instantiate("BCE0018", node, typeName, whatItIs == null ? "not found" : (object)whatItIs, DidYouMeanOrNull(suggestion));
}
public static CompilerError MemberNotFound(MemberReferenceExpression node, INamespace @namespace, string suggestion)
{
return MemberNotFound(node, node.Name, @namespace, suggestion);
}
public static CompilerError MemberNotFound(Node node, string memberName, INamespace @namespace, string suggestion)
{
return Instantiate("BCE0019", node, memberName, @namespace, DidYouMeanOrNull(suggestion));
}
public static CompilerError InstanceRequired(Node node, IMember member)
{
return Instantiate("BCE0020", node, member.DeclaringType, member.Name);
}
public static CompilerError InvalidNamespace(Import import)
{
if (import.AssemblyReference != null)
return Instantiate("BCE0167", import.Expression, import.Namespace, import.AssemblyReference);
return Instantiate("BCE0021", import.Expression, import.Namespace);
}
public static CompilerError IncompatibleExpressionType(Node node, IType expectedType, IType actualType)
{
return Instantiate("BCE0022", node, expectedType, actualType);
}
public static CompilerError NoApropriateOverloadFound(Node node, string signature, string memberName)
{
return Instantiate("BCE0023", node, signature, memberName);
}
public static CompilerError NoApropriateConstructorFound(Node node, IType typeName, string signature)
{
return Instantiate("BCE0024", node, typeName, signature);
}
public static CompilerError InvalidArray(Node node)
{
return Instantiate("BCE0025", node);
}
public static CompilerError BoolExpressionRequired(Node node, IType typeName)
{
return Instantiate("BCE0026", node, typeName);
}
public static CompilerError NoEntryPoint()
{
return Instantiate("BCE0028", LexicalInfo.Empty);
}
public static CompilerError MoreThanOneEntryPoint(Method method)
{
return Instantiate("BCE0029", method);
}
public static CompilerError NotImplemented(Node node, string message)
{
return Instantiate("BCE0031", node, message);
}
public static CompilerError EventArgumentMustBeAMethod(Node node, ITypedEntity eventMember)
{
return Instantiate("BCE0032", node, eventMember, eventMember.Type, LanguageAmbiance.CallableKeyword);
}
public static CompilerError TypeNotAttribute(Node node, IType attributeType)
{
return Instantiate("BCE0033", node, attributeType);
}
public static CompilerError ExpressionMustBeExecutedForItsSideEffects(Node node)
{
return Instantiate("BCE0034", node);
}
public static CompilerError ConflictWithInheritedMember(Node node, IMember member, IMember baseMember)
{
return Instantiate("BCE0035", node, member, baseMember);
}
public static CompilerError InvalidTypeof(Node node)
{
return Instantiate("BCE0036", node);
}
public static CompilerError UnknownMacro(Node node, string name)
{
return Instantiate("BCE0037", node, name);
}
public static CompilerError InvalidMacro(Node node, IType type)
{
return Instantiate("BCE0038", node, type);
}
public static CompilerError AstMacroMustBeExternal(Node node, IType type)
{
return Instantiate("BCE0039", node, type);
}
public static CompilerError UnableToLoadAssembly(Node node, string name, Exception error)
{
return Instantiate("BCE0041", node, error, name);
}
public static CompilerError InputError(string inputName, Exception error)
{
return InputError(new LexicalInfo(inputName), error);
}
public static CompilerError InputError(LexicalInfo lexicalInfo, Exception error)
{
return Instantiate("BCE0042", lexicalInfo, error, lexicalInfo.FileName, error.Message);
}
public static CompilerError UnexpectedToken(LexicalInfo lexicalInfo, Exception error, string token)
{
return Instantiate("BCE0043", lexicalInfo, error, token);
}
public static CompilerError GenericParserError(LexicalInfo lexicalInfo, Exception error)
{
return Instantiate("BCE0044", lexicalInfo, error, error.Message);
}
public static CompilerError MacroExpansionError(Node node, Exception error)
{
return Instantiate("BCE0045", node, error, error.Message);
}
public static CompilerError MacroExpansionError(Node node)
{
return Instantiate("BCE0045", node, StringResources.BooC_InvalidNestedMacroContext);
}
public static CompilerError OperatorCantBeUsedWithValueType(Node node, string operatorName, IType typeName)
{
return Instantiate("BCE0046", node, operatorName, typeName);
}
public static CompilerError CantOverrideNonVirtual(Node node, IMethod method)
{
return Instantiate("BCE0047", node, method);
}
public static CompilerError TypeDoesNotSupportSlicing(Node node, IType fullName)
{
return Instantiate("BCE0048", node, fullName);
}
public static CompilerError LValueExpected(Node node)
{
return Instantiate("BCE0049", node, StripSurroundingParens(node.ToCodeString()));
}
public static CompilerError InvalidOperatorForType(Node node, string operatorName, IType typeName)
{
return Instantiate("BCE0050", node, operatorName, typeName);
}
public static CompilerError InvalidOperatorForTypes(Node node, string operatorName, IType lhs, IType rhs)
{
return Instantiate("BCE0051", node, operatorName, lhs, rhs);
}
public static CompilerError InvalidLen(Node node, IType typeName)
{
return Instantiate("BCE0052", node, typeName);
}
public static CompilerError PropertyIsReadOnly(Node node, IProperty property)
{
return Instantiate("BCE0053", node, property);
}
public static CompilerError IsaArgument(Node node)
{
return Instantiate("BCE0054", node, LanguageAmbiance.IsaKeyword);
}
public static CompilerError InternalError(Node node, Exception error)
{
string message = error != null ? error.Message : string.Empty;
return InternalError(node, message, error);
}
public static CompilerError InternalError(Node node, string message, Exception cause)
{
return Instantiate("BCE0055", node, cause, message);
}
public static CompilerError FileNotFound(string fname)
{
return Instantiate("BCE0056", new LexicalInfo(fname), fname);
}
public static CompilerError CantRedefinePrimitive(Node node, string name)
{
return Instantiate("BCE0057", node, name);
}
public static CompilerError SelfIsNotValidInStaticMember(Node node)
{
return Instantiate("BCE0058", node, SelfKeyword);
}
private static string SelfKeyword
{
get { return LanguageAmbiance.SelfKeyword; }
}
private static LanguageAmbiance LanguageAmbiance
{
get { return My<LanguageAmbiance>.Instance; }
}
public static CompilerError InvalidLockMacroArguments(Node node)
{
return Instantiate("BCE0059", node);
}
public static CompilerError NoMethodToOverride(Node node, IMethod signature, bool incompatibleSignature)
{
return Instantiate("BCE0060", node, signature,
incompatibleSignature ? StringResources.BCE0060_IncompatibleSignature : null);
}
public static CompilerError NoMethodToOverride(Node node, IMethod signature, string suggestion)
{
return Instantiate("BCE0060", node, signature, DidYouMeanOrNull(suggestion));
}
public static CompilerError MethodIsNotOverride(Node node, IMethod method)
{
return Instantiate("BCE0061", node, method);
}
public static CompilerError CouldNotInferReturnType(Node node, string signature)
{
return Instantiate("BCE0062", node, signature);
}
public static CompilerError NoEnclosingLoop(Node node)
{
return Instantiate("BCE0063", node);
}
public static CompilerError UnknownAttribute(Node node, string attributeName, string suggestion)
{
return Instantiate("BCE0064", node, attributeName, DidYouMeanOrNull(suggestion));
}
public static CompilerError InvalidIteratorType(Node node, IType type)
{
return Instantiate("BCE0065", node, type);
}
public static CompilerError InvalidNodeForAttribute(Node node, string attributeName, string expectedNodeTypes)
{
return Instantiate("BCE0066", node, attributeName, expectedNodeTypes);
}
public static CompilerError LocalAlreadyExists(Node node, string name)
{
return Instantiate("BCE0067", node, name);
}
public static CompilerError PropertyRequiresParameters(Node node, IEntity name)
{
return Instantiate("BCE0068", node, name);
}
public static CompilerError InterfaceCanOnlyInheritFromInterface(Node node, IType interfaceType, IType baseType)
{
return Instantiate("BCE0069", node, interfaceType, baseType);
}
public static CompilerError UnresolvedDependency(Node node, IEntity source, IEntity target)
{
return Instantiate("BCE0070", node, source, target);
}
public static CompilerError InheritanceCycle(Node node, IType type)
{
return Instantiate("BCE0071", node, type);
}
public static CompilerError InvalidOverrideReturnType(Node node, IMethod method, IType expectedReturnType, IType actualReturnType)
{
return Instantiate("BCE0072", node, method, expectedReturnType, actualReturnType);
}
public static CompilerError AbstractMethodCantHaveBody(Node node, IMethod method)
{
return Instantiate("BCE0073", node, method);
}
public static CompilerError SelfOutsideMethod(Node node)
{
return Instantiate("BCE0074", node, SelfKeyword);
}
public static CompilerError NamespaceIsNotAnExpression(Node node, string name)
{
return Instantiate("BCE0075", node, name);
}
public static CompilerError RuntimeMethodBodyMustBeEmpty(Node node, IMethod method)
{
return Instantiate("BCE0076", node, method);
}
public static CompilerError TypeIsNotCallable(Node node, IType name)
{
return Instantiate("BCE0077", node, name);
}
public static CompilerError MethodReferenceExpected(Node node)
{
return Instantiate("BCE0078", node);
}
public static CompilerError AddressOfOutsideDelegateConstructor(Node node)
{
return Instantiate("BCE0079", node);
}
public static CompilerError BuiltinCannotBeUsedAsExpression(Node node, string name)
{
return Instantiate("BCE0080", node, name);
}
public static CompilerError ReRaiseOutsideExceptionHandler(Node node)
{
return Instantiate("BCE0081", node, LanguageAmbiance.RaiseKeyword);
}
public static CompilerError EventTypeIsNotCallable(Node node, IType typeName)
{
return Instantiate("BCE0082", node, typeName, LanguageAmbiance.CallableKeyword);
}
public static CompilerError StaticConstructorMustBePrivate(Node node)
{
return Instantiate("BCE0083", node);
}
public static CompilerError StaticConstructorCannotDeclareParameters(Node node)
{
return Instantiate("BCE0084", node);
}
public static CompilerError CantCreateInstanceOfAbstractType(Node node, IType typeName)
{
return Instantiate("BCE0085", node, typeName);
}
public static CompilerError CantCreateInstanceOfInterface(Node node, IType typeName)
{
return Instantiate("BCE0086", node, typeName);
}
public static CompilerError CantCreateInstanceOfEnum(Node node, IType typeName)
{
return Instantiate("BCE0087", node, typeName);
}
public static CompilerError MemberNameConflict(Node node, IType declaringType, string memberName)
{
return Instantiate("BCE0089", node, declaringType, memberName);
}
public static CompilerError DerivedMethodCannotReduceAccess(Node node, IMethod derivedMethod, IMethod superMethod, TypeMemberModifiers derivedAccess, TypeMemberModifiers superAccess)
{
return Instantiate("BCE0090", node, derivedMethod, superMethod, superAccess.ToString().ToLower(), derivedAccess.ToString().ToLower());
}
public static CompilerError EventIsNotAnExpression(Node node, IEntity eventMember)
{
return Instantiate("BCE0091", node, eventMember);
}
public static CompilerError InvalidRaiseArgument(Node node, IType typeName)
{
return Instantiate("BCE0092", node, typeName, LanguageAmbiance.RaiseKeyword);
}
public static CompilerError CannotBranchIntoEnsure(Node node)
{
return Instantiate("BCE0093", node, LanguageAmbiance.EnsureKeyword);
}
public static CompilerError CannotBranchIntoExcept(Node node)
{
return Instantiate("BCE0094", node);
}
public static CompilerError NoSuchLabel(Node node, string label)
{
return Instantiate("BCE0095", node, label);
}
public static CompilerError LabelAlreadyDefined(Node node, IMethod method, string label)
{
return Instantiate("BCE0096", node, method, label);
}
public static CompilerError CannotBranchIntoTry(Node node)
{
return Instantiate("BCE0097", node, LanguageAmbiance.TryKeyword);
}
public static CompilerError InvalidSwitch(Node node)
{
return Instantiate("BCE0098", node);
}
public static CompilerError YieldInsideTryExceptOrEnsureBlock(Node node)
{
return Instantiate("BCE0099", node, LanguageAmbiance.TryKeyword, LanguageAmbiance.ExceptKeyword, LanguageAmbiance.EnsureKeyword);
}
public static CompilerError YieldInsideConstructor(Node node)
{
return Instantiate("BCE0100", node);
}
public static CompilerError InvalidGeneratorReturnType(Node node, IType type)
{
return Instantiate("BCE0101", node, type, LanguageAmbiance.DefaultGeneratorTypeFor(type.DisplayName()));
}
public static CompilerError GeneratorCantReturnValue(Node node)
{
return Instantiate("BCE0102", node);
}
public static CompilerError CannotExtendFinalType(Node node, IType typeName)
{
return Instantiate("BCE0103", node, typeName);
}
public static CompilerError CantBeMarkedTransient(Node node)
{
return Instantiate("BCE0104", node);
}
public static CompilerError CantBeMarkedAbstract(Node node)
{
return Instantiate("BCE0105", node);
}
public static CompilerError FailedToLoadTypesFromAssembly(string assemblyName, Exception x)
{
return Instantiate("BCE0106", LexicalInfo.Empty, x, assemblyName);
}
public static CompilerError ValueTypesCannotDeclareParameterlessConstructors(Node node)
{
return Instantiate("BCE0107", node);
}
public static CompilerError ValueTypeFieldsCannotHaveInitializers(Node node)
{
return Instantiate("BCE0108", node);
}
public static CompilerError InvalidArrayRank(Node node, string arrayName, int real, int given)
{
return Instantiate("BCE0109", node, arrayName, real, given);
}
public static CompilerError NotANamespace(Node node, IEntity entity)
{
return Instantiate("BCE0110", node, entity);
}
public static CompilerError InvalidDestructorModifier(Node node)
{
return Instantiate("BCE0111", node);
}
public static CompilerError CantHaveDestructorParameters(Node node)
{
return Instantiate("BCE0112", node);
}
public static CompilerError InvalidCharLiteral(Node node, string value)
{
return Instantiate("BCE0113", node, value);
}
public static CompilerError InvalidInterfaceForInterfaceMember(Node node, string value)
{
return Instantiate("BCE0114", node, value);
}
public static CompilerError InterfaceImplForInvalidInterface(Node node, string iface, string item)
{
return Instantiate("BCE0115", node, iface, item);
}
public static CompilerError ExplicitImplMustNotHaveModifiers(Node node, string iface, string item)
{
return Instantiate("BCE0116", node, iface, item);
}
public static CompilerError FieldIsReadonly(Node node, string name)
{
return Instantiate("BCE0117", node, name);
}
public static CompilerError ExplodedExpressionMustBeArray(Node node)
{
return Instantiate("BCE0118", node);
}
public static CompilerError ExplodeExpressionMustMatchVarArgCall(Node node)
{
return Instantiate("BCE0119", node, LanguageAmbiance.CallableKeyword);
}
public static CompilerError UnaccessibleMember(Node node, IAccessibleMember name)
{
return Instantiate("BCE0120", node, name);
}
public static CompilerError InvalidSuper(Node node)
{
return Instantiate("BCE0121", node);
}
public static CompilerError ValueTypeCantHaveAbstractMember(Node node, IType type, IMember abstractMember)
{
return Instantiate("BCE0122", node, type, abstractMember);
}
public static CompilerError InvalidParameterType(Node node, IType typeName)
{
return Instantiate("BCE0123", node, typeName, string.Empty);
}
public static CompilerError InvalidGenericParameterType(Node node, IType type)
{
return Instantiate("BCE0123", node, type, "generic ");
}
public static CompilerError InvalidFieldType(Node node, IType typeName)
{
return Instantiate("BCE0124", node, typeName);
}
public static CompilerError InvalidDeclarationType(Node node, IType type)
{
return Instantiate("BCE0125", node, type);
}
public static CompilerError InvalidExpressionType(Node node, IType type)
{
return Instantiate("BCE0126", node, type);
}
public static CompilerError RefArgTakesLValue(Node node)
{
return Instantiate("BCE0127", node, node.ToCodeString());
}
public static CompilerError InvalidTryStatement(Node node)
{
return Instantiate("BCE0128", node, LanguageAmbiance.TryKeyword, LanguageAmbiance.ExceptKeyword, LanguageAmbiance.FailureKeyword, LanguageAmbiance.EnsureKeyword);
}
public static CompilerError InvalidExtensionDefinition(Node node)
{
return Instantiate("BCE0129", node);
}
public static CompilerError CantBeMarkedPartial(Node node)
{
return Instantiate("BCE0130", node);
}
public static CompilerError InvalidCombinationOfModifiers(Node node, IEntity member, string modifiers)
{
return Instantiate("BCE0131", node, member, modifiers);
}
public static CompilerError NamespaceAlreadyContainsMember(Node node, string container, string member)
{
return Instantiate("BCE0132", node, container, member);
}
public static CompilerError InvalidEntryPoint(Node node)
{
return Instantiate("BCE0133", node);
}
public static CompilerError CannotReturnValue(Method node)
{
return Instantiate("BCE0134", node, node);
}
public static CompilerError InvalidName(Node node, string name)
{
return Instantiate("BCE0135", node, name);
}
public static CompilerError ColonInsteadOfEquals(Node node)
{
return Instantiate("BCE0136", node);
}
public static CompilerError PropertyIsWriteOnly(Node node, IEntity property)
{
return Instantiate("BCE0137", node, property);
}
public static CompilerError NotAGenericDefinition(Node node, string name)
{
return Instantiate("BCE0138", node, name);
}
public static CompilerError GenericDefinitionArgumentCount(Node node, IEntity genericDefinition, int expectedCount)
{
return Instantiate("BCE0139", node, genericDefinition, expectedCount);
}
public static CompilerError YieldTypeDoesNotMatchReturnType(Node node, IType yieldType, IType returnType)
{
return Instantiate("BCE0140", node, yieldType, returnType);
}
public static CompilerError DuplicateParameterName(Node node, string parameter, IMethod method)
{
return Instantiate("BCE0141", node, parameter, method);
}
public static CompilerError ValueTypeParameterCannotUseDefaultAttribute(Node node, string parameter)
{
string method = (node is Method) ? ((Method) node).Name : ((Property) node).Name;
return Instantiate("BCE0142", node, parameter, method);
}
public static CompilerError CantReturnFromEnsure(Node node)
{
return Instantiate("BCE0143", node, LanguageAmbiance.EnsureKeyword);
}
public static CompilerError Obsolete(Node node, IMember member, string message)
{
return Instantiate("BCE0144", node, member, message);
}
public static CompilerError InvalidExceptArgument(Node node, IType exceptionType)
{
return Instantiate("BCE0145", node, exceptionType, LanguageAmbiance.ExceptKeyword);
}
public static CompilerError GenericArgumentMustBeReferenceType(Node node, IGenericParameter parameter, IType argument)
{
return Instantiate("BCE0146", node, argument, parameter, parameter.DeclaringEntity);
}
public static CompilerError GenericArgumentMustBeValueType(Node node, IGenericParameter parameter, IType argument)
{
return Instantiate("BCE0147", node, argument, parameter, parameter.DeclaringEntity);
}
public static CompilerError GenericArgumentMustHaveDefaultConstructor(Node node, IGenericParameter parameter, IType argument)
{
return Instantiate("BCE0148", node, argument, parameter, parameter.DeclaringEntity);
}
public static CompilerError GenericArgumentMustHaveBaseType(Node node, IGenericParameter parameter, IType argument, IType baseType)
{
return Instantiate("BCE0149", node, argument, baseType, parameter, parameter.DeclaringEntity);
}
public static CompilerError CantBeMarkedFinal(Node node)
{
return Instantiate("BCE0150", node);
}
public static CompilerError CantBeMarkedStatic(Node node)
{
return Instantiate("BCE0151", node);
}
public static CompilerError ConstructorCantBePolymorphic(Node node, IMethod ctor)
{
return Instantiate("BCE0152", node, ctor);
}
public static CompilerError InvalidAttributeTarget(Node node, Type attrType, AttributeTargets validOn)
{
return Instantiate("BCE0153", node, attrType, validOn);
}
public static CompilerError MultipleAttributeUsage(Node node, Type attrType)
{
return Instantiate("BCE0154", node, attrType);
}
public static CompilerError CannotCreateAnInstanceOfGenericParameterWithoutDefaultConstructorConstraint(Node node, IType type)
{
return Instantiate("BCE0155", node, type);
}
public static CompilerError EventCanOnlyBeInvokedFromWithinDeclaringClass(Node node, IEvent ev)
{
return Instantiate("BCE0156", node, ev.Name, ev.DeclaringType);
}
public static CompilerError GenericTypesMustBeConstructedToBeInstantiated(Node node)
{
return Instantiate("BCE0157", node);
}
public static CompilerError InstanceMethodInvocationBeforeInitialization(Constructor ctor, MemberReferenceExpression mre)
{
return Instantiate("BCE0158", mre, mre.Name, SelfKeyword);
}
public static CompilerError StructAndClassConstraintsConflict(GenericParameterDeclaration gpd)
{
return Instantiate("BCE0159", gpd, gpd.Name);
}
public static CompilerError StructAndConstructorConstraintsConflict(GenericParameterDeclaration gpd)
{
return Instantiate("BCE0160", gpd, gpd.Name);
}
public static CompilerError TypeConstraintConflictsWithSpecialConstraint(GenericParameterDeclaration gpd, TypeReference type, string constraint)
{
return Instantiate("BCE0161", type, gpd.Name, type, constraint);
}
public static CompilerError InvalidTypeConstraint(GenericParameterDeclaration gpd, TypeReference type)
{
return Instantiate("BCE0162", type, gpd.Name, type);
}
public static CompilerError MultipleBaseTypeConstraints(GenericParameterDeclaration gpd, TypeReference type, TypeReference other)
{
return Instantiate("BCE0163", type, gpd.Name, type, other);
}
public static CompilerError CannotInferGenericMethodArguments(Node node, IMethod method)
{
return Instantiate("BCE0164", node, method);
}
public static CompilerError ExceptionAlreadyHandled(ExceptionHandler dupe, ExceptionHandler previous)
{
return Instantiate("BCE0165",
dupe.Declaration, dupe.Declaration.Type, previous.Declaration.Type,
AstUtil.SafePositionOnlyLexicalInfo(previous.Declaration), LanguageAmbiance.ExceptKeyword);
}
public static CompilerError UnknownClassMacroWithFieldHint(MacroStatement node, string name)
{
return Instantiate("BCE0166", node, name);
}
public static CompilerError PointerIncompatibleType(Node node, IType type)
{
return Instantiate("BCE0168", node, type);
}
public static CompilerError NotAMemberOfExplicitInterface(TypeMember member, IType type)
{
return Instantiate("BCE0169", member, member.Name, type);
}
public static CompilerError EnumMemberMustBeConstant(EnumMember member)
{
return Instantiate("BCE0170", member, member.FullName);
}
public static CompilerError ConstantCannotBeConverted(Node node, IType type)
{
return Instantiate("BCE0171", node, node, type);
}
public static CompilerError InterfaceImplementationMustBePublicOrExplicit(TypeMember node, IMember member)
{
return Instantiate("BCE0172", node, member.DeclaringType);
}
public static CompilerError InvalidRegexOption(RELiteralExpression node, char option)
{
return Instantiate("BCE0173", node, option);
}
public static CompilerError InvalidTypeForExplicitMember(Node node, IType type)
{
return Instantiate("BCE0174", node, type);
}
public static CompilerError NestedTypeCannotExtendEnclosingType(Node node, IType nestedType, IType enclosingType)
{
return Instantiate("BCE0175", node, nestedType, enclosingType);
}
public static CompilerError IncompatiblePartialDefinition(Node node, string typeName, string expectedType, string actualType)
{
return Instantiate("BCE0176", node, typeName, expectedType, actualType);
}
public static CompilerError Instantiate(string code, Exception error, params object[] args)
{
return new CompilerError(code, error, args);
}
public static CompilerError Instantiate(string code, Node anchor, Exception error, params object[] args)
{
return Instantiate(code, AstUtil.SafeLexicalInfo(anchor), error, args);
}
private static CompilerError Instantiate(string code, LexicalInfo location, Exception error, params object[] args)
{
return new CompilerError(code, location, error, args);
}
public static CompilerError Instantiate(string code, Node anchor, params object[] args)
{
return Instantiate(code, AstUtil.SafeLexicalInfo(anchor), args);
}
private static CompilerError Instantiate(string code, LexicalInfo location, params object[] args)
{
return new CompilerError(code, location, Array.ConvertAll<object, string>(args, DisplayStringFor));
}
internal static string DisplayStringFor(object o)
{
if (o == null) return "";
var entity = o as IEntity;
return entity != null ? entity.DisplayName() : o.ToString();
}
public static string ToStringList(System.Collections.IEnumerable names)
{
return Builtins.join(names.Cast<object>().Select(o => DisplayStringFor(o)).OrderBy(_ => _), ", ");
}
public static string ToAssemblyQualifiedNameList(List types)
{
var builder = new StringBuilder();
builder.Append(((Type)types[0]).AssemblyQualifiedName);
for (int i=1; i<types.Count; ++i)
{
builder.Append(", ");
builder.Append(((Type)types[i]).AssemblyQualifiedName);
}
return builder.ToString();
}
public static string GetSignature(object[] parameters)
{
var sb = new StringBuilder("(");
for (int i=0; i<parameters.Length; ++i)
{
if (i > 0) sb.Append(", ");
sb.Append(parameters[i].GetType());
}
sb.Append(")");
return sb.ToString();
}
public static string ToNameList(System.Reflection.MemberInfo[] members)
{
var sb = new StringBuilder();
for (int i=0; i<members.Length; ++i)
{
if (i > 0) sb.Append(", ");
sb.Append(members[i].MemberType.ToString());
sb.Append(" ");
sb.Append(members[i].Name);
}
return sb.ToString();
}
private static string DidYouMeanOrNull(string suggestion)
{
return (null != suggestion)
? string.Format(StringResources.BooC_DidYouMean, suggestion)
: null;
}
private static string StripSurroundingParens(string code)
{
return code.StartsWith("(") ? code.Substring(1, code.Length - 2) : code;
}
}
}
| |
using System;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Digests
{
/**
* implementation of RipeMD see,
* http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
*/
public class RipeMD160Digest
: GeneralDigest
{
private const int DigestLength = 20;
private int H0, H1, H2, H3, H4; // IV's
private int[] X = new int[16];
private int xOff;
/**
* Standard constructor
*/
public RipeMD160Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public RipeMD160Digest(RipeMD160Digest t) : base(t)
{
CopyIn(t);
}
private void CopyIn(RipeMD160Digest t)
{
base.CopyIn(t);
H0 = t.H0;
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "RIPEMD160"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8)
| ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24);
if (xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (int)(bitLength & 0xffffffff);
X[15] = (int)((ulong) bitLength >> 32);
}
private void UnpackWord(
int word,
byte[] outBytes,
int outOff)
{
outBytes[outOff] = (byte)word;
outBytes[outOff + 1] = (byte)((uint) word >> 8);
outBytes[outOff + 2] = (byte)((uint) word >> 16);
outBytes[outOff + 3] = (byte)((uint) word >> 24);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
UnpackWord(H0, output, outOff);
UnpackWord(H1, output, outOff + 4);
UnpackWord(H2, output, outOff + 8);
UnpackWord(H3, output, outOff + 12);
UnpackWord(H4, output, outOff + 16);
Reset();
return DigestLength;
}
/**
* reset the chaining variables to the IV values.
*/
public override void Reset()
{
base.Reset();
H0 = unchecked((int) 0x67452301);
H1 = unchecked((int) 0xefcdab89);
H2 = unchecked((int) 0x98badcfe);
H3 = unchecked((int) 0x10325476);
H4 = unchecked((int) 0xc3d2e1f0);
xOff = 0;
for (int i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
/*
* rotate int x left n bits.
*/
private int RL(
int x,
int n)
{
return (x << n) | (int) ((uint) x >> (32 - n));
}
/*
* f1,f2,f3,f4,f5 are the basic RipeMD160 functions.
*/
/*
* rounds 0-15
*/
private int F1(
int x,
int y,
int z)
{
return x ^ y ^ z;
}
/*
* rounds 16-31
*/
private int F2(
int x,
int y,
int z)
{
return (x & y) | (~x & z);
}
/*
* rounds 32-47
*/
private int F3(
int x,
int y,
int z)
{
return (x | ~y) ^ z;
}
/*
* rounds 48-63
*/
private int F4(
int x,
int y,
int z)
{
return (x & z) | (y & ~z);
}
/*
* rounds 64-79
*/
private int F5(
int x,
int y,
int z)
{
return x ^ (y | ~z);
}
internal override void ProcessBlock()
{
int a, aa;
int b, bb;
int c, cc;
int d, dd;
int e, ee;
a = aa = H0;
b = bb = H1;
c = cc = H2;
d = dd = H3;
e = ee = H4;
//
// Rounds 1 - 16
//
// left
a = RL(a + F1(b,c,d) + X[ 0], 11) + e; c = RL(c, 10);
e = RL(e + F1(a,b,c) + X[ 1], 14) + d; b = RL(b, 10);
d = RL(d + F1(e,a,b) + X[ 2], 15) + c; a = RL(a, 10);
c = RL(c + F1(d,e,a) + X[ 3], 12) + b; e = RL(e, 10);
b = RL(b + F1(c,d,e) + X[ 4], 5) + a; d = RL(d, 10);
a = RL(a + F1(b,c,d) + X[ 5], 8) + e; c = RL(c, 10);
e = RL(e + F1(a,b,c) + X[ 6], 7) + d; b = RL(b, 10);
d = RL(d + F1(e,a,b) + X[ 7], 9) + c; a = RL(a, 10);
c = RL(c + F1(d,e,a) + X[ 8], 11) + b; e = RL(e, 10);
b = RL(b + F1(c,d,e) + X[ 9], 13) + a; d = RL(d, 10);
a = RL(a + F1(b,c,d) + X[10], 14) + e; c = RL(c, 10);
e = RL(e + F1(a,b,c) + X[11], 15) + d; b = RL(b, 10);
d = RL(d + F1(e,a,b) + X[12], 6) + c; a = RL(a, 10);
c = RL(c + F1(d,e,a) + X[13], 7) + b; e = RL(e, 10);
b = RL(b + F1(c,d,e) + X[14], 9) + a; d = RL(d, 10);
a = RL(a + F1(b,c,d) + X[15], 8) + e; c = RL(c, 10);
// right
aa = RL(aa + F5(bb,cc,dd) + X[ 5] + unchecked((int) 0x50a28be6), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa,bb,cc) + X[14] + unchecked((int) 0x50a28be6), 9) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee,aa,bb) + X[ 7] + unchecked((int) 0x50a28be6), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd,ee,aa) + X[ 0] + unchecked((int) 0x50a28be6), 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc,dd,ee) + X[ 9] + unchecked((int) 0x50a28be6), 13) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb,cc,dd) + X[ 2] + unchecked((int) 0x50a28be6), 15) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa,bb,cc) + X[11] + unchecked((int) 0x50a28be6), 15) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee,aa,bb) + X[ 4] + unchecked((int) 0x50a28be6), 5) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd,ee,aa) + X[13] + unchecked((int) 0x50a28be6), 7) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc,dd,ee) + X[ 6] + unchecked((int) 0x50a28be6), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb,cc,dd) + X[15] + unchecked((int) 0x50a28be6), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa,bb,cc) + X[ 8] + unchecked((int) 0x50a28be6), 11) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee,aa,bb) + X[ 1] + unchecked((int) 0x50a28be6), 14) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd,ee,aa) + X[10] + unchecked((int) 0x50a28be6), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc,dd,ee) + X[ 3] + unchecked((int) 0x50a28be6), 12) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb,cc,dd) + X[12] + unchecked((int) 0x50a28be6), 6) + ee; cc = RL(cc, 10);
//
// Rounds 16-31
//
// left
e = RL(e + F2(a,b,c) + X[ 7] + unchecked((int) 0x5a827999), 7) + d; b = RL(b, 10);
d = RL(d + F2(e,a,b) + X[ 4] + unchecked((int) 0x5a827999), 6) + c; a = RL(a, 10);
c = RL(c + F2(d,e,a) + X[13] + unchecked((int) 0x5a827999), 8) + b; e = RL(e, 10);
b = RL(b + F2(c,d,e) + X[ 1] + unchecked((int) 0x5a827999), 13) + a; d = RL(d, 10);
a = RL(a + F2(b,c,d) + X[10] + unchecked((int) 0x5a827999), 11) + e; c = RL(c, 10);
e = RL(e + F2(a,b,c) + X[ 6] + unchecked((int) 0x5a827999), 9) + d; b = RL(b, 10);
d = RL(d + F2(e,a,b) + X[15] + unchecked((int) 0x5a827999), 7) + c; a = RL(a, 10);
c = RL(c + F2(d,e,a) + X[ 3] + unchecked((int) 0x5a827999), 15) + b; e = RL(e, 10);
b = RL(b + F2(c,d,e) + X[12] + unchecked((int) 0x5a827999), 7) + a; d = RL(d, 10);
a = RL(a + F2(b,c,d) + X[ 0] + unchecked((int) 0x5a827999), 12) + e; c = RL(c, 10);
e = RL(e + F2(a,b,c) + X[ 9] + unchecked((int) 0x5a827999), 15) + d; b = RL(b, 10);
d = RL(d + F2(e,a,b) + X[ 5] + unchecked((int) 0x5a827999), 9) + c; a = RL(a, 10);
c = RL(c + F2(d,e,a) + X[ 2] + unchecked((int) 0x5a827999), 11) + b; e = RL(e, 10);
b = RL(b + F2(c,d,e) + X[14] + unchecked((int) 0x5a827999), 7) + a; d = RL(d, 10);
a = RL(a + F2(b,c,d) + X[11] + unchecked((int) 0x5a827999), 13) + e; c = RL(c, 10);
e = RL(e + F2(a,b,c) + X[ 8] + unchecked((int) 0x5a827999), 12) + d; b = RL(b, 10);
// right
ee = RL(ee + F4(aa,bb,cc) + X[ 6] + unchecked((int) 0x5c4dd124), 9) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee,aa,bb) + X[11] + unchecked((int) 0x5c4dd124), 13) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd,ee,aa) + X[ 3] + unchecked((int) 0x5c4dd124), 15) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc,dd,ee) + X[ 7] + unchecked((int) 0x5c4dd124), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb,cc,dd) + X[ 0] + unchecked((int) 0x5c4dd124), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa,bb,cc) + X[13] + unchecked((int) 0x5c4dd124), 8) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee,aa,bb) + X[ 5] + unchecked((int) 0x5c4dd124), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd,ee,aa) + X[10] + unchecked((int) 0x5c4dd124), 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc,dd,ee) + X[14] + unchecked((int) 0x5c4dd124), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb,cc,dd) + X[15] + unchecked((int) 0x5c4dd124), 7) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa,bb,cc) + X[ 8] + unchecked((int) 0x5c4dd124), 12) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee,aa,bb) + X[12] + unchecked((int) 0x5c4dd124), 7) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd,ee,aa) + X[ 4] + unchecked((int) 0x5c4dd124), 6) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc,dd,ee) + X[ 9] + unchecked((int) 0x5c4dd124), 15) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb,cc,dd) + X[ 1] + unchecked((int) 0x5c4dd124), 13) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa,bb,cc) + X[ 2] + unchecked((int) 0x5c4dd124), 11) + dd; bb = RL(bb, 10);
//
// Rounds 32-47
//
// left
d = RL(d + F3(e,a,b) + X[ 3] + unchecked((int) 0x6ed9eba1), 11) + c; a = RL(a, 10);
c = RL(c + F3(d,e,a) + X[10] + unchecked((int) 0x6ed9eba1), 13) + b; e = RL(e, 10);
b = RL(b + F3(c,d,e) + X[14] + unchecked((int) 0x6ed9eba1), 6) + a; d = RL(d, 10);
a = RL(a + F3(b,c,d) + X[ 4] + unchecked((int) 0x6ed9eba1), 7) + e; c = RL(c, 10);
e = RL(e + F3(a,b,c) + X[ 9] + unchecked((int) 0x6ed9eba1), 14) + d; b = RL(b, 10);
d = RL(d + F3(e,a,b) + X[15] + unchecked((int) 0x6ed9eba1), 9) + c; a = RL(a, 10);
c = RL(c + F3(d,e,a) + X[ 8] + unchecked((int) 0x6ed9eba1), 13) + b; e = RL(e, 10);
b = RL(b + F3(c,d,e) + X[ 1] + unchecked((int) 0x6ed9eba1), 15) + a; d = RL(d, 10);
a = RL(a + F3(b,c,d) + X[ 2] + unchecked((int) 0x6ed9eba1), 14) + e; c = RL(c, 10);
e = RL(e + F3(a,b,c) + X[ 7] + unchecked((int) 0x6ed9eba1), 8) + d; b = RL(b, 10);
d = RL(d + F3(e,a,b) + X[ 0] + unchecked((int) 0x6ed9eba1), 13) + c; a = RL(a, 10);
c = RL(c + F3(d,e,a) + X[ 6] + unchecked((int) 0x6ed9eba1), 6) + b; e = RL(e, 10);
b = RL(b + F3(c,d,e) + X[13] + unchecked((int) 0x6ed9eba1), 5) + a; d = RL(d, 10);
a = RL(a + F3(b,c,d) + X[11] + unchecked((int) 0x6ed9eba1), 12) + e; c = RL(c, 10);
e = RL(e + F3(a,b,c) + X[ 5] + unchecked((int) 0x6ed9eba1), 7) + d; b = RL(b, 10);
d = RL(d + F3(e,a,b) + X[12] + unchecked((int) 0x6ed9eba1), 5) + c; a = RL(a, 10);
// right
dd = RL(dd + F3(ee,aa,bb) + X[15] + unchecked((int) 0x6d703ef3), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd,ee,aa) + X[ 5] + unchecked((int) 0x6d703ef3), 7) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc,dd,ee) + X[ 1] + unchecked((int) 0x6d703ef3), 15) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb,cc,dd) + X[ 3] + unchecked((int) 0x6d703ef3), 11) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa,bb,cc) + X[ 7] + unchecked((int) 0x6d703ef3), 8) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee,aa,bb) + X[14] + unchecked((int) 0x6d703ef3), 6) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd,ee,aa) + X[ 6] + unchecked((int) 0x6d703ef3), 6) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc,dd,ee) + X[ 9] + unchecked((int) 0x6d703ef3), 14) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb,cc,dd) + X[11] + unchecked((int) 0x6d703ef3), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa,bb,cc) + X[ 8] + unchecked((int) 0x6d703ef3), 13) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee,aa,bb) + X[12] + unchecked((int) 0x6d703ef3), 5) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd,ee,aa) + X[ 2] + unchecked((int) 0x6d703ef3), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc,dd,ee) + X[10] + unchecked((int) 0x6d703ef3), 13) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb,cc,dd) + X[ 0] + unchecked((int) 0x6d703ef3), 13) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa,bb,cc) + X[ 4] + unchecked((int) 0x6d703ef3), 7) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee,aa,bb) + X[13] + unchecked((int) 0x6d703ef3), 5) + cc; aa = RL(aa, 10);
//
// Rounds 48-63
//
// left
c = RL(c + F4(d,e,a) + X[ 1] + unchecked((int) 0x8f1bbcdc), 11) + b; e = RL(e, 10);
b = RL(b + F4(c,d,e) + X[ 9] + unchecked((int) 0x8f1bbcdc), 12) + a; d = RL(d, 10);
a = RL(a + F4(b,c,d) + X[11] + unchecked((int) 0x8f1bbcdc), 14) + e; c = RL(c, 10);
e = RL(e + F4(a,b,c) + X[10] + unchecked((int) 0x8f1bbcdc), 15) + d; b = RL(b, 10);
d = RL(d + F4(e,a,b) + X[ 0] + unchecked((int) 0x8f1bbcdc), 14) + c; a = RL(a, 10);
c = RL(c + F4(d,e,a) + X[ 8] + unchecked((int) 0x8f1bbcdc), 15) + b; e = RL(e, 10);
b = RL(b + F4(c,d,e) + X[12] + unchecked((int) 0x8f1bbcdc), 9) + a; d = RL(d, 10);
a = RL(a + F4(b,c,d) + X[ 4] + unchecked((int) 0x8f1bbcdc), 8) + e; c = RL(c, 10);
e = RL(e + F4(a,b,c) + X[13] + unchecked((int) 0x8f1bbcdc), 9) + d; b = RL(b, 10);
d = RL(d + F4(e,a,b) + X[ 3] + unchecked((int) 0x8f1bbcdc), 14) + c; a = RL(a, 10);
c = RL(c + F4(d,e,a) + X[ 7] + unchecked((int) 0x8f1bbcdc), 5) + b; e = RL(e, 10);
b = RL(b + F4(c,d,e) + X[15] + unchecked((int) 0x8f1bbcdc), 6) + a; d = RL(d, 10);
a = RL(a + F4(b,c,d) + X[14] + unchecked((int) 0x8f1bbcdc), 8) + e; c = RL(c, 10);
e = RL(e + F4(a,b,c) + X[ 5] + unchecked((int) 0x8f1bbcdc), 6) + d; b = RL(b, 10);
d = RL(d + F4(e,a,b) + X[ 6] + unchecked((int) 0x8f1bbcdc), 5) + c; a = RL(a, 10);
c = RL(c + F4(d,e,a) + X[ 2] + unchecked((int) 0x8f1bbcdc), 12) + b; e = RL(e, 10);
// right
cc = RL(cc + F2(dd,ee,aa) + X[ 8] + unchecked((int) 0x7a6d76e9), 15) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc,dd,ee) + X[ 6] + unchecked((int) 0x7a6d76e9), 5) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb,cc,dd) + X[ 4] + unchecked((int) 0x7a6d76e9), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa,bb,cc) + X[ 1] + unchecked((int) 0x7a6d76e9), 11) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee,aa,bb) + X[ 3] + unchecked((int) 0x7a6d76e9), 14) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd,ee,aa) + X[11] + unchecked((int) 0x7a6d76e9), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc,dd,ee) + X[15] + unchecked((int) 0x7a6d76e9), 6) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb,cc,dd) + X[ 0] + unchecked((int) 0x7a6d76e9), 14) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa,bb,cc) + X[ 5] + unchecked((int) 0x7a6d76e9), 6) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee,aa,bb) + X[12] + unchecked((int) 0x7a6d76e9), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd,ee,aa) + X[ 2] + unchecked((int) 0x7a6d76e9), 12) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc,dd,ee) + X[13] + unchecked((int) 0x7a6d76e9), 9) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb,cc,dd) + X[ 9] + unchecked((int) 0x7a6d76e9), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa,bb,cc) + X[ 7] + unchecked((int) 0x7a6d76e9), 5) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee,aa,bb) + X[10] + unchecked((int) 0x7a6d76e9), 15) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd,ee,aa) + X[14] + unchecked((int) 0x7a6d76e9), 8) + bb; ee = RL(ee, 10);
//
// Rounds 64-79
//
// left
b = RL(b + F5(c,d,e) + X[ 4] + unchecked((int) 0xa953fd4e), 9) + a; d = RL(d, 10);
a = RL(a + F5(b,c,d) + X[ 0] + unchecked((int) 0xa953fd4e), 15) + e; c = RL(c, 10);
e = RL(e + F5(a,b,c) + X[ 5] + unchecked((int) 0xa953fd4e), 5) + d; b = RL(b, 10);
d = RL(d + F5(e,a,b) + X[ 9] + unchecked((int) 0xa953fd4e), 11) + c; a = RL(a, 10);
c = RL(c + F5(d,e,a) + X[ 7] + unchecked((int) 0xa953fd4e), 6) + b; e = RL(e, 10);
b = RL(b + F5(c,d,e) + X[12] + unchecked((int) 0xa953fd4e), 8) + a; d = RL(d, 10);
a = RL(a + F5(b,c,d) + X[ 2] + unchecked((int) 0xa953fd4e), 13) + e; c = RL(c, 10);
e = RL(e + F5(a,b,c) + X[10] + unchecked((int) 0xa953fd4e), 12) + d; b = RL(b, 10);
d = RL(d + F5(e,a,b) + X[14] + unchecked((int) 0xa953fd4e), 5) + c; a = RL(a, 10);
c = RL(c + F5(d,e,a) + X[ 1] + unchecked((int) 0xa953fd4e), 12) + b; e = RL(e, 10);
b = RL(b + F5(c,d,e) + X[ 3] + unchecked((int) 0xa953fd4e), 13) + a; d = RL(d, 10);
a = RL(a + F5(b,c,d) + X[ 8] + unchecked((int) 0xa953fd4e), 14) + e; c = RL(c, 10);
e = RL(e + F5(a,b,c) + X[11] + unchecked((int) 0xa953fd4e), 11) + d; b = RL(b, 10);
d = RL(d + F5(e,a,b) + X[ 6] + unchecked((int) 0xa953fd4e), 8) + c; a = RL(a, 10);
c = RL(c + F5(d,e,a) + X[15] + unchecked((int) 0xa953fd4e), 5) + b; e = RL(e, 10);
b = RL(b + F5(c,d,e) + X[13] + unchecked((int) 0xa953fd4e), 6) + a; d = RL(d, 10);
// right
bb = RL(bb + F1(cc,dd,ee) + X[12], 8) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb,cc,dd) + X[15], 5) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa,bb,cc) + X[10], 12) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee,aa,bb) + X[ 4], 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd,ee,aa) + X[ 1], 12) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc,dd,ee) + X[ 5], 5) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb,cc,dd) + X[ 8], 14) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa,bb,cc) + X[ 7], 6) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee,aa,bb) + X[ 6], 8) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd,ee,aa) + X[ 2], 13) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc,dd,ee) + X[13], 6) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb,cc,dd) + X[14], 5) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa,bb,cc) + X[ 0], 15) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee,aa,bb) + X[ 3], 13) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd,ee,aa) + X[ 9], 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc,dd,ee) + X[11], 11) + aa; dd = RL(dd, 10);
dd += c + H1;
H1 = H2 + d + ee;
H2 = H3 + e + aa;
H3 = H4 + a + bb;
H4 = H0 + b + cc;
H0 = dd;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
for (int i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
public override IMemoable Copy()
{
return new RipeMD160Digest(this);
}
public override void Reset(IMemoable other)
{
RipeMD160Digest d = (RipeMD160Digest)other;
CopyIn(d);
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocList
// ObjectType: DocList
// CSLAType: ReadOnlyCollection
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using UsingLibrary;
namespace DocStore.Business
{
/// <summary>
/// Collection of document's basic information (read only list).<br/>
/// This is a generated <see cref="DocList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="DocInfo"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class DocList : MyReadOnlyBindingListBase<DocList, DocInfo>, IHaveInterface, IHaveGenericInterface<DocList>
#else
public partial class DocList : MyReadOnlyListBase<DocList, DocInfo>, IHaveInterface, IHaveGenericInterface<DocList>
#endif
{
#region Event handler properties
[NotUndoable]
private static bool _singleInstanceSavedHandler = true;
/// <summary>
/// Gets or sets a value indicating whether only a single instance should handle the Saved event.
/// </summary>
/// <value>
/// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>.
/// </value>
public static bool SingleInstanceSavedHandler
{
get { return _singleInstanceSavedHandler; }
set { _singleInstanceSavedHandler = value; }
}
#endregion
#region Collection Business Methods
/// <summary>
/// Determines whether a <see cref="DocInfo"/> item is in the collection.
/// </summary>
/// <param name="docID">The DocID of the item to search for.</param>
/// <returns><c>true</c> if the DocInfo is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int docID)
{
foreach (var docInfo in this)
{
if (docInfo.DocID == docID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="DocInfo"/> item of the <see cref="DocList"/> collection, based on a given DocID.
/// </summary>
/// <param name="docID">The DocID.</param>
/// <returns>A <see cref="DocInfo"/> object.</returns>
public DocInfo FindDocInfoByDocID(int docID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].DocID.Equals(docID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="DocList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="DocList"/> collection.</returns>
public static DocList GetDocList()
{
return DataPortal.Fetch<DocList>();
}
/// <summary>
/// Factory method. Loads a <see cref="DocList"/> collection, based on given parameters.
/// </summary>
/// <param name="crit">The fetch criteria.</param>
/// <returns>A reference to the fetched <see cref="DocList"/> collection.</returns>
public static DocList GetDocList(DocListFilteredCriteria crit)
{
return DataPortal.Fetch<DocList>(crit);
}
/// <summary>
/// Factory method. Loads a <see cref="DocList"/> collection, based on given parameters.
/// </summary>
/// <param name="docID">The DocID parameter of the DocList to fetch.</param>
/// <param name="docClassID">The DocClassID parameter of the DocList to fetch.</param>
/// <param name="docTypeID">The DocTypeID parameter of the DocList to fetch.</param>
/// <param name="senderID">The SenderID parameter of the DocList to fetch.</param>
/// <param name="recipientID">The RecipientID parameter of the DocList to fetch.</param>
/// <param name="docRef">The DocRef parameter of the DocList to fetch.</param>
/// <param name="docDate">The DocDate parameter of the DocList to fetch.</param>
/// <param name="subject">The Subject parameter of the DocList to fetch.</param>
/// <param name="docStatusID">The DocStatusID parameter of the DocList to fetch.</param>
/// <param name="createDate">The CreateDate parameter of the DocList to fetch.</param>
/// <param name="createUserID">The CreateUserID parameter of the DocList to fetch.</param>
/// <param name="changeDate">The ChangeDate parameter of the DocList to fetch.</param>
/// <param name="changeUserID">The ChangeUserID parameter of the DocList to fetch.</param>
/// <returns>A reference to the fetched <see cref="DocList"/> collection.</returns>
public static DocList GetDocList(int? docID, int? docClassID, int? docTypeID, int? senderID, int? recipientID, string docRef, SmartDate docDate, string subject, int? docStatusID, SmartDate createDate, int? createUserID, SmartDate changeDate, int? changeUserID)
{
return DataPortal.Fetch<DocList>(new DocListFilteredCriteria(docID, docClassID, docTypeID, senderID, recipientID, docRef, docDate, subject, docStatusID, createDate, createUserID, changeDate, changeUserID));
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="DocList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetDocList(EventHandler<DataPortalResult<DocList>> callback)
{
DataPortal.BeginFetch<DocList>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="DocList"/> collection, based on given parameters.
/// </summary>
/// <param name="crit">The fetch criteria.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetDocList(DocListFilteredCriteria crit, EventHandler<DataPortalResult<DocList>> callback)
{
DataPortal.BeginFetch<DocList>(crit, callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="DocList"/> collection, based on given parameters.
/// </summary>
/// <param name="docID">The DocID parameter of the DocList to fetch.</param>
/// <param name="docClassID">The DocClassID parameter of the DocList to fetch.</param>
/// <param name="docTypeID">The DocTypeID parameter of the DocList to fetch.</param>
/// <param name="senderID">The SenderID parameter of the DocList to fetch.</param>
/// <param name="recipientID">The RecipientID parameter of the DocList to fetch.</param>
/// <param name="docRef">The DocRef parameter of the DocList to fetch.</param>
/// <param name="docDate">The DocDate parameter of the DocList to fetch.</param>
/// <param name="subject">The Subject parameter of the DocList to fetch.</param>
/// <param name="docStatusID">The DocStatusID parameter of the DocList to fetch.</param>
/// <param name="createDate">The CreateDate parameter of the DocList to fetch.</param>
/// <param name="createUserID">The CreateUserID parameter of the DocList to fetch.</param>
/// <param name="changeDate">The ChangeDate parameter of the DocList to fetch.</param>
/// <param name="changeUserID">The ChangeUserID parameter of the DocList to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetDocList(int? docID, int? docClassID, int? docTypeID, int? senderID, int? recipientID, string docRef, SmartDate docDate, string subject, int? docStatusID, SmartDate createDate, int? createUserID, SmartDate changeDate, int? changeUserID, EventHandler<DataPortalResult<DocList>> callback)
{
DataPortal.BeginFetch<DocList>(new DocListFilteredCriteria(docID, docClassID, docTypeID, senderID, recipientID, docRef, docDate, subject, docStatusID, createDate, createUserID, changeDate, changeUserID), callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocList()
{
// Use factory methods and do not use direct creation.
DocSaved.Register(this);
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Saved Event Handler
/// <summary>
/// Handle Saved events of <see cref="Doc"/> to update the list of <see cref="DocInfo"/> objects.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
internal void DocSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
var obj = (Doc)e.NewObject;
if (((Doc)sender).IsNew)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
Add(DocInfo.LoadInfo(obj));
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
else if (((Doc)sender).IsDeleted)
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.DocID == obj.DocID)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
this.RemoveItem(index);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
break;
}
}
}
else
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.DocID == obj.DocID)
{
child.UpdatePropertiesOnSaved(obj);
#if !WINFORMS
var notifyCollectionChangedEventArgs =
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index);
OnCollectionChanged(notifyCollectionChangedEventArgs);
#else
var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
OnListChanged(listChangedEventArgs);
#endif
break;
}
}
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="DocList"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
GetQueryGetDocList();
using (var cmd = new SqlCommand(getDocListInlineQuery, ctx.Connection))
{
cmd.CommandType = CommandType.Text;
var args = new DataPortalHookArgs(cmd);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
/// <summary>
/// Loads a <see cref="DocList"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="crit">The fetch criteria.</param>
protected void DataPortal_Fetch(DocListFilteredCriteria crit)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
GetQueryGetDocList(crit);
using (var cmd = new SqlCommand(getDocListInlineQuery, ctx.Connection))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@DocID", crit.DocID == null ? (object)DBNull.Value : crit.DocID.Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@DocClassID", crit.DocClassID == null ? (object)DBNull.Value : crit.DocClassID.Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@DocTypeID", crit.DocTypeID == null ? (object)DBNull.Value : crit.DocTypeID.Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SenderID", crit.SenderID == null ? (object)DBNull.Value : crit.SenderID.Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RecipientID", crit.RecipientID == null ? (object)DBNull.Value : crit.RecipientID.Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@DocRef", crit.DocRef == null ? (object)DBNull.Value : crit.DocRef).DbType = DbType.String;
cmd.Parameters.AddWithValue("@DocDate", crit.DocDate == null ? (object)DBNull.Value : crit.DocDate.DBValue).DbType = DbType.Date;
cmd.Parameters.AddWithValue("@Subject", crit.Subject == null ? (object)DBNull.Value : crit.Subject).DbType = DbType.String;
cmd.Parameters.AddWithValue("@DocStatusID", crit.DocStatusID == null ? (object)DBNull.Value : crit.DocStatusID.Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@CreateDate", crit.CreateDate == null ? (object)DBNull.Value : crit.CreateDate.DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", crit.CreateUserID == null ? (object)DBNull.Value : crit.CreateUserID.Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", crit.ChangeDate == null ? (object)DBNull.Value : crit.ChangeDate.DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", crit.ChangeUserID == null ? (object)DBNull.Value : crit.ChangeUserID.Value).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, crit);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="DocList"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DocInfo.GetDocInfo(dr));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region Inline queries fields and partial methods
[NotUndoable, NonSerialized]
private string getDocListInlineQuery;
partial void GetQueryGetDocList();
partial void GetQueryGetDocList(DocListFilteredCriteria crit);
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
#region DocSaved nested class
/// <summary>
/// Nested class to manage the Saved events of <see cref="Doc"/>
/// to update the list of <see cref="DocInfo"/> objects.
/// </summary>
private static class DocSaved
{
private static List<WeakReference> _references;
private static bool Found(object obj)
{
return _references.Any(reference => Equals(reference.Target, obj));
}
/// <summary>
/// Registers a DocList instance to handle Saved events.
/// to update the list of <see cref="DocInfo"/> objects.
/// </summary>
/// <param name="obj">The DocList instance.</param>
public static void Register(DocList obj)
{
var mustRegister = _references == null;
if (mustRegister)
_references = new List<WeakReference>();
if (DocList.SingleInstanceSavedHandler)
_references.Clear();
if (!Found(obj))
_references.Add(new WeakReference(obj));
if (mustRegister)
Doc.DocSaved += DocSavedHandler;
}
/// <summary>
/// Handles Saved events of <see cref="Doc"/>.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
public static void DocSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
foreach (var reference in _references)
{
if (reference.IsAlive)
((DocList) reference.Target).DocSavedHandler(sender, e);
}
}
/// <summary>
/// Removes event handling and clears all registered DocList instances.
/// </summary>
public static void Unregister()
{
Doc.DocSaved -= DocSavedHandler;
_references = null;
}
}
#endregion
}
#region Criteria
/// <summary>
/// DocListFilteredCriteria criteria.
/// </summary>
[Serializable]
public partial class DocListFilteredCriteria : CriteriaBase<DocListFilteredCriteria>
{
/// <summary>
/// Maintains metadata about <see cref="DocID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> DocIDProperty = RegisterProperty<int?>(p => p.DocID);
/// <summary>
/// Gets or sets the Doc ID.
/// </summary>
/// <value>The Doc ID.</value>
public int? DocID
{
get { return ReadProperty(DocIDProperty); }
set { LoadProperty(DocIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="DocClassID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> DocClassIDProperty = RegisterProperty<int?>(p => p.DocClassID);
/// <summary>
/// Gets or sets the Doc Class ID.
/// </summary>
/// <value>The Doc Class ID.</value>
public int? DocClassID
{
get { return ReadProperty(DocClassIDProperty); }
set { LoadProperty(DocClassIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="DocTypeID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> DocTypeIDProperty = RegisterProperty<int?>(p => p.DocTypeID);
/// <summary>
/// Gets or sets the Doc Type ID.
/// </summary>
/// <value>The Doc Type ID.</value>
public int? DocTypeID
{
get { return ReadProperty(DocTypeIDProperty); }
set { LoadProperty(DocTypeIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="SenderID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> SenderIDProperty = RegisterProperty<int?>(p => p.SenderID);
/// <summary>
/// Gets or sets the Sender ID.
/// </summary>
/// <value>The Sender ID.</value>
public int? SenderID
{
get { return ReadProperty(SenderIDProperty); }
set { LoadProperty(SenderIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="RecipientID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> RecipientIDProperty = RegisterProperty<int?>(p => p.RecipientID);
/// <summary>
/// Gets or sets the Recipient ID.
/// </summary>
/// <value>The Recipient ID.</value>
public int? RecipientID
{
get { return ReadProperty(RecipientIDProperty); }
set { LoadProperty(RecipientIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="DocRef"/> property.
/// </summary>
public static readonly PropertyInfo<string> DocRefProperty = RegisterProperty<string>(p => p.DocRef);
/// <summary>
/// Gets or sets the Doc Ref.
/// </summary>
/// <value>The Doc Ref.</value>
public string DocRef
{
get { return ReadProperty(DocRefProperty); }
set { LoadProperty(DocRefProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="DocDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> DocDateProperty = RegisterProperty<SmartDate>(p => p.DocDate);
/// <summary>
/// Gets or sets the Doc Date.
/// </summary>
/// <value>The Doc Date.</value>
public SmartDate DocDate
{
get { return ReadProperty(DocDateProperty); }
set { LoadProperty(DocDateProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Subject"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject);
/// <summary>
/// Gets or sets the Subject.
/// </summary>
/// <value>The Subject.</value>
public string Subject
{
get { return ReadProperty(SubjectProperty); }
set { LoadProperty(SubjectProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="DocStatusID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> DocStatusIDProperty = RegisterProperty<int?>(p => p.DocStatusID);
/// <summary>
/// Gets or sets the Doc Status ID.
/// </summary>
/// <value>The Doc Status ID.</value>
public int? DocStatusID
{
get { return ReadProperty(DocStatusIDProperty); }
set { LoadProperty(DocStatusIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate);
/// <summary>
/// Gets or sets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return ReadProperty(CreateDateProperty); }
set { LoadProperty(CreateDateProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> CreateUserIDProperty = RegisterProperty<int?>(p => p.CreateUserID);
/// <summary>
/// Gets or sets the Create User ID.
/// </summary>
/// <value>The Create User ID.</value>
public int? CreateUserID
{
get { return ReadProperty(CreateUserIDProperty); }
set { LoadProperty(CreateUserIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate);
/// <summary>
/// Gets or sets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return ReadProperty(ChangeDateProperty); }
set { LoadProperty(ChangeDateProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> ChangeUserIDProperty = RegisterProperty<int?>(p => p.ChangeUserID);
/// <summary>
/// Gets or sets the Change User ID.
/// </summary>
/// <value>The Change User ID.</value>
public int? ChangeUserID
{
get { return ReadProperty(ChangeUserIDProperty); }
set { LoadProperty(ChangeUserIDProperty, value); }
}
/// <summary>
/// Initializes a new instance of the <see cref="DocListFilteredCriteria"/> class.
/// </summary>
/// <remarks> A parameterless constructor is required by the MobileFormatter.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocListFilteredCriteria()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DocListFilteredCriteria"/> class.
/// </summary>
/// <param name="docID">The DocID.</param>
/// <param name="docClassID">The DocClassID.</param>
/// <param name="docTypeID">The DocTypeID.</param>
/// <param name="senderID">The SenderID.</param>
/// <param name="recipientID">The RecipientID.</param>
/// <param name="docRef">The DocRef.</param>
/// <param name="docDate">The DocDate.</param>
/// <param name="subject">The Subject.</param>
/// <param name="docStatusID">The DocStatusID.</param>
/// <param name="createDate">The CreateDate.</param>
/// <param name="createUserID">The CreateUserID.</param>
/// <param name="changeDate">The ChangeDate.</param>
/// <param name="changeUserID">The ChangeUserID.</param>
public DocListFilteredCriteria(int? docID, int? docClassID, int? docTypeID, int? senderID, int? recipientID, string docRef, SmartDate docDate, string subject, int? docStatusID, SmartDate createDate, int? createUserID, SmartDate changeDate, int? changeUserID)
{
DocID = docID;
DocClassID = docClassID;
DocTypeID = docTypeID;
SenderID = senderID;
RecipientID = recipientID;
DocRef = docRef;
DocDate = docDate;
Subject = subject;
DocStatusID = docStatusID;
CreateDate = createDate;
CreateUserID = createUserID;
ChangeDate = changeDate;
ChangeUserID = changeUserID;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is DocListFilteredCriteria)
{
var c = (DocListFilteredCriteria) obj;
if (!DocID.Equals(c.DocID))
return false;
if (!DocClassID.Equals(c.DocClassID))
return false;
if (!DocTypeID.Equals(c.DocTypeID))
return false;
if (!SenderID.Equals(c.SenderID))
return false;
if (!RecipientID.Equals(c.RecipientID))
return false;
if (!DocRef.Equals(c.DocRef))
return false;
if (!DocDate.Equals(c.DocDate))
return false;
if (!Subject.Equals(c.Subject))
return false;
if (!DocStatusID.Equals(c.DocStatusID))
return false;
if (!CreateDate.Equals(c.CreateDate))
return false;
if (!CreateUserID.Equals(c.CreateUserID))
return false;
if (!ChangeDate.Equals(c.ChangeDate))
return false;
if (!ChangeUserID.Equals(c.ChangeUserID))
return false;
return true;
}
return false;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return string.Concat("DocListFilteredCriteria", DocID.ToString(), DocClassID.ToString(), DocTypeID.ToString(), SenderID.ToString(), RecipientID.ToString(), DocRef.ToString(), DocDate.ToString(), Subject.ToString(), DocStatusID.ToString(), CreateDate.ToString(), CreateUserID.ToString(), ChangeDate.ToString(), ChangeUserID.ToString()).GetHashCode();
}
}
#endregion
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula;
using System.Text;
/**
* Implementation for Excel function INDIRECT<p/>
*
* INDIRECT() returns the cell or area reference denoted by the text argument.<p/>
*
* <b>Syntax</b>:<br/>
* <b>INDIRECT</b>(<b>ref_text</b>,isA1Style)<p/>
*
* <b>ref_text</b> a string representation of the desired reference as it would normally be written
* in a cell formula.<br/>
* <b>isA1Style</b> (default TRUE) specifies whether the ref_text should be interpreted as A1-style
* or R1C1-style.
*
*
* @author Josh Micich
*/
public class Indirect : FreeRefFunction
{
public static FreeRefFunction instance = new Indirect();
private Indirect()
{
// enforce singleton
}
public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
{
if (args.Length < 1)
{
return ErrorEval.VALUE_INVALID;
}
bool isA1style;
String text;
try
{
ValueEval ve = OperandResolver.GetSingleValue(args[0], ec.RowIndex, ec
.ColumnIndex);
text = OperandResolver.CoerceValueToString(ve);
switch (args.Length)
{
case 1:
isA1style = true;
break;
case 2:
isA1style = EvaluateBooleanArg(args[1], ec);
break;
default:
return ErrorEval.VALUE_INVALID;
}
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
return EvaluateIndirect(ec, text, isA1style);
}
private static bool EvaluateBooleanArg(ValueEval arg, OperationEvaluationContext ec)
{
ValueEval ve = OperandResolver.GetSingleValue(arg, ec.RowIndex, ec.ColumnIndex);
if (ve == BlankEval.instance || ve == MissingArgEval.instance)
{
return false;
}
// numeric quantities follow standard bool conversion rules
// for strings, only "TRUE" and "FALSE" (case insensitive) are valid
return (bool)OperandResolver.CoerceValueToBoolean(ve, false);
}
private static ValueEval EvaluateIndirect(OperationEvaluationContext ec, String text,
bool isA1style)
{
// Search backwards for '!' because sheet names can contain '!'
int plingPos = text.LastIndexOf('!');
String workbookName;
String sheetName;
String refText; // whitespace around this Gets Trimmed OK
if (plingPos < 0)
{
workbookName = null;
sheetName = null;
refText = text;
}
else
{
String[] parts = ParseWorkbookAndSheetName(text.Substring(0, plingPos));
if (parts == null)
{
return ErrorEval.REF_INVALID;
}
workbookName = parts[0];
sheetName = parts[1];
refText = text.Substring(plingPos + 1);
}
String refStrPart1;
String refStrPart2;
int colonPos = refText.IndexOf(':');
if (colonPos < 0)
{
refStrPart1 = refText.Trim();
refStrPart2 = null;
}
else
{
refStrPart1 = refText.Substring(0, colonPos).Trim();
refStrPart2 = refText.Substring(colonPos + 1).Trim();
}
return ec.GetDynamicReference(workbookName, sheetName, refStrPart1, refStrPart2, isA1style);
}
/**
* @return array of length 2: {workbookName, sheetName,}. Second element will always be
* present. First element may be null if sheetName is unqualified.
* Returns <code>null</code> if text cannot be parsed.
*/
private static String[] ParseWorkbookAndSheetName(string text)
{
int lastIx = text.Length - 1;
if (lastIx < 0)
{
return null;
}
if (CanTrim(text))
{
return null;
}
char firstChar = text[0];
if (Char.IsWhiteSpace(firstChar))
{
return null;
}
if (firstChar == '\'')
{
// workbookName or sheetName needs quoting
// quotes go around both
if (text[lastIx] != '\'')
{
return null;
}
firstChar = text[1];
if (Char.IsWhiteSpace(firstChar))
{
return null;
}
String wbName;
int sheetStartPos;
if (firstChar == '[')
{
int rbPos = text.ToString().LastIndexOf(']');
if (rbPos < 0)
{
return null;
}
wbName = UnescapeString(text.Substring(2, rbPos - 2));
if (wbName == null || CanTrim(wbName))
{
return null;
}
sheetStartPos = rbPos + 1;
}
else
{
wbName = null;
sheetStartPos = 1;
}
// else - just sheet name
String sheetName = UnescapeString(text.Substring(sheetStartPos, lastIx - sheetStartPos));
if (sheetName == null)
{ // note - when quoted, sheetName can
// start/end with whitespace
return null;
}
return new String[] { wbName, sheetName, };
}
if (firstChar == '[')
{
int rbPos = text.ToString().LastIndexOf(']');
if (rbPos < 0)
{
return null;
}
string wbName = text.Substring(1, rbPos - 1);
if (CanTrim(wbName))
{
return null;
}
string sheetName = text.Substring(rbPos + 1);
if (CanTrim(sheetName))
{
return null;
}
return new String[] { wbName.ToString(), sheetName.ToString(), };
}
// else - just sheet name
return new String[] { null, text.ToString(), };
}
/**
* @return <code>null</code> if there is a syntax error in any escape sequence
* (the typical syntax error is a single quote character not followed by another).
*/
private static String UnescapeString(string text)
{
int len = text.Length;
StringBuilder sb = new StringBuilder(len);
int i = 0;
while (i < len)
{
char ch = text[i];
if (ch == '\'')
{
// every quote must be followed by another
i++;
if (i >= len)
{
return null;
}
ch = text[i];
if (ch != '\'')
{
return null;
}
}
sb.Append(ch);
i++;
}
return sb.ToString();
}
private static bool CanTrim(string text)
{
int lastIx = text.Length - 1;
if (lastIx < 0)
{
return false;
}
if (Char.IsWhiteSpace(text[0]))
{
return true;
}
if (Char.IsWhiteSpace(text[lastIx]))
{
return true;
}
return false;
}
}
}
| |
using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WalletWasabi.Extensions;
using WalletWasabi.Hwi.Models;
using WalletWasabi.Tests.Helpers;
using WalletWasabi.Wallets;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class WalletDirTests
{
private async Task<(string walletsPath, string walletsBackupPath)> CleanupWalletDirectoriesAsync(string baseDir)
{
var walletsPath = Path.Combine(baseDir, WalletDirectories.WalletsDirName);
var walletsBackupPath = Path.Combine(baseDir, WalletDirectories.WalletsBackupDirName);
await IoHelpers.TryDeleteDirectoryAsync(walletsPath);
await IoHelpers.TryDeleteDirectoryAsync(walletsBackupPath);
return (walletsPath, walletsBackupPath);
}
[Fact]
public async Task CreatesWalletDirectoriesAsync()
{
var baseDir = Common.GetWorkDir();
(string walletsPath, string walletsBackupPath) = await CleanupWalletDirectoriesAsync(baseDir);
_ = new WalletDirectories(Network.Main, baseDir);
Assert.True(Directory.Exists(walletsPath));
Assert.True(Directory.Exists(walletsBackupPath));
// Testing what happens if the directories are already exist.
_ = new WalletDirectories(Network.Main, baseDir);
Assert.True(Directory.Exists(walletsPath));
Assert.True(Directory.Exists(walletsBackupPath));
}
[Fact]
public async Task TestPathsAsync()
{
var baseDir = Common.GetWorkDir();
_ = await CleanupWalletDirectoriesAsync(baseDir);
var mainWd = new WalletDirectories(Network.Main, baseDir);
Assert.Equal(Network.Main, mainWd.Network);
Assert.Equal(Path.Combine(baseDir, "Wallets"), mainWd.WalletsDir);
Assert.Equal(Path.Combine(baseDir, "WalletBackups"), mainWd.WalletsBackupDir);
var testWd = new WalletDirectories(Network.TestNet, baseDir);
Assert.Equal(Network.TestNet, testWd.Network);
Assert.Equal(Path.Combine(baseDir, "Wallets", "TestNet"), testWd.WalletsDir);
Assert.Equal(Path.Combine(baseDir, "WalletBackups", "TestNet"), testWd.WalletsBackupDir);
var regWd = new WalletDirectories(Network.RegTest, baseDir);
Assert.Equal(Network.RegTest, regWd.Network);
Assert.Equal(Path.Combine(baseDir, "Wallets", "RegTest"), regWd.WalletsDir);
Assert.Equal(Path.Combine(baseDir, "WalletBackups", "RegTest"), regWd.WalletsBackupDir);
}
[Fact]
public async Task CorrectWalletDirectoryNameAsync()
{
var baseDir = Common.GetWorkDir();
(string walletsPath, string walletsBackupPath) = await CleanupWalletDirectoriesAsync(baseDir);
var walletDirectories = new WalletDirectories(Network.Main, $" {baseDir} ");
Assert.Equal(walletsPath, walletDirectories.WalletsDir);
Assert.Equal(walletsBackupPath, walletDirectories.WalletsBackupDir);
}
[Fact]
public async Task ServesWalletFilesAsync()
{
var baseDir = Common.GetWorkDir();
await CleanupWalletDirectoriesAsync(baseDir);
var walletDirectories = new WalletDirectories(Network.Main, baseDir);
string walletName = "FooWallet.json";
(string walletPath, string walletBackupPath) = walletDirectories.GetWalletFilePaths(walletName);
Assert.Equal(Path.Combine(walletDirectories.WalletsDir, walletName), walletPath);
Assert.Equal(Path.Combine(walletDirectories.WalletsBackupDir, walletName), walletBackupPath);
}
[Fact]
public async Task EnsuresJsonAsync()
{
var baseDir = Common.GetWorkDir();
await CleanupWalletDirectoriesAsync(baseDir);
var walletDirectories = new WalletDirectories(Network.Main, baseDir);
string walletName = "FooWallet";
string walletFileName = $"{walletName}.json";
(string walletPath, string walletBackupPath) = walletDirectories.GetWalletFilePaths(walletName);
Assert.Equal(Path.Combine(walletDirectories.WalletsDir, walletFileName), walletPath);
Assert.Equal(Path.Combine(walletDirectories.WalletsBackupDir, walletFileName), walletBackupPath);
}
[Fact]
public async Task EnumerateFilesAsync()
{
var baseDir = Common.GetWorkDir();
await CleanupWalletDirectoriesAsync(baseDir);
var walletDirectories = new WalletDirectories(Network.Main, baseDir);
var wallets = new List<string>();
var walletBackups = new List<string>();
const int NumberOfWallets = 4;
for (int i = 0; i < NumberOfWallets; i++)
{
var walletFile = Path.Combine(walletDirectories.WalletsDir, $"FooWallet{i}.json");
var dummyFile = Path.Combine(walletDirectories.WalletsDir, $"FooWallet{i}.dummy");
var backupFile = Path.Combine(walletDirectories.WalletsBackupDir, $"FooWallet{i}.json");
await File.Create(walletFile).DisposeAsync();
await File.Create(dummyFile).DisposeAsync();
await File.Create(backupFile).DisposeAsync();
wallets.Add(walletFile);
walletBackups.Add(backupFile);
}
Assert.True(wallets.ToHashSet().SetEquals(walletDirectories.EnumerateWalletFiles().Select(x => x.FullName).ToHashSet()));
Assert.True(wallets.Concat(walletBackups).ToHashSet().SetEquals(walletDirectories.EnumerateWalletFiles(true).Select(x => x.FullName).ToHashSet()));
}
[Fact]
public async Task EnumerateOrdersByAccessAsync()
{
var baseDir = Common.GetWorkDir();
await CleanupWalletDirectoriesAsync(baseDir);
var walletDirectories = new WalletDirectories(Network.Main, baseDir);
var walletFile1 = Path.Combine(walletDirectories.WalletsDir, $"FooWallet1.json");
await File.Create(walletFile1).DisposeAsync();
File.SetLastAccessTimeUtc(walletFile1, new DateTime(2005, 1, 1, 1, 1, 1, DateTimeKind.Utc));
var walletFile2 = Path.Combine(walletDirectories.WalletsDir, $"FooWallet2.json");
await File.Create(walletFile2).DisposeAsync();
File.SetLastAccessTimeUtc(walletFile2, new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
var walletFile3 = Path.Combine(walletDirectories.WalletsDir, $"FooWallet3.json");
await File.Create(walletFile3).DisposeAsync();
File.SetLastAccessTimeUtc(walletFile3, new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc));
var orderedWallets = new[] { walletFile3, walletFile1, walletFile2 };
Assert.Equal(orderedWallets, walletDirectories.EnumerateWalletFiles().Select(x => x.FullName));
}
[Fact]
public async Task EnumerateMissingDirAsync()
{
var baseDir = Common.GetWorkDir();
(string walletsPath, string walletsBackupPath) = await CleanupWalletDirectoriesAsync(baseDir);
var walletDirectories = new WalletDirectories(Network.Main, baseDir);
Assert.Empty(walletDirectories.EnumerateWalletFiles());
Directory.Delete(walletsBackupPath);
Assert.Empty(walletDirectories.EnumerateWalletFiles());
Directory.Delete(walletsPath);
Assert.Empty(walletDirectories.EnumerateWalletFiles());
Directory.Delete(baseDir);
Assert.Empty(walletDirectories.EnumerateWalletFiles());
}
[Fact]
public async Task GetNextWalletTestAsync()
{
var baseDir = Common.GetWorkDir();
await CleanupWalletDirectoriesAsync(baseDir);
var walletDirectories = new WalletDirectories(Network.Main, baseDir);
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Random Wallet 3.json"));
Assert.Equal("Random Wallet", walletDirectories.GetNextWalletName());
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Random Wallet.json"));
Assert.Equal("Random Wallet 2", walletDirectories.GetNextWalletName());
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Random Wallet 2.json"));
Assert.Equal("Random Wallet 4", walletDirectories.GetNextWalletName());
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Random Wallet 4.dat"));
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Random Wallet 4"));
Assert.Equal("Random Wallet 4", walletDirectories.GetNextWalletName());
File.Delete(Path.Combine(walletDirectories.WalletsDir, "Random Wallet.json"));
File.Delete(Path.Combine(walletDirectories.WalletsDir, "Random Wallet 3.json"));
Assert.Equal("Random Wallet", walletDirectories.GetNextWalletName());
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Random Wallet.json"));
Assert.Equal("Random Wallet 3", walletDirectories.GetNextWalletName());
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Random Wallet 3.json"));
File.Delete(Path.Combine(walletDirectories.WalletsDir, "Random Wallet 3.json"));
Assert.Equal("Foo", walletDirectories.GetNextWalletName("Foo"));
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Foo.json"));
Assert.Equal("Foo 2", walletDirectories.GetNextWalletName("Foo"));
IoHelpers.CreateOrOverwriteFile(Path.Combine(walletDirectories.WalletsDir, "Foo 2.json"));
}
[Fact]
public void GetFriendlyNameTest()
{
Assert.Equal("Hardware Wallet", HardwareWalletModels.Unknown.FriendlyName());
Assert.Equal("Coldcard", HardwareWalletModels.Coldcard.FriendlyName());
Assert.Equal("Coldcard Simulator", HardwareWalletModels.Coldcard_Simulator.FriendlyName());
Assert.Equal("BitBox", HardwareWalletModels.DigitalBitBox_01.FriendlyName());
Assert.Equal("BitBox Simulator", HardwareWalletModels.DigitalBitBox_01_Simulator.FriendlyName());
Assert.Equal("KeepKey", HardwareWalletModels.KeepKey.FriendlyName());
Assert.Equal("KeepKey Simulator", HardwareWalletModels.KeepKey_Simulator.FriendlyName());
Assert.Equal("Ledger Nano S", HardwareWalletModels.Ledger_Nano_S.FriendlyName());
Assert.Equal("Trezor One", HardwareWalletModels.Trezor_1.FriendlyName());
Assert.Equal("Trezor One Simulator", HardwareWalletModels.Trezor_1_Simulator.FriendlyName());
Assert.Equal("Trezor T", HardwareWalletModels.Trezor_T.FriendlyName());
Assert.Equal("Trezor T Simulator", HardwareWalletModels.Trezor_T_Simulator.FriendlyName());
Assert.Equal("BitBox", HardwareWalletModels.BitBox02_BTCOnly.FriendlyName());
Assert.Equal("BitBox", HardwareWalletModels.BitBox02_Multi.FriendlyName());
}
}
}
| |
using System;
using BigMath;
using NUnit.Framework;
using Raksha.Asn1;
using Raksha.Asn1.X509;
using Raksha.Crypto;
using Raksha.Crypto.Parameters;
using Raksha.Math;
using Raksha.Utilities.Date;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
using Raksha.X509;
using Raksha.X509.Store;
namespace Raksha.Tests.Misc
{
[TestFixture]
public class AttrCertSelectorTest
: SimpleTest
{
private static readonly RsaPrivateCrtKeyParameters RsaPrivateKeySpec = new RsaPrivateCrtKeyParameters(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16),
new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
private static readonly byte[] holderCert = Base64.Decode(
"MIIGjTCCBXWgAwIBAgICAPswDQYJKoZIhvcNAQEEBQAwaTEdMBsGCSqGSIb3DQEJ"
+ "ARYOaXJtaGVscEB2dC5lZHUxLjAsBgNVBAMTJVZpcmdpbmlhIFRlY2ggQ2VydGlm"
+ "aWNhdGlvbiBBdXRob3JpdHkxCzAJBgNVBAoTAnZ0MQswCQYDVQQGEwJVUzAeFw0w"
+ "MzAxMzExMzUyMTRaFw0wNDAxMzExMzUyMTRaMIGDMRswGQYJKoZIhvcNAQkBFgxz"
+ "c2hhaEB2dC5lZHUxGzAZBgNVBAMTElN1bWl0IFNoYWggKHNzaGFoKTEbMBkGA1UE"
+ "CxMSVmlyZ2luaWEgVGVjaCBVc2VyMRAwDgYDVQQLEwdDbGFzcyAxMQswCQYDVQQK"
+ "EwJ2dDELMAkGA1UEBhMCVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPDc"
+ "scgSKmsEp0VegFkuitD5j5PUkDuzLjlfaYONt2SN8WeqU4j2qtlCnsipa128cyKS"
+ "JzYe9duUdNxquh5BPIkMkHBw4jHoQA33tk0J/sydWdN74/AHPpPieK5GHwhU7GTG"
+ "rCCS1PJRxjXqse79ExAlul+gjQwHeldAC+d4A6oZAgMBAAGjggOmMIIDojAMBgNV"
+ "HRMBAf8EAjAAMBEGCWCGSAGG+EIBAQQEAwIFoDAOBgNVHQ8BAf8EBAMCA/gwHQYD"
+ "VR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMB0GA1UdDgQWBBRUIoWAzlXbzBYE"
+ "yVTjQFWyMMKo1jCBkwYDVR0jBIGLMIGIgBTgc3Fm+TGqKDhen+oKfbl+xVbj2KFt"
+ "pGswaTEdMBsGCSqGSIb3DQEJARYOaXJtaGVscEB2dC5lZHUxLjAsBgNVBAMTJVZp"
+ "cmdpbmlhIFRlY2ggQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxCzAJBgNVBAoTAnZ0"
+ "MQswCQYDVQQGEwJVU4IBADCBiwYJYIZIAYb4QgENBH4WfFZpcmdpbmlhIFRlY2gg"
+ "Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgZGlnaXRhbCBjZXJ0aWZpY2F0ZXMgYXJl"
+ "IHN1YmplY3QgdG8gcG9saWNpZXMgbG9jYXRlZCBhdCBodHRwOi8vd3d3LnBraS52"
+ "dC5lZHUvY2EvY3BzLy4wFwYDVR0RBBAwDoEMc3NoYWhAdnQuZWR1MBkGA1UdEgQS"
+ "MBCBDmlybWhlbHBAdnQuZWR1MEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcwAoYn"
+ "aHR0cDovL2JveDE3Ny5jYy52dC5lZHUvY2EvaXNzdWVycy5odG1sMEQGA1UdHwQ9"
+ "MDswOaA3oDWGM2h0dHA6Ly9ib3gxNzcuY2MudnQuZWR1L2h0ZG9jcy1wdWJsaWMv"
+ "Y3JsL2NhY3JsLmNybDBUBgNVHSAETTBLMA0GCysGAQQBtGgFAQEBMDoGCysGAQQB"
+ "tGgFAQEBMCswKQYIKwYBBQUHAgEWHWh0dHA6Ly93d3cucGtpLnZ0LmVkdS9jYS9j"
+ "cHMvMD8GCWCGSAGG+EIBBAQyFjBodHRwOi8vYm94MTc3LmNjLnZ0LmVkdS9jZ2kt"
+ "cHVibGljL2NoZWNrX3Jldl9jYT8wPAYJYIZIAYb4QgEDBC8WLWh0dHA6Ly9ib3gx"
+ "NzcuY2MudnQuZWR1L2NnaS1wdWJsaWMvY2hlY2tfcmV2PzBLBglghkgBhvhCAQcE"
+ "PhY8aHR0cHM6Ly9ib3gxNzcuY2MudnQuZWR1L35PcGVuQ0E4LjAxMDYzMC9jZ2kt"
+ "cHVibGljL3JlbmV3YWw/MCwGCWCGSAGG+EIBCAQfFh1odHRwOi8vd3d3LnBraS52"
+ "dC5lZHUvY2EvY3BzLzANBgkqhkiG9w0BAQQFAAOCAQEAHJ2ls9yjpZVcu5DqiE67"
+ "r7BfkdMnm7IOj2v8cd4EAlPp6OPBmjwDMwvKRBb/P733kLBqFNWXWKTpT008R0KB"
+ "8kehbx4h0UPz9vp31zhGv169+5iReQUUQSIwTGNWGLzrT8kPdvxiSAvdAJxcbRBm"
+ "KzDic5I8PoGe48kSCkPpT1oNmnivmcu5j1SMvlx0IS2BkFMksr0OHiAW1elSnE/N"
+ "RuX2k73b3FucwVxB3NRo3vgoHPCTnh9r4qItAHdxFlF+pPtbw2oHESKRfMRfOIHz"
+ "CLQWSIa6Tvg4NIV3RRJ0sbCObesyg08lymalQMdkXwtRn5eGE00SHWwEUjSXP2gR"
+ "3g==");
public override string Name
{
get { return "AttrCertSelector"; }
}
private IX509AttributeCertificate CreateAttrCert()
{
// CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
// X509Certificate iCert = (X509Certificate) fact
// .generateCertificate(new ByteArrayInputStream(holderCert));
X509Certificate iCert = new X509CertificateParser().ReadCertificate(holderCert);
//
// a sample key pair.
//
// RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
// new BigInteger(
// "b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7",
// 16), new BigInteger("11", 16));
//
// set up the keys
//
// KeyFactory kFact = KeyFactory.getInstance("RSA", "BC");
// PrivateKey privKey = kFact.generatePrivate(RsaPrivateKeySpec);
AsymmetricKeyParameter privKey = RsaPrivateKeySpec;
X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator();
// the actual attributes
GeneralName roleName = new GeneralName(GeneralName.Rfc822Name, "DAU123456789@test.com");
Asn1EncodableVector roleSyntax = new Asn1EncodableVector(roleName);
// roleSyntax OID: 2.5.24.72
X509Attribute attributes = new X509Attribute("2.5.24.72",
new DerSequence(roleSyntax));
gen.AddAttribute(attributes);
gen.SetHolder(new AttributeCertificateHolder(PrincipalUtilities.GetSubjectX509Principal(iCert)));
gen.SetIssuer(new AttributeCertificateIssuer(new X509Name("cn=test")));
gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
gen.SetSerialNumber(BigInteger.One);
gen.SetSignatureAlgorithm("SHA1WithRSAEncryption");
Target targetName = new Target(
Target.Choice.Name,
new GeneralName(GeneralName.DnsName, "www.test.com"));
Target targetGroup = new Target(
Target.Choice.Group,
new GeneralName(GeneralName.DirectoryName, "o=Test, ou=Test"));
Target[] targets = new Target[]{ targetName, targetGroup };
TargetInformation targetInformation = new TargetInformation(targets);
gen.AddExtension(X509Extensions.TargetInformation.Id, true, targetInformation);
return gen.Generate(privKey);
}
[Test]
public void TestSelector()
{
IX509AttributeCertificate aCert = CreateAttrCert();
X509AttrCertStoreSelector sel = new X509AttrCertStoreSelector();
sel.AttributeCert = aCert;
bool match = sel.Match(aCert);
if (!match)
{
Fail("Selector does not match attribute certificate.");
}
sel.AttributeCert = null;
match = sel.Match(aCert);
if (!match)
{
Fail("Selector does not match attribute certificate.");
}
sel.Holder = aCert.Holder;
match = sel.Match(aCert);
if (!match)
{
Fail("Selector does not match attribute certificate holder.");
}
sel.Holder = null;
sel.Issuer = aCert.Issuer;
match = sel.Match(aCert);
if (!match)
{
Fail("Selector does not match attribute certificate issuer.");
}
sel.Issuer = null;
// CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
// X509Certificate iCert = (X509Certificate) fact.generateCertificate(
// new ByteArrayInputStream(holderCert));
X509Certificate iCert = new X509CertificateParser().ReadCertificate(holderCert);
match = aCert.Holder.Match(iCert);
if (!match)
{
Fail("Issuer holder does not match signing certificate of attribute certificate.");
}
sel.SerialNumber = aCert.SerialNumber;
match = sel.Match(aCert);
if (!match)
{
Fail("Selector does not match attribute certificate serial number.");
}
sel.AttributeCertificateValid = new DateTimeObject(DateTime.UtcNow);
match = sel.Match(aCert);
if (!match)
{
Fail("Selector does not match attribute certificate time.");
}
sel.AddTargetName(new GeneralName(2, "www.test.com"));
match = sel.Match(aCert);
if (!match)
{
Fail("Selector does not match attribute certificate target name.");
}
sel.SetTargetNames(null);
sel.AddTargetGroup(new GeneralName(4, "o=Test, ou=Test"));
match = sel.Match(aCert);
if (!match)
{
Fail("Selector does not match attribute certificate target group.");
}
sel.SetTargetGroups(null);
}
public override void PerformTest()
{
TestSelector();
}
public static void Main(
string[] args)
{
RunTest(new AttrCertSelectorTest());
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace VulkanCore.Khr
{
/// <summary>
/// Provides Khronos specific extension methods for the <see cref="Device"/> class.
/// </summary>
public unsafe static class DeviceExtensions
{
/// <summary>
/// Create a swapchain.
/// </summary>
/// <param name="device">The device to create the swapchain for.</param>
/// <param name="createInfo">The structure specifying the parameters of the created swapchain.</param>
/// <param name="allocator">
/// The allocator used for host memory allocated for the swapchain object when there is no
/// more specific allocator available.
/// </param>
/// <returns>Created swapchain object.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static SwapchainKhr CreateSwapchainKhr(this Device device, SwapchainCreateInfoKhr createInfo,
AllocationCallbacks? allocator = null)
{
return new SwapchainKhr(device, ref createInfo, ref allocator);
}
/// <summary>
/// Create multiple swapchains that share presentable images.
/// <para>
/// Is similar to <see cref="CreateSwapchainKhr"/>, except that it takes an array of <see
/// cref="SwapchainCreateInfoKhr"/> structures, and returns an array of swapchain objects.
/// </para>
/// <para>
/// The swapchain creation parameters that affect the properties and number of presentable
/// images must match between all the swapchains.If the displays used by any of the
/// swapchains do not use the same presentable image layout or are incompatible in a way that
/// prevents sharing images, swapchain creation will fail with the result code <see
/// cref="Result.ErrorIncompatibleDisplayKhr"/>. If any error occurs, no swapchains will be
/// created. Images presented to multiple swapchains must be re-acquired from all of them
/// before transitioning away from <see cref="ImageLayout.PresentSrcKhr"/>. After destroying
/// one or more of the swapchains, the remaining swapchains and the presentable images can
/// continue to be used.
/// </para>
/// </summary>
/// <param name="device">The device to create the swapchains for.</param>
/// <param name="createInfos">Structures specifying the parameters of the created swapchains.</param>
/// <param name="allocator">
/// The allocator used for host memory allocated for the swapchain objects when there is no
/// more specific allocator available.
/// </param>
/// <returns>The created swapchain objects.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static SwapchainKhr[] CreateSharedSwapchainsKhr(this Device device,
SwapchainCreateInfoKhr[] createInfos, AllocationCallbacks? allocator = null)
{
return SwapchainKhr.CreateSharedKhr(device, createInfos, ref allocator);
}
/// <summary>
/// Create a new descriptor update template.
/// </summary>
/// <param name="device">The logical device that creates the descriptor update template.</param>
/// <param name="createInfo">
/// Specifies the set of descriptors to update with a single call to <see cref="DescriptorSetExtensions.UpdateWithTemplateKhr"/>.
/// </param>
/// <param name="allocator">Controls host memory allocation.</param>
/// <returns>The resulting descriptor update template object.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static DescriptorUpdateTemplateKhr CreateDescriptorUpdateTemplateKhr(this Device device,
DescriptorUpdateTemplateCreateInfoKhr createInfo, AllocationCallbacks? allocator = null)
{
return new DescriptorUpdateTemplateKhr(device, ref createInfo, ref allocator);
}
/// <summary>
/// Get properties of external memory Win32 handles.
/// <para>
/// Windows memory handles compatible with Vulkan may also be created by non-Vulkan APIs
/// using methods beyond the scope of this specification.
/// </para>
/// </summary>
/// <param name="device">The logical device that will be importing <paramref name="handle"/>.</param>
/// <param name="handleType">The type of the handle <paramref name="handle"/>.</param>
/// <param name="handle">the handle which will be imported.</param>
/// <returns>Properties of <paramref name="handle"/>.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static MemoryWin32HandlePropertiesKhr GetMemoryWin32HandlePropertiesKhr(this Device device,
ExternalMemoryHandleTypesKhr handleType, IntPtr handle)
{
MemoryWin32HandlePropertiesKhr properties;
Result result = vkGetMemoryWin32HandlePropertiesKHR(device)(device, handleType, handle, &properties);
VulkanException.ThrowForInvalidResult(result);
return properties;
}
/// <summary>
/// Get properties of external memory file descriptors.
/// <para>
/// POSIX file descriptor memory handles compatible with Vulkan may also be created by
/// non-Vulkan APIs using methods beyond the scope of this specification.
/// </para>
/// </summary>
/// <param name="device">The logical device that will be importing <paramref name="fd"/>.</param>
/// <param name="handleType">The type of the handle <paramref name="fd"/>.</param>
/// <param name="fd">The handle which will be imported.</param>
/// <returns>Properties of the handle <paramref name="fd"/>.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static MemoryFdPropertiesKhr GetMemoryFdPropertiesKhr(this Device device,
ExternalMemoryHandleTypesKhr handleType, int fd)
{
MemoryFdPropertiesKhr properties;
Result result = vkGetMemoryFdPropertiesKHR(device)(device, handleType, fd, &properties);
VulkanException.ThrowForInvalidResult(result);
return properties;
}
/// <summary>
/// Import a semaphore from a Windows HANDLE.
/// </summary>
/// <param name="device">The logical device that created the semaphore.</param>
/// <returns>Structure specifying the semaphore and import parameters.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static ImportSemaphoreWin32HandleInfoKhr ImportSemaphoreWin32HandleKhr(this Device device)
{
ImportSemaphoreWin32HandleInfoKhr.Native nativeInfo;
Result result = vkImportSemaphoreWin32HandleKHR(device)(device, &nativeInfo);
VulkanException.ThrowForInvalidResult(result);
var semaphore = new Semaphore(nativeInfo.Semaphore, device);
ImportSemaphoreWin32HandleInfoKhr.FromNative(ref nativeInfo, semaphore, out var info);
return info;
}
/// <summary>
/// Import a semaphore from a POSIX file descriptor.
/// </summary>
/// <param name="device">The logical device that created the semaphore.</param>
/// <returns>Structure specifying the semaphore and import parameters.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static ImportSemaphoreFdInfoKhr ImportSemaphoreFdKhr(this Device device)
{
ImportSemaphoreFdInfoKhr.Native nativeInfo;
Result result = vkImportSemaphoreFdKHR(device)(device, &nativeInfo);
VulkanException.ThrowForInvalidResult(result);
var semaphore = new Semaphore(nativeInfo.Semaphore, device);
ImportSemaphoreFdInfoKhr.FromNative(ref nativeInfo, semaphore, out var info);
return info;
}
/// <summary>
/// Returns the memory requirements for specified Vulkan object.
/// </summary>
/// <param name="device">The logical device that owns the buffer.</param>
/// <param name="info">
/// Structure containing parameters required for the memory requirements query.
/// </param>
/// <returns>Structure in which the memory requirements of the buffer object are returned.</returns>
public static MemoryRequirements2Khr GetBufferMemoryRequirements2Khr(this Device device, BufferMemoryRequirementsInfo2Khr info)
{
MemoryRequirements2Khr memoryRequirements;
vkGetBufferMemoryRequirements2KHR(device)(device, &info, &memoryRequirements);
return memoryRequirements;
}
/// <summary>
/// Returns the memory requirements for specified Vulkan object.
/// </summary>
/// <param name="device">The logical device that owns the image.</param>
/// <param name="info">
/// Structure containing parameters required for the memory requirements query.
/// </param>
/// <returns>Structure in which the memory requirements of the image object are returned.</returns>
public static MemoryRequirements2Khr GetImageMemoryRequirements2Khr(this Device device, ImageMemoryRequirementsInfo2Khr info)
{
MemoryRequirements2Khr memoryRequirements;
vkGetImageMemoryRequirements2KHR(device)(device, &info, &memoryRequirements);
return memoryRequirements;
}
public static SparseImageMemoryRequirements2Khr[] GetImageSparseMemoryRequirements2Khr(this Device device,
ImageSparseMemoryRequirementsInfo2Khr info)
{
int count;
vkGetImageSparseMemoryRequirements2KHR(device)(device, &info, &count, null);
var memoryRequirements = new SparseImageMemoryRequirements2Khr[count];
fixed (SparseImageMemoryRequirements2Khr* memoryRequirementsPtr = memoryRequirements)
vkGetImageSparseMemoryRequirements2KHR(device)(device, &info, &count, memoryRequirementsPtr);
return memoryRequirements;
}
/// <summary>
/// Bind device memory to buffer objects.
/// </summary>
/// <param name="device">The logical device that owns the buffers and memory.</param>
/// <param name="bindInfos">Structures describing buffers and memory to bind.</param>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static void BindBufferMemory2Khr(this Device device, params BindBufferMemoryInfoKhr[] bindInfos)
{
int count = bindInfos?.Length ?? 0;
var nativeBindInfos = stackalloc BindBufferMemoryInfoKhr.Native[count];
for (int i = 0; i < count; i++)
bindInfos[i].ToNative(out nativeBindInfos[i]);
Result result = vkBindBufferMemory2KHR(device)(device, count, nativeBindInfos);
for (int i = 0; i < count; i++)
nativeBindInfos[i].Free();
VulkanException.ThrowForInvalidResult(result);
}
/// <summary>
/// Bind device memory to image objects.
/// </summary>
/// <param name="device">The logical device that owns the images and memory.</param>
/// <param name="bindInfos">Structures describing images and memory to bind.</param>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static void BindImageMemory2Khr(this Device device, params BindImageMemoryInfoKhr[] bindInfos)
{
int count = bindInfos?.Length ?? 0;
var nativeBindInfos = stackalloc BindImageMemoryInfoKhr.Native[count];
for (int i = 0; i < count; i++)
bindInfos[i].ToNative(out nativeBindInfos[i]);
Result result = vkBindImageMemory2KHR(device)(device, count, nativeBindInfos);
for (int i = 0; i < count; i++)
nativeBindInfos[i].Free();
VulkanException.ThrowForInvalidResult(result);
}
/// <summary>
/// Create a new Ycbcr conversion.
/// </summary>
/// <param name="device">The logical device that creates the sampler Y'C~B~C~R~ conversion.</param>
/// <param name="createInfo">
/// Specifies the requested sampler Y'C~B~C~R~ conversion.
/// </param>
/// <param name="allocator">Controls host memory allocation.</param>
/// <returns>The resulting sampler Y'C~B~C~R~ conversion.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static SamplerYcbcrConversionKhr CreateSamplerYcbcrConversionKhr(this Device device,
SamplerYcbcrConversionCreateInfoKhr createInfo, AllocationCallbacks? allocator = null)
{
return new SamplerYcbcrConversionKhr(device, &createInfo, ref allocator);
}
private delegate Result vkGetMemoryWin32HandlePropertiesKHRDelegate(IntPtr device, ExternalMemoryHandleTypesKhr handleType, IntPtr handle, MemoryWin32HandlePropertiesKhr* memoryWin32HandleProperties);
private static vkGetMemoryWin32HandlePropertiesKHRDelegate vkGetMemoryWin32HandlePropertiesKHR(Device device) => device.GetProc<vkGetMemoryWin32HandlePropertiesKHRDelegate>(nameof(vkGetMemoryWin32HandlePropertiesKHR));
private delegate Result vkGetMemoryFdPropertiesKHRDelegate(IntPtr device, ExternalMemoryHandleTypesKhr handleType, int fd, MemoryFdPropertiesKhr* memoryFdProperties);
private static vkGetMemoryFdPropertiesKHRDelegate vkGetMemoryFdPropertiesKHR(Device device) => device.GetProc<vkGetMemoryFdPropertiesKHRDelegate>(nameof(vkGetMemoryFdPropertiesKHR));
private delegate Result vkImportSemaphoreWin32HandleKHRDelegate(IntPtr device, ImportSemaphoreWin32HandleInfoKhr.Native* importSemaphoreWin32HandleInfo);
private static vkImportSemaphoreWin32HandleKHRDelegate vkImportSemaphoreWin32HandleKHR(Device device) => device.GetProc<vkImportSemaphoreWin32HandleKHRDelegate>(nameof(vkImportSemaphoreWin32HandleKHR));
private delegate Result vkImportSemaphoreFdKHRDelegate(IntPtr device, ImportSemaphoreFdInfoKhr.Native* importSemaphoreFdInfo);
private static vkImportSemaphoreFdKHRDelegate vkImportSemaphoreFdKHR(Device device) => device.GetProc<vkImportSemaphoreFdKHRDelegate>(nameof(vkImportSemaphoreFdKHR));
private delegate void vkGetBufferMemoryRequirements2KHRDelegate(IntPtr device, BufferMemoryRequirementsInfo2Khr* info, MemoryRequirements2Khr* memoryRequirements);
private static vkGetBufferMemoryRequirements2KHRDelegate vkGetBufferMemoryRequirements2KHR(Device device) => device.GetProc<vkGetBufferMemoryRequirements2KHRDelegate>(nameof(vkGetBufferMemoryRequirements2KHR));
private delegate void vkGetImageMemoryRequirements2KHRDelegate(IntPtr device, ImageMemoryRequirementsInfo2Khr* info, MemoryRequirements2Khr* memoryRequirements);
private static vkGetImageMemoryRequirements2KHRDelegate vkGetImageMemoryRequirements2KHR(Device device) => device.GetProc<vkGetImageMemoryRequirements2KHRDelegate>(nameof(vkGetImageMemoryRequirements2KHR));
private delegate void vkGetImageSparseMemoryRequirements2KHRDelegate(IntPtr device, ImageSparseMemoryRequirementsInfo2Khr* info, int* sparseMemoryRequirementCount, SparseImageMemoryRequirements2Khr* sparseMemoryRequirements);
private static vkGetImageSparseMemoryRequirements2KHRDelegate vkGetImageSparseMemoryRequirements2KHR(Device device) => device.GetProc<vkGetImageSparseMemoryRequirements2KHRDelegate>(nameof(vkGetImageSparseMemoryRequirements2KHR));
private delegate Result vkBindBufferMemory2KHRDelegate(IntPtr device, int bindInfoCount, BindBufferMemoryInfoKhr.Native* bindInfos);
private static vkBindBufferMemory2KHRDelegate vkBindBufferMemory2KHR(Device device) => device.GetProc<vkBindBufferMemory2KHRDelegate>(nameof(vkBindBufferMemory2KHR));
private delegate Result vkBindImageMemory2KHRDelegate(IntPtr device, int bindInfoCount, BindImageMemoryInfoKhr.Native* bindInfos);
private static vkBindImageMemory2KHRDelegate vkBindImageMemory2KHR(Device device) => device.GetProc<vkBindImageMemory2KHRDelegate>(nameof(vkBindImageMemory2KHR));
}
/// <summary>
/// Structure specifying Windows handle to import to a semaphore.
/// </summary>
public struct ImportSemaphoreWin32HandleInfoKhr
{
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The semaphore into which the state will be imported.
/// </summary>
public Semaphore Semaphore;
/// <summary>
/// Specifies additional parameters for the semaphore payload import operation.
/// </summary>
public SemaphoreImportFlagsKhr Flags;
/// <summary>
/// Specifies the type of <see cref="Handle"/>.
/// </summary>
public ExternalSemaphoreHandleTypesKhr HandleType;
/// <summary>
/// The external handle to import, or <c>null</c>.
/// </summary>
public IntPtr Handle;
/// <summary>
/// A NULL-terminated UTF-16 string naming the underlying synchronization primitive to
/// import, or <c>null</c>.
/// </summary>
public IntPtr Name;
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public long Semaphore;
public SemaphoreImportFlagsKhr Flags;
public ExternalSemaphoreHandleTypesKhr HandleType;
public IntPtr Handle;
public IntPtr Name;
}
internal static void FromNative(ref Native native, Semaphore semaphore,
out ImportSemaphoreWin32HandleInfoKhr managed)
{
managed.Next = native.Next;
managed.Semaphore = semaphore;
managed.Flags = native.Flags;
managed.HandleType = native.HandleType;
managed.Handle = native.Handle;
managed.Name = native.Name;
}
}
/// <summary>
/// Structure specifying POSIX file descriptor to import to a semaphore.
/// </summary>
public struct ImportSemaphoreFdInfoKhr
{
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The semaphore into which the payload will be imported.
/// </summary>
public Semaphore Semaphore;
/// <summary>
/// Specifies additional parameters for the semaphore payload import operation.
/// </summary>
public SemaphoreImportFlagsKhr Flags;
/// <summary>
/// Specifies the type of <see cref="Fd"/>.
/// </summary>
public ExternalSemaphoreHandleTypesKhr HandleType;
/// <summary>
/// The external handle to import.
/// </summary>
public int Fd;
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public long Semaphore;
public SemaphoreImportFlagsKhr Flags;
public ExternalSemaphoreHandleTypesKhr HandleType;
public int Fd;
}
internal static void FromNative(ref Native native, Semaphore semaphore,
out ImportSemaphoreFdInfoKhr managed)
{
managed.Next = native.Next;
managed.Semaphore = semaphore;
managed.Flags = native.Flags;
managed.HandleType = native.HandleType;
managed.Fd = native.Fd;
}
}
/// <summary>
/// Bitmask of valid external semaphore handle types.
/// </summary>
[Flags]
public enum ExternalSemaphoreHandleTypesKhr
{
/// <summary>
/// Specifies a POSIX file descriptor handle that has only limited valid usage outside of
/// Vulkan and other compatible APIs.
/// <para>
/// It must be compatible with the POSIX system calls <c>dup</c>, <c>dup2</c>, <c>close</c>,
/// and the non-standard system call <c>dup3</c>. Additionally, it must be transportable over
/// a socket using an <c>SCM_RIGHTS</c> control message.
/// </para>
/// <para>
/// It owns a reference to the underlying synchronization primitive represented by its Vulkan
/// semaphore object.
/// </para>
/// </summary>
OpaqueFd = 1 << 0,
/// <summary>
/// Specifies an NT handle that has only limited valid usage outside of Vulkan and other
/// compatible APIs.
/// <para>
/// It must be compatible with the functions <c>DuplicateHandle</c>, <c>CloseHandle</c>,
/// <c>CompareObjectHandles</c>, <c>GetHandleInformation</c>, and <c>SetHandleInformation</c>.
/// </para>
/// <para>
/// It owns a reference to the underlying synchronization primitive represented by its Vulkan
/// semaphore object.
/// </para>
/// </summary>
OpaqueWin32 = 1 << 1,
/// <summary>
/// Specifies a global share handle that has only limited valid usage outside of Vulkan and
/// other compatible APIs.
/// <para>It is not compatible with any native APIs.</para>
/// <para>
/// It does not own own a reference to the underlying synchronization primitive represented
/// its Vulkan semaphore object, and will therefore become invalid when all Vulkan semaphore
/// objects associated with it are destroyed.
/// </para>
/// </summary>
OpaqueWin32Kmt = 1 << 2,
/// <summary>
/// Specifies an NT handle returned by <c>ID3D12Device::CreateSharedHandle</c> referring to a
/// Direct3D 12 fence.
/// <para>
/// It owns a reference to the underlying synchronization primitive associated with the
/// Direct3D fence.
/// </para>
/// </summary>
D3D12Fence = 1 << 3,
/// <summary>
/// Specifies a POSIX file descriptor handle to a Linux or Android Fence object.
/// <para>
/// It can be used with any native API accepting a valid fence object file descriptor as input.
/// </para>
/// <para>
/// It owns a reference to the underlying synchronization primitive associated with the file descriptor.
/// </para>
/// <para>
/// Implementations which support importing this handle type must accept any type of fence FD
/// supported by the native system they are running on.
/// </para>
/// </summary>
SyncFd = 1 << 4
}
/// <summary>
/// Properties of external memory windows handles.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MemoryWin32HandlePropertiesKhr
{
internal StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// A bitmask containing one bit set for every memory type which the specified windows handle
/// can be imported as.
/// </summary>
public int MemoryTypeBits;
}
/// <summary>
/// Properties of external memory file descriptors.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MemoryFdPropertiesKhr
{
internal StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// A bitmask containing one bit set for every memory type which the specified file
/// descriptor can be imported as.
/// </summary>
public int MemoryTypeBits;
}
[StructLayout(LayoutKind.Sequential)]
public struct BufferMemoryRequirementsInfo2Khr
{
/// <summary>
/// Type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The <see cref="VulkanCore.Buffer"/> to query.
/// </summary>
public long Buffer;
}
/// <summary>
/// Structure specifying memory requirements.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MemoryRequirements2Khr
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// Describes the memory requirements of the resource.
/// </summary>
public MemoryRequirements MemoryRequirements;
}
[StructLayout(LayoutKind.Sequential)]
public struct ImageMemoryRequirementsInfo2Khr
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The <see cref="VulkanCore.Image"/> to query.
/// </summary>
public long Image;
}
[StructLayout(LayoutKind.Sequential)]
public struct ImageSparseMemoryRequirementsInfo2Khr
{
public StructureType Type;
/// <summary>
/// Pointer to next structure.
/// </summary>
public IntPtr Next;
public long Image;
}
[StructLayout(LayoutKind.Sequential)]
public struct SparseImageMemoryRequirements2Khr
{
public StructureType Type;
/// <summary>
/// Pointer to next structure.
/// </summary>
public IntPtr Next;
public SparseImageMemoryRequirements MemoryRequirements;
}
/// <summary>
/// Structure specifying how to bind a buffer to memory.
/// </summary>
public struct BindBufferMemoryInfoKhr
{
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The <see cref="VulkanCore.Buffer"/> to be attached to memory.
/// </summary>
public long Buffer;
/// <summary>
/// A <see cref="DeviceMemory"/> object describing the device memory to attach.
/// </summary>
public long Memory;
/// <summary>
/// The start offset of the region of memory which is to be bound to the buffer. The number
/// of bytes returned in the <see cref="MemoryRequirements.Size"/> member in memory, starting
/// from <see cref="MemoryOffset"/> bytes, will be bound to the specified buffer.
/// </summary>
public long MemoryOffset;
/// <summary>
/// An array of device indices.
/// </summary>
public int[] DeviceIndices;
/// <summary>
/// Initializes a new instance of the <see cref="BindBufferMemoryInfoKhr"/> structure.
/// </summary>
/// <param name="buffer">The <see cref="VulkanCore.Buffer"/> to be attached to memory.</param>
/// <param name="memory">
/// A <see cref="DeviceMemory"/> object describing the device memory to attach.
/// </param>
/// <param name="memoryOffset">
/// The start offset of the region of memory which is to be bound to the buffer. The number
/// of bytes returned in the <see cref="MemoryRequirements.Size"/> member in memory, starting
/// from <see cref="MemoryOffset"/> bytes, will be bound to the specified buffer.
/// </param>
/// <param name="deviceIndices">An array of device indices.</param>
/// <param name="next">
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </param>
public BindBufferMemoryInfoKhr(Buffer buffer, DeviceMemory memory, long memoryOffset,
int[] deviceIndices, IntPtr next = default(IntPtr))
{
Next = next;
Buffer = buffer;
Memory = memory;
MemoryOffset = memoryOffset;
DeviceIndices = deviceIndices;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public long Buffer;
public long Memory;
public long MemoryOffset;
public int DeviceIndexCount;
public IntPtr DeviceIndices;
public void Free()
{
Interop.Free(DeviceIndices);
}
}
internal void ToNative(out Native native)
{
native.Type = StructureType.BindBufferMemoryInfoKhr;
native.Next = Next;
native.Buffer = Buffer;
native.Memory = Memory;
native.MemoryOffset = MemoryOffset;
native.DeviceIndexCount = DeviceIndices?.Length ?? 0;
native.DeviceIndices = Interop.Struct.AllocToPointer(DeviceIndices);
}
}
/// <summary>
/// Structure specifying how to bind an image to memory.
/// </summary>
public struct BindImageMemoryInfoKhr
{
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The <see cref="VulkanCore.Image"/> to be attached to memory.
/// </summary>
public long Image;
/// <summary>
/// A <see cref="DeviceMemory"/> object describing the device memory to attach.
/// </summary>
public long Memory;
/// <summary>
/// The start offset of the region of memory which is to be bound to the image. The number of
/// bytes returned in the <see cref="MemoryRequirements.Size"/> member in memory, starting
/// from <see cref="MemoryOffset"/> bytes, will be bound to the specified image.
/// </summary>
public long MemoryOffset;
/// <summary>
/// An array of device indices.
/// </summary>
public int[] DeviceIndices;
/// <summary>
/// An array of rectangles describing which regions of the image are attached to each
/// instance of memory.
/// </summary>
public Rect2D[] SFRRects;
/// <summary>
/// Initializes a new instance of the <see cref="BindImageMemoryInfoKhr"/> structure.
/// </summary>
/// <param name="image">The <see cref="VulkanCore.Image"/> to be attached to memory.</param>
/// <param name="memory">
/// A <see cref="DeviceMemory"/> object describing the device memory to attach.
/// </param>
/// <param name="memoryOffset">
/// The start offset of the region of memory which is to be bound to the image. If the length
/// of <see cref="SFRRects"/> is zero, the number of bytes returned in the <see
/// cref="MemoryRequirements.Size"/> member in memory, starting from <see
/// cref="MemoryOffset"/> bytes, will be bound to the specified image.
/// </param>
/// <param name="deviceIndices">An array of device indices.</param>
/// <param name="sfrRects">
/// An array of rectangles describing which regions of the image are attached to each
/// instance of memory.
/// </param>
/// <param name="next">
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </param>
public BindImageMemoryInfoKhr(Image image, DeviceMemory memory, long memoryOffset,
int[] deviceIndices, Rect2D[] sfrRects = null, IntPtr next = default(IntPtr))
{
Next = next;
Image = image;
Memory = memory;
MemoryOffset = memoryOffset;
DeviceIndices = deviceIndices;
SFRRects = sfrRects;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public long Image;
public long Memory;
public long MemoryOffset;
public int DeviceIndexCount;
public IntPtr DeviceIndices;
public int SFRRectCount;
public IntPtr SFRRects;
public void Free()
{
Interop.Free(DeviceIndices);
Interop.Free(SFRRects);
}
}
internal void ToNative(out Native native)
{
native.Type = StructureType.BindBufferMemoryInfoKhr;
native.Next = Next;
native.Image = Image;
native.Memory = Memory;
native.MemoryOffset = MemoryOffset;
native.DeviceIndexCount = DeviceIndices?.Length ?? 0;
native.DeviceIndices = Interop.Struct.AllocToPointer(DeviceIndices);
native.SFRRectCount = SFRRects?.Length ?? 0;
native.SFRRects = Interop.Struct.AllocToPointer(SFRRects);
}
}
/// <summary>
/// Enum specifying the point clipping behaviour.
/// </summary>
public enum PointClippingBehaviorKhr
{
AllClipPlanes = 0,
UserClipPlanesOnly = 1
}
/// <summary>
/// Enum describing tessellation domain origin.
/// </summary>
public enum TessellationDomainOriginKhr
{
/// <summary>
/// Indicates that the origin of the domain space is in the upper left corner.
/// </summary>
UpperLeft = 0,
/// <summary>
/// Indicates that the origin of the domain space is in the lower left corner.
/// </summary>
LowerLeft = 1
}
/// <summary>
/// Structure specifying a subpass/input attachment pair and an aspect mask that can be read.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct InputAttachmentAspectReferenceKhr
{
/// <summary>
/// An index into the parent <see cref="RenderPassCreateInfo.Subpasses"/>.
/// </summary>
public int Subpass;
public int InputAttachmentIndex;
/// <summary>
/// A mask of which aspect(s) can be accessed within the specified subpass.
/// </summary>
public int AspectMask;
}
/// <summary>
/// Structure specifying, for a given subpass/input attachment pair, which aspect can be read.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct RenderPassInputAttachmentAspectCreateInfoKhr
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The number of elements in the <see cref="AspectReferences"/> array.
/// </summary>
public int AspectReferenceCount;
/// <summary>
/// Points to an array of <see cref="AspectReferenceCount"/> number of <see
/// cref="InputAttachmentAspectReferenceKhr"/> structures describing which aspect(s) can be
/// accessed for a given input attachment within a given subpass.
/// </summary>
public IntPtr AspectReferences;
}
/// <summary>
/// Specify the intended usage of an image view.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ImageViewUsageCreateInfoKhr
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// A bitmask describing the allowed usages of the image view.
/// </summary>
public ImageUsages Usage;
}
/// <summary>
/// Structure specifying the orientation of the tessellation domain.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct PipelineTessellationDomainOriginStateCreateInfoKhr
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// Controls the origin of the tessellation domain space.
/// </summary>
public TessellationDomainOriginKhr DomainOrigin;
}
/// <summary>
/// Structure specifying how to bind an image plane to memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct BindImagePlaneMemoryInfoKhr
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The aspect of the disjoint image plane to bind.
/// </summary>
public ImageAspects PlaneAspect;
}
/// <summary>
/// Structure specifying image plane for memory requirements.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ImagePlaneMemoryRequirementsInfoKhr
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The aspect corresponding to the image plane to query.
/// </summary>
public ImageAspects PlaneAspect;
}
/// <summary>
/// Specify that an image can be used with a particular set of formats.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ImageFormatListCreateInfoKhr
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The number of entries in the <see cref="ViewFormats"/> array.
/// </summary>
public int ViewFormatCount;
/// <summary>
/// An array which lists of all formats which can be used when creating views of this image.
/// </summary>
public IntPtr ViewFormats;
}
}
| |
using System;
using MonoDevelop.Projects;
using System.Xml;
using MonoDevelop.Core.Assemblies;
namespace MonoDevelop.Cocos2D
{
public static class Cocos2DBuildAction
{
public static readonly string Shader;
public static bool IsCocos2DBuildAction(string action)
{
return action == Shader;
}
static Cocos2DBuildAction ()
{
Shader = "Cocos2DShader";
}
}
public class Cocos2DProject : DotNetAssemblyProject
{
public Cocos2DProject ()
{
Init ();
}
public Cocos2DProject (string languageName)
: base (languageName)
{
Init ();
}
public Cocos2DProject (string languageName, ProjectCreateInformation info, XmlElement projectOptions)
: base (languageName, info, projectOptions)
{
Init ();
}
private void Init()
{
}
public override SolutionItemConfiguration CreateConfiguration (string name)
{
var conf = new Cocos2DProjectConfiguration (name);
conf.CopyFrom (base.CreateConfiguration (name));
return conf;
}
public override bool SupportsFormat (FileFormat format)
{
return format.Id == "MSBuild10";
}
public override TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (FileFormat format)
{
return new TargetFrameworkMoniker("4.0");
}
public override bool SupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework)
{
if (!framework.IsCompatibleWithFramework (MonoDevelop.Core.Assemblies.TargetFrameworkMoniker.NET_4_0))
return false;
else
return base.SupportsFramework (framework);
}
protected override System.Collections.Generic.IList<string> GetCommonBuildActions ()
{
var actions = new System.Collections.Generic.List<string>(base.GetCommonBuildActions());
actions.Add(Cocos2DBuildAction.Shader);
return actions;
}
public override string GetDefaultBuildAction (string fileName)
{
if (System.IO.Path.GetExtension(fileName) == ".fx")
{
return Cocos2DBuildAction.Shader;
}
return base.GetDefaultBuildAction (fileName);
}
protected override void PopulateSupportFileList(FileCopySet list, ConfigurationSelector solutionConfiguration)
{
base.PopulateSupportFileList(list, solutionConfiguration);
//HACK: workaround for MD not local-copying package references
foreach (var projectReference in References)
{
if (projectReference.Package != null && projectReference.Package.Name == "Cocos2D")
{
if (projectReference.ReferenceType == ReferenceType.Gac)
{
foreach (var assem in projectReference.Package.Assemblies)
{
list.Add(assem.Location);
var cfg = (Cocos2DProjectConfiguration)solutionConfiguration.GetConfiguration(this);
if (cfg.DebugMode)
{
var mdbFile = TargetRuntime.GetAssemblyDebugInfoFile(assem.Location);
if (System.IO.File.Exists(mdbFile))
list.Add(mdbFile);
}
}
}
break;
}
}
}
}
public class Cocos2DBuildExtension : ProjectServiceExtension
{
protected override BuildResult Build (MonoDevelop.Core.IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration)
{
#if DEBUG
monitor.Log.WriteLine("Cocos2D Extension Build Called");
#endif
try
{
return base.Build (monitor, item, configuration);
}
finally
{
#if DEBUG
monitor.Log.WriteLine("Cocos2D Extension Build Ended");
#endif
}
}
protected override BuildResult Compile (MonoDevelop.Core.IProgressMonitor monitor, SolutionEntityItem item, BuildData buildData)
{
#if DEBUG
monitor.Log.WriteLine("Cocos2D Extension Compile Called");
#endif
try
{
var proj = item as Cocos2DProject;
if (proj == null)
{
return base.Compile (monitor, item, buildData);
}
var results = new System.Collections.Generic.List<BuildResult>();
foreach(var file in proj.Files)
{
if (Cocos2DBuildAction.IsCocos2DBuildAction(file.BuildAction))
{
buildData.Items.Add(file);
var buildResult = Cocos2DContentProcessor.Compile(file, monitor, buildData);
results.Add(buildResult);
}
}
return base.Compile (monitor, item, buildData).Append(results);
}
finally
{
#if DEBUG
monitor.Log.WriteLine("Cocos2D Extension Compile Ended");
#endif
}
}
}
public class Cocos2DProjectBinding : IProjectBinding
{
public Project CreateProject (ProjectCreateInformation info, System.Xml.XmlElement projectOptions)
{
string lang = projectOptions.GetAttribute ("language");
return new Cocos2DProject (lang, info, projectOptions);
}
public Project CreateSingleFileProject (string sourceFile)
{
throw new InvalidOperationException ();
}
public bool CanCreateSingleFileProject (string sourceFile)
{
return false;
}
public string Name {
get { return "Cocos2D"; }
}
}
public class Cocos2DProjectConfiguration : DotNetProjectConfiguration
{
public Cocos2DProjectConfiguration () : base ()
{
}
public Cocos2DProjectConfiguration (string name) : base (name)
{
}
public override void CopyFrom (ItemConfiguration configuration)
{
base.CopyFrom (configuration);
}
}
public class Cocos2DContentProcessor
{
public static BuildResult Compile(ProjectFile file,MonoDevelop.Core.IProgressMonitor monitor,BuildData buildData)
{
switch (file.BuildAction) {
case "Cocos2DShader" :
var result = new BuildResult();
monitor.Log.WriteLine("Compiling Shader");
monitor.Log.WriteLine("Shader : "+buildData.Configuration.OutputDirectory);
monitor.Log.WriteLine("Shader : "+file.FilePath);
monitor.Log.WriteLine("Shader : "+file.ToString());
return result;
default:
return new BuildResult();
}
}
}
}
| |
// Copyright Bastian Eicher
// Licensed under the MIT License
#if !NET20 && !NET40
using System.Runtime.CompilerServices;
#endif
namespace NanoByte.Common;
/// <summary>
/// Provides neat little code-shortcuts for updating properties.
/// </summary>
public static class UpdateUtils
{
/// <summary>
/// Immediately invokes the specified <paramref name="action"/> with the <paramref name="value"/>. Useful for applying null-coalescing operator.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="action">The action to invoke.</param>
/// <example>
/// This allows you to write:
/// <code>
/// Uri? uri = nullableString?.To(x => new Uri(x);
/// </code>
/// Instead of:
/// <code>
/// Uri? uri = nullableString == null ? null : new Uri(nullableString);
/// </code>
/// </example>
#if !NET20 && !NET40
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static TOut To<TIn, TOut>(this TIn value, [InstantHandle] Func<TIn, TOut> action)
=> (action ?? throw new ArgumentNullException(nameof(action))).Invoke(value);
/// <summary>
/// Updates a value and sets a boolean flag to <c>true</c> if the original value actually changed.
/// </summary>
/// <typeparam name="T">The type of data to update.</typeparam>
/// <param name="value">The new value.</param>
/// <param name="original">The original value to update.</param>
/// <param name="updated">Gets set to <c>true</c> if value is different from original.</param>
#if !NET20 && !NET40
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static void To<T>(this T value, ref T original, ref bool updated) where T : struct
{
// If the values already match, nothing needs to be done
if (original.Equals(value)) return;
// Otherwise set the "updated" flag and change the value
updated = true;
original = value;
}
/// <summary>
/// Updates a value and sets two boolean flags to <c>true</c> if the original value actually changed.
/// </summary>
/// <typeparam name="T">The type of data to update.</typeparam>
/// <param name="value">The new value.</param>
/// <param name="original">The original value to update.</param>
/// <param name="updated1">Gets set to <c>true</c> if value is different from original.</param>
/// <param name="updated2">Gets set to <c>true</c> if value is different from original.</param>
#if !NET20 && !NET40
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static void To<T>(this T value, ref T original, ref bool updated1, ref bool updated2) where T : struct
{
// If the values already match, nothing needs to be done
if (original.Equals(value)) return;
updated1 = true;
updated2 = true;
original = value;
}
/// <summary>
/// Updates a value and sets a boolean flag to <c>true</c> if the original value actually changed
/// </summary>
/// <param name="value">The new value</param>
/// <param name="original">The original value to update</param>
/// <param name="updated">Gets set to <c>true</c> if value is different from original</param>
#if !NET20 && !NET40
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static void To(this string value, ref string original, ref bool updated)
{
// If the values already match, nothing needs to be done
if (original == value) return;
// Otherwise set the "updated" flag and change the value
updated = true;
original = value;
}
/// <summary>
/// Updates a value and sets two boolean flags to <c>true</c> if the original value actually changed
/// </summary>
/// <param name="value">The new value</param>
/// <param name="original">The original value to update</param>
/// <param name="updated1">Gets set to <c>true</c> if value is different from original</param>
/// <param name="updated2">Gets set to <c>true</c> if value is different from original</param>
#if !NET20 && !NET40
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static void To(this string value, ref string original, ref bool updated1, ref bool updated2)
{
if (original == value) return;
updated1 = true;
updated2 = true;
original = value;
}
/// <summary>
/// Updates a value and calls back a delegate if the original value actually changed.
/// </summary>
/// <typeparam name="T">The type of data to update.</typeparam>
/// <param name="value">The new value.</param>
/// <param name="original">The original value to update.</param>
/// <param name="updated">Gets called if value is different from original.</param>
#if !NET20 && !NET40
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static void To<T>(this T value, ref T original, [InstantHandle] Action updated) where T : struct
{
#region Sanity checks
if (updated == null) throw new ArgumentNullException(nameof(updated));
#endregion
// If the values already match, nothing needs to be done
if (original.Equals(value)) return;
// Backup the original value in case it needs to be reverted
var backup = original;
// Set the new value
original = value;
// Execute the "updated" delegate
try
{
updated.Invoke();
}
catch
{
// Restore the original value before passing exceptions upwards
original = backup;
throw;
}
}
/// <summary>
/// Updates a value and calls back a delegate if the original value actually changed.
/// </summary>
/// <param name="value">The new value.</param>
/// <param name="original">The original value to update.</param>
/// <param name="updated">Gets called if value is different from original.</param>
#if !NET20 && !NET40
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static void To(this string value, ref string original, [InstantHandle] Action updated)
{
#region Sanity checks
if (updated == null) throw new ArgumentNullException(nameof(updated));
#endregion
// If the values already match, nothing needs to be done
if (original == value) return;
// Backup the original value in case it needs to be reverted
string backup = original;
// Set the new value
original = value;
// Execute the "updated" delegate
try
{
updated.Invoke();
}
catch
{
// Restore the original value before passing exceptions upwards
original = backup;
throw;
}
}
/// <summary>
/// Swaps the content of two fields.
/// </summary>
/// <typeparam name="T">The type of objects to swap.</typeparam>
/// <param name="value1">The first field which will afterwards carry the content of <paramref name="value2"/>.</param>
/// <param name="value2">The first field which will afterwards carry the content of <paramref name="value1"/>.</param>
#if !NET20 && !NET40
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static void Swap<T>(ref T value1, ref T value2)
{
var tempValue = value1;
value1 = value2;
value2 = tempValue;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace PetStore.Server.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/**
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Text;
using Thrift.Transport;
namespace Thrift.Protocol
{
public class TBinaryProtocol : TProtocol
{
protected const uint VERSION_MASK = 0xffff0000;
protected const uint VERSION_1 = 0x80010000;
protected bool strictRead_ = false;
protected bool strictWrite_ = true;
protected int readLength_;
protected bool checkReadLength_ = false;
#region BinaryProtocol Factory
/**
* Factory
*/
public class Factory : TProtocolFactory {
protected bool strictRead_ = false;
protected bool strictWrite_ = true;
public Factory()
:this(false, true)
{
}
public Factory(bool strictRead, bool strictWrite)
{
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
public TProtocol GetProtocol(TTransport trans) {
return new TBinaryProtocol(trans, strictRead_, strictWrite_);
}
}
#endregion
public TBinaryProtocol(TTransport trans)
: this(trans, false, true)
{
}
public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite)
:base(trans)
{
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
#region Write Methods
public override void WriteMessageBegin(TMessage message)
{
if (strictWrite_)
{
uint version = VERSION_1 | (uint)(message.Type);
WriteI32((int)version);
WriteString(message.Name);
WriteI32(message.SeqID);
}
else
{
WriteString(message.Name);
WriteByte((sbyte)message.Type);
WriteI32(message.SeqID);
}
}
public override void WriteMessageEnd()
{
}
public override void WriteStructBegin(TStruct struc)
{
}
public override void WriteStructEnd()
{
}
public override void WriteFieldBegin(TField field)
{
WriteByte((sbyte)field.Type);
WriteI16(field.ID);
}
public override void WriteFieldEnd()
{
}
public override void WriteFieldStop()
{
WriteByte((sbyte)TType.Stop);
}
public override void WriteMapBegin(TMap map)
{
WriteByte((sbyte)map.KeyType);
WriteByte((sbyte)map.ValueType);
WriteI32(map.Count);
}
public override void WriteMapEnd()
{
}
public override void WriteListBegin(TList list)
{
WriteByte((sbyte)list.ElementType);
WriteI32(list.Count);
}
public override void WriteListEnd()
{
}
public override void WriteSetBegin(TSet set)
{
WriteByte((sbyte)set.ElementType);
WriteI32(set.Count);
}
public override void WriteSetEnd()
{
}
public override void WriteBool(bool b)
{
WriteByte(b ? (sbyte)1 : (sbyte)0);
}
private byte[] bout = new byte[1];
public override void WriteByte(sbyte b)
{
bout[0] = (byte)b;
trans.Write(bout, 0, 1);
}
private byte[] i16out = new byte[2];
public override void WriteI16(short s)
{
i16out[0] = (byte)(0xff & (s >> 8));
i16out[1] = (byte)(0xff & s);
trans.Write(i16out, 0, 2);
}
private byte[] i32out = new byte[4];
public override void WriteI32(int i32)
{
i32out[0] = (byte)(0xff & (i32 >> 24));
i32out[1] = (byte)(0xff & (i32 >> 16));
i32out[2] = (byte)(0xff & (i32 >> 8));
i32out[3] = (byte)(0xff & i32);
trans.Write(i32out, 0, 4);
}
private byte[] i64out = new byte[8];
public override void WriteI64(long i64)
{
i64out[0] = (byte)(0xff & (i64 >> 56));
i64out[1] = (byte)(0xff & (i64 >> 48));
i64out[2] = (byte)(0xff & (i64 >> 40));
i64out[3] = (byte)(0xff & (i64 >> 32));
i64out[4] = (byte)(0xff & (i64 >> 24));
i64out[5] = (byte)(0xff & (i64 >> 16));
i64out[6] = (byte)(0xff & (i64 >> 8));
i64out[7] = (byte)(0xff & i64);
trans.Write(i64out, 0, 8);
}
public override void WriteDouble(double d)
{
#if !SILVERLIGHT
WriteI64(BitConverter.DoubleToInt64Bits(d));
#else
var bytes = BitConverter.GetBytes(d);
WriteI64(BitConverter.ToInt64(bytes, 0));
#endif
}
public override void WriteBinary(byte[] b)
{
WriteI32(b.Length);
trans.Write(b, 0, b.Length);
}
#endregion
#region ReadMethods
public override TMessage ReadMessageBegin()
{
TMessage message = new TMessage();
int size = ReadI32();
if (size < 0)
{
uint version = (uint)size & VERSION_MASK;
if (version != VERSION_1)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in ReadMessageBegin: " + version);
}
message.Type = (TMessageType)(size & 0x000000ff);
message.Name = ReadString();
message.SeqID = ReadI32();
}
else
{
if (strictRead_)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?");
}
message.Name = ReadStringBody(size);
message.Type = (TMessageType)ReadByte();
message.SeqID = ReadI32();
}
return message;
}
public override void ReadMessageEnd()
{
}
public override TStruct ReadStructBegin()
{
return new TStruct();
}
public override void ReadStructEnd()
{
}
public override TField ReadFieldBegin()
{
TField field = new TField();
field.Type = (TType)ReadByte();
if (field.Type != TType.Stop)
{
field.ID = ReadI16();
}
return field;
}
public override void ReadFieldEnd()
{
}
public override TMap ReadMapBegin()
{
TMap map = new TMap();
map.KeyType = (TType)ReadByte();
map.ValueType = (TType)ReadByte();
map.Count = ReadI32();
return map;
}
public override void ReadMapEnd()
{
}
public override TList ReadListBegin()
{
TList list = new TList();
list.ElementType = (TType)ReadByte();
list.Count = ReadI32();
return list;
}
public override void ReadListEnd()
{
}
public override TSet ReadSetBegin()
{
TSet set = new TSet();
set.ElementType = (TType)ReadByte();
set.Count = ReadI32();
return set;
}
public override void ReadSetEnd()
{
}
public override bool ReadBool()
{
return ReadByte() == 1;
}
private byte[] bin = new byte[1];
public override sbyte ReadByte()
{
ReadAll(bin, 0, 1);
return (sbyte)bin[0];
}
private byte[] i16in = new byte[2];
public override short ReadI16()
{
ReadAll(i16in, 0, 2);
return (short)(((i16in[0] & 0xff) << 8) | ((i16in[1] & 0xff)));
}
private byte[] i32in = new byte[4];
public override int ReadI32()
{
ReadAll(i32in, 0, 4);
return (int)(((i32in[0] & 0xff) << 24) | ((i32in[1] & 0xff) << 16) | ((i32in[2] & 0xff) << 8) | ((i32in[3] & 0xff)));
}
#pragma warning disable 675
private byte[] i64in = new byte[8];
public override long ReadI64()
{
ReadAll(i64in, 0, 8);
unchecked {
return (long)(
((long)(i64in[0] & 0xff) << 56) |
((long)(i64in[1] & 0xff) << 48) |
((long)(i64in[2] & 0xff) << 40) |
((long)(i64in[3] & 0xff) << 32) |
((long)(i64in[4] & 0xff) << 24) |
((long)(i64in[5] & 0xff) << 16) |
((long)(i64in[6] & 0xff) << 8) |
((long)(i64in[7] & 0xff)));
}
}
#pragma warning restore 675
public override double ReadDouble()
{
#if !SILVERLIGHT
return BitConverter.Int64BitsToDouble(ReadI64());
#else
var value = ReadI64();
var bytes = BitConverter.GetBytes(value);
return BitConverter.ToDouble(bytes, 0);
#endif
}
public void SetReadLength(int readLength)
{
readLength_ = readLength;
checkReadLength_ = true;
}
protected void CheckReadLength(int length)
{
if (checkReadLength_)
{
readLength_ -= length;
if (readLength_ < 0)
{
throw new Exception("Message length exceeded: " + length);
}
}
}
public override byte[] ReadBinary()
{
int size = ReadI32();
CheckReadLength(size);
byte[] buf = new byte[size];
trans.ReadAll(buf, 0, size);
return buf;
}
private string ReadStringBody(int size)
{
CheckReadLength(size);
byte[] buf = new byte[size];
trans.ReadAll(buf, 0, size);
return Encoding.UTF8.GetString(buf, 0, buf.Length);
}
private int ReadAll(byte[] buf, int off, int len)
{
CheckReadLength(len);
return trans.ReadAll(buf, off, len);
}
#endregion
}
}
| |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.Reflection;
using Quartz.Util;
namespace Quartz.Impl
{
/// <summary>
/// Model for saving attribute's information in cache
/// Used in key/value pair with <see cref="IJobDetail.JobType"/> as a value
/// and show presence of attributes of specified type
/// </summary>
/// <seealso cref="DisallowConcurrentExecutionAttribute"/>
/// <seealso cref="PersistJobDataAfterExecutionAttribute"/>
internal class JobTypeInformation
{
internal bool ConcurrentExecutionDisallowed { get; set; }
internal bool PersistJobDataAfterExecution { get; set; }
}
/// <summary>
/// Conveys the detail properties of a given job instance.
/// </summary>
/// <remarks>
/// Quartz does not store an actual instance of a <see cref="IJob" /> type, but
/// instead allows you to define an instance of one, through the use of a <see cref="IJobDetail" />.
/// <para>
/// <see cref="IJob" />s have a name and group associated with them, which
/// should uniquely identify them within a single <see cref="IScheduler" />.
/// </para>
/// <para>
/// <see cref="ITrigger" /> s are the 'mechanism' by which <see cref="IJob" /> s
/// are scheduled. Many <see cref="ITrigger" /> s can point to the same <see cref="IJob" />,
/// but a single <see cref="ITrigger" /> can only point to one <see cref="IJob" />.
/// </para>
/// </remarks>
/// <seealso cref="IJob" />
/// <seealso cref="DisallowConcurrentExecutionAttribute"/>
/// <seealso cref="PersistJobDataAfterExecutionAttribute"/>
/// <seealso cref="JobDataMap"/>
/// <seealso cref="ITrigger"/>
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class JobDetailImpl : IJobDetail
{
private static readonly ConcurrentDictionary<Type, JobTypeInformation> jobTypeCache = new ConcurrentDictionary<Type, JobTypeInformation>();
private string name = null!;
private string group = SchedulerConstants.DefaultGroup;
private string? description;
private JobDataMap jobDataMap = null!;
private Type jobType = null!;
[NonSerialized] // we have the key in string fields
private JobKey key = null!;
/// <summary>
/// Create a <see cref="IJobDetail" /> with no specified name or group, and
/// the default settings of all the other properties.
/// <para>
/// Note that the <see cref="Name" />,<see cref="Group" /> and
/// <see cref="JobType" /> properties must be set before the job can be
/// placed into a <see cref="IScheduler" />.
/// </para>
/// </summary>
public JobDetailImpl()
{
// do nothing...
}
/// <summary>
/// Create a <see cref="IJobDetail" /> with the given name, default group, and
/// the default settings of all the other properties.
/// If <see langword="null" />, SchedulerConstants.DefaultGroup will be used.
/// </summary>
/// <exception cref="ArgumentException">
/// If name is null or empty, or the group is an empty string.
/// </exception>
public JobDetailImpl(string name, Type jobType) : this(name, SchedulerConstants.DefaultGroup, jobType)
{
}
/// <summary>
/// Create a <see cref="IJobDetail" /> with the given name, and group, and
/// the default settings of all the other properties.
/// If <see langword="null" />, SchedulerConstants.DefaultGroup will be used.
/// </summary>
/// <exception cref="ArgumentException">
/// If name is null or empty, or the group is an empty string.
/// </exception>
public JobDetailImpl(string name, string group, Type jobType)
{
Name = name;
Group = group;
JobType = jobType;
}
/// <summary>
/// Create a <see cref="IJobDetail" /> with the given name, and group, and
/// the given settings of all the other properties.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">if <see langword="null" />, SchedulerConstants.DefaultGroup will be used.</param>
/// <param name="jobType">Type of the job.</param>
/// <param name="isDurable">if set to <c>true</c>, job will be durable.</param>
/// <param name="requestsRecovery">if set to <c>true</c>, job will request recovery.</param>
/// <exception cref="ArgumentException">
/// ArgumentException if name is null or empty, or the group is an empty string.
/// </exception>
public JobDetailImpl(string name, string group, Type jobType, bool isDurable, bool requestsRecovery)
{
Name = name;
Group = group;
JobType = jobType;
Durable = isDurable;
RequestsRecovery = requestsRecovery;
}
/// <summary>
/// Get or sets the name of this <see cref="IJob" />.
/// </summary>
/// <exception cref="ArgumentException">
/// if name is null or empty.
/// </exception>
public string Name
{
get => name;
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Job name cannot be empty.");
}
name = value;
}
}
/// <summary>
/// Get or sets the group of this <see cref="IJob" />.
/// If <see langword="null" />, <see cref="SchedulerConstants.DefaultGroup" /> will be used.
/// </summary>
/// <exception cref="ArgumentException">
/// If the group is an empty string.
/// </exception>
public string Group
{
get => group;
set
{
if (value != null && value.Trim().Length == 0)
{
throw new ArgumentException("Group name cannot be empty.");
}
if (value == null)
{
value = SchedulerConstants.DefaultGroup;
}
group = value;
}
}
/// <summary>
/// Returns the 'full name' of the <see cref="ITrigger" /> in the format
/// "group.name".
/// </summary>
public string FullName => group + "." + name;
/// <summary>
/// Gets the key.
/// </summary>
/// <value>The key.</value>
public JobKey Key
{
get
{
if (key == null)
{
if (Name == null)
{
return null!;
}
key = new JobKey(Name, Group);
}
return key;
}
set
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
Name = value.Name;
Group = value.Group;
key = value;
}
}
/// <summary>
/// Get or set the description given to the <see cref="IJob" /> instance by its
/// creator (if any).
/// </summary>
/// <remarks>
/// May be useful for remembering/displaying the purpose of the job, though the
/// description has no meaning to Quartz.
/// </remarks>
public string? Description
{
get => description;
set => description = value;
}
/// <summary>
/// Get or sets the instance of <see cref="IJob" /> that will be executed.
/// </summary>
/// <exception cref="ArgumentException">
/// if jobType is null or the class is not a <see cref="IJob" />.
/// </exception>
public virtual Type JobType
{
get => jobType;
set
{
if (value == null)
{
throw new ArgumentException("Job class cannot be null.");
}
if (!typeof(IJob).GetTypeInfo().IsAssignableFrom(value.GetTypeInfo()))
{
throw new ArgumentException("Job class must implement the Job interface.");
}
jobType = value;
}
}
/// <summary>
/// Get or set the <see cref="JobDataMap" /> that is associated with the <see cref="IJob" />.
/// </summary>
public virtual JobDataMap JobDataMap
{
get
{
if (jobDataMap == null)
{
jobDataMap = new JobDataMap();
}
return jobDataMap;
}
set => jobDataMap = value;
}
/// <summary>
/// Set whether or not the <see cref="IScheduler" /> should re-Execute
/// the <see cref="IJob" /> if a 'recovery' or 'fail-over' situation is
/// encountered.
/// <para>
/// If not explicitly set, the default value is <see langword="false" />.
/// </para>
/// </summary>
/// <seealso cref="IJobExecutionContext.Recovering" />
public bool RequestsRecovery { set; get; }
/// <summary>
/// Whether or not the <see cref="IJob" /> should remain stored after it is
/// orphaned (no <see cref="ITrigger" />s point to it).
/// <para>
/// If not explicitly set, the default value is <see langword="false" />.
/// </para>
/// </summary>
/// <returns>
/// <see langword="true" /> if the Job should remain persisted after
/// being orphaned.
/// </returns>
public bool Durable { get; set; }
/// <summary>
/// Whether the associated Job class carries the <see cref="PersistJobDataAfterExecutionAttribute" /> attribute.
/// </summary>
public virtual bool PersistJobDataAfterExecution => jobTypeCache.GetOrAdd(this.jobType, GetJobTypeInformation).PersistJobDataAfterExecution;
/// <summary>
/// Whether the associated Job class carries the <see cref="DisallowConcurrentExecutionAttribute" /> attribute.
/// </summary>
public virtual bool ConcurrentExecutionDisallowed => jobTypeCache.GetOrAdd(this.jobType, GetJobTypeInformation).ConcurrentExecutionDisallowed;
/// <summary>
/// Validates whether the properties of the <see cref="IJobDetail" /> are
/// valid for submission into a <see cref="IScheduler" />.
/// </summary>
public virtual void Validate()
{
if (name == null)
{
throw new SchedulerException("Job's name cannot be null");
}
if (group == null)
{
throw new SchedulerException("Job's group cannot be null");
}
if (jobType == null)
{
throw new SchedulerException("Job's class cannot be null");
}
}
/// <summary>
/// Return a simple string representation of this object.
/// </summary>
public override string ToString()
{
return
string.Format(
CultureInfo.InvariantCulture,
"JobDetail '{0}': jobType: '{1} persistJobDataAfterExecution: {2} concurrentExecutionDisallowed: {3} isDurable: {4} requestsRecovers: {5}",
FullName, JobType?.FullName, PersistJobDataAfterExecution, ConcurrentExecutionDisallowed, Durable, RequestsRecovery);
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public virtual IJobDetail Clone()
{
var copy = (JobDetailImpl) MemberwiseClone();
if (jobDataMap != null)
{
copy.jobDataMap = (JobDataMap) jobDataMap.Clone();
}
return copy;
}
/// <summary>
/// Determines whether the specified detail is equal to this instance.
/// </summary>
/// <param name="detail">The detail to examine.</param>
/// <returns>
/// <c>true</c> if the specified detail is equal; otherwise, <c>false</c>.
/// </returns>
protected virtual bool IsEqual(JobDetailImpl detail)
{
//doesn't consider job's saved data,
//durability etc
return detail != null && detail.Name == Name && detail.Group == Group && detail.JobType == JobType;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// <see langword="true"/> if the specified <see cref="T:System.Object"/> is equal to the
/// current <see cref="T:System.Object"/>; otherwise, <see langword="false"/>.
/// </returns>
public override bool Equals(object? obj)
{
if (!(obj is JobDetailImpl jd))
{
return false;
}
return IsEqual(jd);
}
/// <summary>
/// Checks equality between given job detail and this instance.
/// </summary>
/// <param name="detail">The detail to compare this instance with.</param>
/// <returns></returns>
public virtual bool Equals(JobDetailImpl detail)
{
return IsEqual(detail);
}
/// <summary>
/// Serves as a hash function for a particular type, suitable
/// for use in hashing algorithms and data structures like a hash table.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
return FullName.GetHashCode();
}
public virtual JobBuilder GetJobBuilder()
{
JobBuilder b = JobBuilder.Create()
.OfType(JobType)
.RequestRecovery(RequestsRecovery)
.StoreDurably(Durable)
.UsingJobData(JobDataMap)
.WithDescription(description)
.WithIdentity(Key);
return b;
}
/// <summary>
/// Return information about JobType as an instance
/// </summary>
/// <param name="jobType">The type for which information will be searched</param>
/// <returns>
/// An <see cref="JobTypeInformation"/> object that describe specified type
/// </returns>
/// <seealso cref="jobType"/>
private JobTypeInformation GetJobTypeInformation(Type jobType)
{
return new JobTypeInformation
{
PersistJobDataAfterExecution = ObjectUtils.IsAnyInterfaceAttributePresent(jobType, typeof(PersistJobDataAfterExecutionAttribute)),
ConcurrentExecutionDisallowed = ObjectUtils.IsAnyInterfaceAttributePresent(jobType, typeof(DisallowConcurrentExecutionAttribute))
};
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.Packets;
using log4net;
using OpenSim.Framework.Monitoring;
namespace OpenSim.Region.ClientStack.LindenUDP
{
public sealed class PacketPool
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly PacketPool instance = new PacketPool();
/// <summary>
/// Pool of packets available for reuse.
/// </summary>
private readonly Dictionary<PacketType, Stack<Packet>> pool = new Dictionary<PacketType, Stack<Packet>>();
private static Dictionary<Type, Stack<Object>> DataBlocks = new Dictionary<Type, Stack<Object>>();
public static PacketPool Instance
{
get { return instance; }
}
public bool RecyclePackets { get; set; }
public bool RecycleDataBlocks { get; set; }
/// <summary>
/// The number of packets pooled
/// </summary>
public int PacketsPooled
{
get
{
lock (pool)
return pool.Count;
}
}
/// <summary>
/// The number of blocks pooled.
/// </summary>
public int BlocksPooled
{
get
{
lock (DataBlocks)
return DataBlocks.Count;
}
}
/// <summary>
/// Number of packets requested.
/// </summary>
public long PacketsRequested { get; private set; }
/// <summary>
/// Number of packets reused.
/// </summary>
public long PacketsReused { get; private set; }
/// <summary>
/// Number of packet blocks requested.
/// </summary>
public long BlocksRequested { get; private set; }
/// <summary>
/// Number of packet blocks reused.
/// </summary>
public long BlocksReused { get; private set; }
private PacketPool()
{
// defaults
RecyclePackets = true;
RecycleDataBlocks = true;
}
/// <summary>
/// Gets a packet of the given type.
/// </summary>
/// <param name='type'></param>
/// <returns>Guaranteed to always return a packet, whether from the pool or newly constructed.</returns>
public Packet GetPacket(PacketType type)
{
PacketsRequested++;
Packet packet;
if (!RecyclePackets)
return Packet.BuildPacket(type);
lock (pool)
{
if (!pool.ContainsKey(type) || pool[type] == null || (pool[type]).Count == 0)
{
// m_log.DebugFormat("[PACKETPOOL]: Building {0} packet", type);
// Creating a new packet if we cannot reuse an old package
packet = Packet.BuildPacket(type);
}
else
{
// m_log.DebugFormat("[PACKETPOOL]: Pulling {0} packet", type);
// Recycle old packages
PacketsReused++;
packet = pool[type].Pop();
}
}
return packet;
}
// private byte[] decoded_header = new byte[10];
private static PacketType GetType(byte[] bytes)
{
byte[] decoded_header = new byte[10 + 8];
ushort id;
PacketFrequency freq;
if ((bytes[0] & Helpers.MSG_ZEROCODED) != 0)
{
Helpers.ZeroDecode(bytes, 16, decoded_header);
}
else
{
Buffer.BlockCopy(bytes, 0, decoded_header, 0, 10);
}
if (decoded_header[6] == 0xFF)
{
if (decoded_header[7] == 0xFF)
{
id = (ushort) ((decoded_header[8] << 8) + decoded_header[9]);
freq = PacketFrequency.Low;
}
else
{
id = decoded_header[7];
freq = PacketFrequency.Medium;
}
}
else
{
id = decoded_header[6];
freq = PacketFrequency.High;
}
return Packet.GetType(id, freq);
}
public Packet GetPacket(byte[] bytes, ref int packetEnd, byte[] zeroBuffer)
{
PacketType type = GetType(bytes);
// Array.Clear(zeroBuffer, 0, zeroBuffer.Length);
int i = 0;
Packet packet = GetPacket(type);
if (packet == null)
m_log.WarnFormat("[PACKETPOOL]: Failed to get packet of type {0}", type);
else
packet.FromBytes(bytes, ref i, ref packetEnd, zeroBuffer);
return packet;
}
/// <summary>
/// Return a packet to the packet pool
/// </summary>
/// <param name="packet"></param>
public void ReturnPacket(Packet packet)
{
if (RecycleDataBlocks)
{
switch (packet.Type)
{
case PacketType.ObjectUpdate:
ObjectUpdatePacket oup = (ObjectUpdatePacket)packet;
foreach (ObjectUpdatePacket.ObjectDataBlock oupod in oup.ObjectData)
ReturnDataBlock<ObjectUpdatePacket.ObjectDataBlock>(oupod);
oup.ObjectData = null;
break;
case PacketType.ImprovedTerseObjectUpdate:
ImprovedTerseObjectUpdatePacket itoup = (ImprovedTerseObjectUpdatePacket)packet;
foreach (ImprovedTerseObjectUpdatePacket.ObjectDataBlock itoupod in itoup.ObjectData)
ReturnDataBlock<ImprovedTerseObjectUpdatePacket.ObjectDataBlock>(itoupod);
itoup.ObjectData = null;
break;
}
}
if (RecyclePackets)
{
switch (packet.Type)
{
// List pooling packets here
case PacketType.AgentUpdate:
case PacketType.PacketAck:
case PacketType.ObjectUpdate:
case PacketType.ImprovedTerseObjectUpdate:
lock (pool)
{
PacketType type = packet.Type;
if (!pool.ContainsKey(type))
{
pool[type] = new Stack<Packet>();
}
if ((pool[type]).Count < 50)
{
// m_log.DebugFormat("[PACKETPOOL]: Pushing {0} packet", type);
pool[type].Push(packet);
}
}
break;
// Other packets wont pool
default:
return;
}
}
}
public T GetDataBlock<T>() where T: new()
{
lock (DataBlocks)
{
BlocksRequested++;
Stack<Object> s;
if (DataBlocks.TryGetValue(typeof(T), out s))
{
if (s.Count > 0)
{
BlocksReused++;
return (T)s.Pop();
}
}
else
{
DataBlocks[typeof(T)] = new Stack<Object>();
}
return new T();
}
}
public void ReturnDataBlock<T>(T block) where T: new()
{
if (block == null)
return;
lock (DataBlocks)
{
if (!DataBlocks.ContainsKey(typeof(T)))
DataBlocks[typeof(T)] = new Stack<Object>();
if (DataBlocks[typeof(T)].Count < 50)
DataBlocks[typeof(T)].Push(block);
}
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
using umbraco.cms.businesslogic.template;
using System.Collections.Generic;
namespace Umbraco.Web.Mvc
{
public class RenderRouteHandler : IRouteHandler
{
// Define reserved dictionary keys for controller, action and area specified in route additional values data
private static class ReservedAdditionalKeys
{
internal const string Controller = "c";
internal const string Action = "a";
internal const string Area = "ar";
}
public RenderRouteHandler(IControllerFactory controllerFactory)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
_controllerFactory = controllerFactory;
}
/// <summary>
/// Contructor generally used for unit testing
/// </summary>
/// <param name="controllerFactory"></param>
/// <param name="umbracoContext"></param>
internal RenderRouteHandler(IControllerFactory controllerFactory, UmbracoContext umbracoContext)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
_controllerFactory = controllerFactory;
_umbracoContext = umbracoContext;
}
private readonly IControllerFactory _controllerFactory;
private readonly UmbracoContext _umbracoContext;
/// <summary>
/// Returns the current UmbracoContext
/// </summary>
public UmbracoContext UmbracoContext
{
get { return _umbracoContext ?? UmbracoContext.Current; }
}
#region IRouteHandler Members
/// <summary>
/// Assigns the correct controller based on the Umbraco request and returns a standard MvcHandler to prcess the response,
/// this also stores the render model into the data tokens for the current RouteData.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (UmbracoContext == null)
{
throw new NullReferenceException("There is not current UmbracoContext, it must be initialized before the RenderRouteHandler executes");
}
var docRequest = UmbracoContext.PublishedContentRequest;
if (docRequest == null)
{
throw new NullReferenceException("There is not current PublishedContentRequest, it must be initialized before the RenderRouteHandler executes");
}
SetupRouteDataForRequest(
new RenderModel(docRequest.PublishedContent, docRequest.Culture),
requestContext,
docRequest);
return GetHandlerForRoute(requestContext, docRequest);
}
#endregion
/// <summary>
/// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
/// </summary>
/// <param name="renderModel"></param>
/// <param name="requestContext"></param>
/// <param name="docRequest"></param>
internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
{
//put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
requestContext.RouteData.DataTokens.Add("umbraco", renderModel); //required for the RenderModelBinder and view engine
requestContext.RouteData.DataTokens.Add("umbraco-doc-request", docRequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add("umbraco-context", UmbracoContext); //required for UmbracoTemplatePage
}
private void UpdateRouteDataForRequest(RenderModel renderModel, RequestContext requestContext)
{
if (renderModel == null) throw new ArgumentNullException("renderModel");
if (requestContext == null) throw new ArgumentNullException("requestContext");
requestContext.RouteData.DataTokens["umbraco"] = renderModel;
// the rest should not change -- it's only the published content that has changed
}
/// <summary>
/// Checks the request and query strings to see if it matches the definition of having a Surface controller
/// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
private static PostedDataProxyInfo GetFormInfo(RequestContext requestContext)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
//if it is a POST/GET then a value must be in the request
if (requestContext.HttpContext.Request.QueryString["ufprt"].IsNullOrWhiteSpace()
&& requestContext.HttpContext.Request.Form["ufprt"].IsNullOrWhiteSpace())
{
return null;
}
string encodedVal;
switch (requestContext.HttpContext.Request.RequestType)
{
case "POST":
//get the value from the request.
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.Form["ufprt"];
break;
case "GET":
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.QueryString["ufprt"];
break;
default:
return null;
}
string decryptedString;
try
{
decryptedString = encodedVal.DecryptWithMachineKey();
}
catch (FormatException)
{
LogHelper.Warn<RenderRouteHandler>("A value was detected in the ufprt parameter but Umbraco could not decrypt the string");
return null;
}
var parsedQueryString = HttpUtility.ParseQueryString(decryptedString);
var decodedParts = new Dictionary<string, string>();
foreach (var key in parsedQueryString.AllKeys)
{
decodedParts[key] = parsedQueryString[key];
}
//validate all required keys exist
//the controller
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Controller))
return null;
//the action
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Action))
return null;
//the area
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Area))
return null;
foreach (var item in decodedParts.Where(x => new[] {
ReservedAdditionalKeys.Controller,
ReservedAdditionalKeys.Action,
ReservedAdditionalKeys.Area }.Contains(x.Key) == false))
{
// Populate route with additional values which aren't reserved values so they eventually to action parameters
requestContext.RouteData.Values[item.Key] = item.Value;
}
//return the proxy info without the surface id... could be a local controller.
return new PostedDataProxyInfo
{
ControllerName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
ActionName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
Area = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
};
}
/// <summary>
/// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that
/// the right DataTokens are set.
/// </summary>
/// <param name="requestContext"></param>
/// <param name="postedInfo"></param>
private IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (postedInfo == null) throw new ArgumentNullException("postedInfo");
//set the standard route values/tokens
requestContext.RouteData.Values["controller"] = postedInfo.ControllerName;
requestContext.RouteData.Values["action"] = postedInfo.ActionName;
IHttpHandler handler;
//get the route from the defined routes
using (RouteTable.Routes.GetReadLock())
{
Route surfaceRoute;
if (postedInfo.Area.IsNullOrWhiteSpace())
{
//find the controller in the route table without an area
var surfaceRoutes = RouteTable.Routes.OfType<Route>()
.Where(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
x.DataTokens.ContainsKey("area") == false).ToList();
// If more than one route is found, find one with a matching action
if (surfaceRoutes.Count() > 1)
{
surfaceRoute = surfaceRoutes.SingleOrDefault(x =>
x.Defaults["action"].ToString().InvariantEquals(postedInfo.ActionName));
}
else
{
surfaceRoute = surfaceRoutes.SingleOrDefault();
}
}
else
{
//find the controller in the route table with the specified area
surfaceRoute = RouteTable.Routes.OfType<Route>()
.SingleOrDefault(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
x.DataTokens.ContainsKey("area") &&
x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area));
}
if (surfaceRoute == null)
throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName);
//set the area if one is there.
if (surfaceRoute.DataTokens.ContainsKey("area"))
{
requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"];
}
//set the 'Namespaces' token so the controller factory knows where to look to construct it
if (surfaceRoute.DataTokens.ContainsKey("Namespaces"))
{
requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"];
}
handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext);
}
return handler;
}
/// <summary>
/// Returns a RouteDefinition object based on the current renderModel
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
/// <returns></returns>
internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");
var defaultControllerType = DefaultRenderMvcControllerResolver.Current.GetDefaultControllerType();
var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
//creates the default route definition which maps to the 'UmbracoController' controller
var def = new RouteDefinition
{
ControllerName = defaultControllerName,
ControllerType = defaultControllerType,
PublishedContentRequest = publishedContentRequest,
ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
HasHijackedRoute = false
};
//check that a template is defined), if it doesn't and there is a hijacked route it will just route
// to the index Action
if (publishedContentRequest.HasTemplate)
{
//the template Alias should always be already saved with a safe name.
//if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
// with the action name attribute.
var templateName = publishedContentRequest.TemplateAlias.Split('.')[0].ToSafeAlias();
def.ActionName = templateName;
}
//check if there's a custom controller assigned, base on the document type alias.
var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias);
//check if that controller exists
if (controllerType != null)
{
//ensure the controller is of type 'IRenderMvcController' and ControllerBase
if (TypeHelper.IsTypeAssignableFrom<IRenderMvcController>(controllerType)
&& TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType))
{
//set the controller and name to the custom one
def.ControllerType = controllerType;
def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
if (def.ControllerName != defaultControllerName)
{
def.HasHijackedRoute = true;
}
}
else
{
LogHelper.Warn<RenderRouteHandler>(
"The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.",
() => publishedContentRequest.PublishedContent.DocumentTypeAlias,
() => controllerType.FullName,
() => typeof(IRenderMvcController).FullName,
() => typeof(ControllerBase).FullName);
//we cannot route to this custom controller since it is not of the correct type so we'll continue with the defaults
// that have already been set above.
}
}
//store the route definition
requestContext.RouteData.DataTokens["umbraco-route-def"] = def;
return def;
}
internal IHttpHandler GetHandlerOnMissingTemplate(PublishedContentRequest pcr)
{
if (pcr == null) throw new ArgumentNullException("pcr");
// missing template, so we're in a 404 here
// so the content, if any, is a custom 404 page of some sort
if (!pcr.HasPublishedContent)
// means the builder could not find a proper document to handle 404
return new PublishedContentNotFoundHandler();
if (!pcr.HasTemplate)
// means the engine could find a proper document, but the document has no template
// at that point there isn't much we can do and there is no point returning
// to Mvc since Mvc can't do much
return new PublishedContentNotFoundHandler("In addition, no template exists to render the custom 404.");
// so we have a template, so we should have a rendering engine
if (pcr.RenderingEngine == RenderingEngine.WebForms) // back to webforms ?
return GetWebFormsHandler();
if (pcr.RenderingEngine != RenderingEngine.Mvc) // else ?
return new PublishedContentNotFoundHandler("In addition, no rendering engine exists to render the custom 404.");
return null;
}
/// <summary>
/// this will determine the controller and set the values in the route data
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");
var routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
//Need to check for a special case if there is form data being posted back to an Umbraco URL
var postedInfo = GetFormInfo(requestContext);
if (postedInfo != null)
{
return HandlePostedValues(requestContext, postedInfo);
}
//Now we can check if we are supposed to render WebForms when the route has not been hijacked
if (publishedContentRequest.RenderingEngine == RenderingEngine.WebForms
&& publishedContentRequest.HasTemplate
&& routeDef.HasHijackedRoute == false)
{
return GetWebFormsHandler();
}
//here we need to check if there is no hijacked route and no template assigned, if this is the case
//we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
if (!publishedContentRequest.HasTemplate && !routeDef.HasHijackedRoute)
{
publishedContentRequest.UpdateOnMissingTemplate(); // will go 404
// HandleHttpResponseStatus returns a value indicating that the request should
// not be processed any further, eg because it has been redirect. then, exit.
if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest))
return null;
var handler = GetHandlerOnMissingTemplate(publishedContentRequest);
// if it's not null it can be either the PublishedContentNotFoundHandler (no document was
// found to handle 404, or document with no template was found) or the WebForms handler
// (a document was found and its template is WebForms)
// if it's null it means that a document was found and its template is Mvc
// if we have a handler, return now
if (handler != null)
return handler;
// else we are running Mvc
// update the route data - because the PublishedContent has changed
UpdateRouteDataForRequest(
new RenderModel(publishedContentRequest.PublishedContent, publishedContentRequest.Culture),
requestContext);
// update the route definition
routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
}
//no post values, just route to the controller/action requried (local)
requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
if (!string.IsNullOrWhiteSpace(routeDef.ActionName))
{
requestContext.RouteData.Values["action"] = routeDef.ActionName;
}
// Set the session state requirements
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));
// reset the friendly path so in the controllers and anything occuring after this point in time,
//the URL is reset back to the original request.
requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);
return new UmbracoMvcHandler(requestContext);
}
/// <summary>
/// Returns the handler for webforms requests
/// </summary>
/// <returns></returns>
internal static IHttpHandler GetWebFormsHandler()
{
return (global::umbraco.UmbracoDefault)BuildManager.CreateInstanceFromVirtualPath("~/default.aspx", typeof(global::umbraco.UmbracoDefault));
}
private SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext, string controllerName)
{
return _controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlSchemaExporter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
/// <include file='doc\XmlSchemaExporter.uex' path='docs/doc[@for="XmlSchemaExporter"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSchemaExporter {
internal const XmlSchemaForm elementFormDefault = XmlSchemaForm.Qualified;
internal const XmlSchemaForm attributeFormDefault = XmlSchemaForm.Unqualified;
XmlSchemas schemas;
Hashtable elements = new Hashtable(); // ElementAccessor -> XmlSchemaElement
Hashtable attributes = new Hashtable(); // AttributeAccessor -> XmlSchemaElement
Hashtable types = new Hashtable(); // StructMapping/EnumMapping -> XmlSchemaComplexType/XmlSchemaSimpleType
Hashtable references = new Hashtable(); // TypeMappings to keep track of circular references via anonymous types
bool needToExportRoot;
TypeScope scope;
/// <include file='doc\XmlSchemaExporter.uex' path='docs/doc[@for="XmlSchemaExporter.XmlSchemaExporter"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSchemaExporter(XmlSchemas schemas) {
this.schemas = schemas;
}
/// <include file='doc\XmlSchemaExporter.uex' path='docs/doc[@for="XmlSchemaExporter.ExportTypeMapping"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void ExportTypeMapping(XmlTypeMapping xmlTypeMapping) {
xmlTypeMapping.CheckShallow();
CheckScope(xmlTypeMapping.Scope);
ExportElement(xmlTypeMapping.Accessor);
ExportRootIfNecessary(xmlTypeMapping.Scope);
}
/// <include file='doc\XmlSchemaExporter.uex' path='docs/doc[@for="XmlSchemaExporter.ExportTypeMapping1"]/*' />
public XmlQualifiedName ExportTypeMapping(XmlMembersMapping xmlMembersMapping) {
xmlMembersMapping.CheckShallow();
CheckScope(xmlMembersMapping.Scope);
MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping;
if (mapping.Members.Length == 1 && mapping.Members[0].Elements[0].Mapping is SpecialMapping) {
SpecialMapping special = (SpecialMapping)mapping.Members[0].Elements[0].Mapping;
XmlSchemaType type = ExportSpecialMapping(special, xmlMembersMapping.Accessor.Namespace, false, null);
if (type != null && type.Name != null && type.Name.Length > 0) {
type.Name = xmlMembersMapping.Accessor.Name;
AddSchemaItem(type, xmlMembersMapping.Accessor.Namespace, null);
}
ExportRootIfNecessary(xmlMembersMapping.Scope);
return (new XmlQualifiedName(xmlMembersMapping.Accessor.Name, xmlMembersMapping.Accessor.Namespace));
}
return null;
}
/// <include file='doc\XmlSchemaExporter.uex' path='docs/doc[@for="XmlSchemaExporter.ExportMembersMapping"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping) {
ExportMembersMapping(xmlMembersMapping, true);
}
/// <include file='doc\XmlSchemaExporter.uex' path='docs/doc[@for="XmlSchemaExporter.ExportMembersMapping1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool exportEnclosingType) {
xmlMembersMapping.CheckShallow();
MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping;
CheckScope(xmlMembersMapping.Scope);
if (mapping.HasWrapperElement && exportEnclosingType) {
ExportElement(xmlMembersMapping.Accessor);
}
else {
foreach (MemberMapping member in mapping.Members) {
if (member.Attribute != null)
throw new InvalidOperationException(Res.GetString(Res.XmlBareAttributeMember, member.Attribute.Name));
else if (member.Text != null)
throw new InvalidOperationException(Res.GetString(Res.XmlBareTextMember, member.Text.Name));
else if (member.Elements == null || member.Elements.Length == 0)
continue;
if (member.TypeDesc.IsArrayLike && !(member.Elements[0].Mapping is ArrayMapping))
throw new InvalidOperationException(Res.GetString(Res.XmlIllegalArrayElement, member.Elements[0].Name));
if (exportEnclosingType) {
ExportElement(member.Elements[0]);
}
else {
ExportMapping(member.Elements[0].Mapping, member.Elements[0].Namespace, member.Elements[0].Any);
}
}
}
ExportRootIfNecessary(xmlMembersMapping.Scope);
}
private static XmlSchemaType FindSchemaType(string name, XmlSchemaObjectCollection items) {
// Have to loop through the items because schema.SchemaTypes has not been populated yet.
foreach (object o in items) {
XmlSchemaType type = o as XmlSchemaType;
if (type == null)
continue;
if (type.Name == name)
return type;
}
return null;
}
private static bool IsAnyType(XmlSchemaType schemaType, bool mixed, bool unbounded) {
XmlSchemaComplexType complexType = schemaType as XmlSchemaComplexType;
if (complexType != null) {
if (complexType.IsMixed != mixed)
return false;
if (complexType.Particle is XmlSchemaSequence) {
XmlSchemaSequence sequence = (XmlSchemaSequence) complexType.Particle;
if (sequence.Items.Count == 1 && sequence.Items[0] is XmlSchemaAny) {
XmlSchemaAny any = (XmlSchemaAny)sequence.Items[0];
return (unbounded == any.IsMultipleOccurrence);
}
}
}
return false;
}
/// <include file='doc\XmlSchemaExporter.uex' path='docs/doc[@for="XmlSchemaExporter.ExportAnyType"]/*' />
public string ExportAnyType(string ns) {
string name = "any";
int i = 0;
XmlSchema schema = schemas[ns];
if (schema != null) {
while (true) {
XmlSchemaType schemaType = FindSchemaType(name, schema.Items);
if (schemaType == null)
break;
if (IsAnyType(schemaType, true, true))
return name;
i++;
name = "any" + i.ToString(CultureInfo.InvariantCulture);
}
}
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.Name = name;
type.IsMixed = true;
XmlSchemaSequence seq = new XmlSchemaSequence();
XmlSchemaAny any = new XmlSchemaAny();
any.MinOccurs = 0;
any.MaxOccurs = decimal.MaxValue;
seq.Items.Add(any);
type.Particle = seq;
AddSchemaItem(type, ns, null);
return name;
}
/// <include file='doc\XmlSchemaExporter.uex' path='docs/doc[@for="XmlSchemaExporter.ExportAnyType1"]/*' />
public string ExportAnyType(XmlMembersMapping members) {
if (members.Count == 1 && members[0].Any && members[0].ElementName.Length == 0) {
XmlMemberMapping member = members[0];
string ns = member.Namespace;
bool isUnbounded = member.Mapping.TypeDesc.IsArrayLike;
bool isMixed = isUnbounded && member.Mapping.TypeDesc.ArrayElementTypeDesc != null ? member.Mapping.TypeDesc.ArrayElementTypeDesc.IsMixed : member.Mapping.TypeDesc.IsMixed;
if (isMixed && member.Mapping.TypeDesc.IsMixed)
// special case of the single top-level XmlNode --> map it to node array to match the "mixed" any type for backward compatibility
isUnbounded = true;
// generate type name, make sure that it is backward compatible
string baseName = isMixed ? "any" : isUnbounded ? "anyElements" : "anyElement";
string name = baseName;
int i = 0;
XmlSchema schema = schemas[ns];
if (schema != null) {
while (true) {
XmlSchemaType schemaType = FindSchemaType(name, schema.Items);
if (schemaType == null)
break;
if (IsAnyType(schemaType, isMixed, isUnbounded))
return name;
i++;
name = baseName + i.ToString(CultureInfo.InvariantCulture);
}
}
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.Name = name;
type.IsMixed = isMixed;
XmlSchemaSequence seq = new XmlSchemaSequence();
XmlSchemaAny any = new XmlSchemaAny();
any.MinOccurs = 0;
if (isUnbounded)
any.MaxOccurs = decimal.MaxValue;
seq.Items.Add(any);
type.Particle = seq;
AddSchemaItem(type, ns, null);
return name;
}
else {
return null;
}
}
void CheckScope(TypeScope scope) {
if (this.scope == null) {
this.scope = scope;
}
else if (this.scope != scope) {
throw new InvalidOperationException(Res.GetString(Res.XmlMappingsScopeMismatch));
}
}
XmlSchemaElement ExportElement(ElementAccessor accessor) {
if (!accessor.Mapping.IncludeInSchema && !accessor.Mapping.TypeDesc.IsRoot) {
return null;
}
if (accessor.Any && accessor.Name.Length == 0)
throw new InvalidOperationException(Res.GetString(Res.XmlIllegalWildcard));
XmlSchemaElement element = (XmlSchemaElement)elements[accessor];
if (element != null) return element;
element = new XmlSchemaElement();
element.Name = accessor.Name;
element.IsNillable = accessor.IsNullable;
elements.Add(accessor, element);
element.Form = accessor.Form;
AddSchemaItem(element, accessor.Namespace, null);
ExportElementMapping(element, accessor.Mapping, accessor.Namespace, accessor.Any);
return element;
}
void CheckForDuplicateType(TypeMapping mapping, string newNamespace) {
if (mapping.IsAnonymousType)
return;
string newTypeName = mapping.TypeName;
XmlSchema schema = schemas[newNamespace];
if (schema != null){
foreach (XmlSchemaObject o in schema.Items) {
XmlSchemaType type = o as XmlSchemaType;
if ( type != null && type.Name == newTypeName)
throw new InvalidOperationException(Res.GetString(Res.XmlDuplicateTypeName, newTypeName, newNamespace));
}
}
}
XmlSchema AddSchema(string targetNamespace) {
XmlSchema schema = new XmlSchema();
schema.TargetNamespace = string.IsNullOrEmpty(targetNamespace) ? null : targetNamespace;
#pragma warning disable 429 // Unreachable code: the default values are constant, so will never be Unqualified
schema.ElementFormDefault = elementFormDefault == XmlSchemaForm.Unqualified ? XmlSchemaForm.None : elementFormDefault;
schema.AttributeFormDefault = attributeFormDefault == XmlSchemaForm.Unqualified ? XmlSchemaForm.None : attributeFormDefault;
#pragma warning restore 429
schemas.Add(schema);
return schema;
}
void AddSchemaItem(XmlSchemaObject item, string ns, string referencingNs) {
XmlSchema schema = schemas[ns];
if (schema == null) {
schema = AddSchema(ns);
}
if (item is XmlSchemaElement) {
XmlSchemaElement e = (XmlSchemaElement)item;
if (e.Form == XmlSchemaForm.Unqualified)
throw new InvalidOperationException(Res.GetString(Res.XmlIllegalForm, e.Name));
e.Form = XmlSchemaForm.None;
}
else if (item is XmlSchemaAttribute) {
XmlSchemaAttribute a = (XmlSchemaAttribute)item;
if (a.Form == XmlSchemaForm.Unqualified)
throw new InvalidOperationException(Res.GetString(Res.XmlIllegalForm, a.Name));
a.Form = XmlSchemaForm.None;
}
schema.Items.Add(item);
AddSchemaImport(ns, referencingNs);
}
void AddSchemaImport(string ns, string referencingNs) {
if (referencingNs == null) return;
if (NamespacesEqual(ns, referencingNs)) return;
XmlSchema schema = schemas[referencingNs];
if (schema == null) {
schema = AddSchema(referencingNs);
}
if (FindImport(schema, ns) == null) {
XmlSchemaImport import = new XmlSchemaImport();
if (ns != null && ns.Length > 0)
import.Namespace = ns;
schema.Includes.Add(import);
}
}
static bool NamespacesEqual(string ns1, string ns2)
{
if (ns1 == null || ns1.Length == 0)
return (ns2 == null || ns2.Length == 0);
else
return ns1 == ns2;
}
bool SchemaContainsItem(XmlSchemaObject item, string ns) {
XmlSchema schema = schemas[ns];
if (schema != null) {
return schema.Items.Contains(item);
}
return false;
}
XmlSchemaImport FindImport(XmlSchema schema, string ns) {
foreach (object item in schema.Includes) {
if (item is XmlSchemaImport) {
XmlSchemaImport import = (XmlSchemaImport)item;
if (NamespacesEqual(import.Namespace, ns)) {
return import;
}
}
}
return null;
}
void ExportMapping(Mapping mapping, string ns, bool isAny) {
if (mapping is ArrayMapping)
ExportArrayMapping((ArrayMapping)mapping, ns, null);
else if (mapping is PrimitiveMapping) {
ExportPrimitiveMapping((PrimitiveMapping)mapping, ns);
}
else if (mapping is StructMapping)
ExportStructMapping((StructMapping)mapping, ns, null);
else if (mapping is MembersMapping)
ExportMembersMapping((MembersMapping)mapping, ns);
else if (mapping is SpecialMapping)
ExportSpecialMapping((SpecialMapping)mapping, ns, isAny, null);
else if (mapping is NullableMapping)
ExportMapping(((NullableMapping)mapping).BaseMapping, ns, isAny);
else
throw new ArgumentException(Res.GetString(Res.XmlInternalError), "mapping");
}
void ExportElementMapping(XmlSchemaElement element, Mapping mapping, string ns, bool isAny) {
if (mapping is ArrayMapping)
ExportArrayMapping((ArrayMapping)mapping, ns, element);
else if (mapping is PrimitiveMapping) {
PrimitiveMapping pm = (PrimitiveMapping)mapping;
if (pm.IsAnonymousType) {
element.SchemaType = ExportAnonymousPrimitiveMapping(pm);
}
else {
element.SchemaTypeName = ExportPrimitiveMapping(pm, ns);
}
}
else if (mapping is StructMapping) {
ExportStructMapping((StructMapping)mapping, ns, element);
}
else if (mapping is MembersMapping)
element.SchemaType = ExportMembersMapping((MembersMapping)mapping, ns);
else if (mapping is SpecialMapping)
ExportSpecialMapping((SpecialMapping)mapping, ns, isAny, element);
else if (mapping is NullableMapping) {
ExportElementMapping(element, ((NullableMapping)mapping).BaseMapping, ns, isAny);
}
else
throw new ArgumentException(Res.GetString(Res.XmlInternalError), "mapping");
}
XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, string ns) {
XmlSchemaSimpleType type = (XmlSchemaSimpleType)mapping.TypeDesc.DataType;
if (!SchemaContainsItem(type, UrtTypes.Namespace)) {
AddSchemaItem(type, UrtTypes.Namespace, ns);
}
else {
AddSchemaImport(mapping.Namespace, ns);
}
return new XmlQualifiedName(mapping.TypeDesc.DataType.Name, UrtTypes.Namespace);
}
XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bool isAny, XmlSchemaElement element) {
switch (mapping.TypeDesc.Kind) {
case TypeKind.Node: {
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.IsMixed = mapping.TypeDesc.IsMixed;
XmlSchemaSequence seq = new XmlSchemaSequence();
XmlSchemaAny any = new XmlSchemaAny();
if (isAny) {
type.AnyAttribute = new XmlSchemaAnyAttribute();
type.IsMixed = true;
any.MaxOccurs = decimal.MaxValue;
}
seq.Items.Add(any);
type.Particle = seq;
if (element != null)
element.SchemaType = type;
return type;
}
case TypeKind.Serializable: {
SerializableMapping serializableMapping = (SerializableMapping)mapping;
if (serializableMapping.IsAny) {
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.IsMixed = mapping.TypeDesc.IsMixed;
XmlSchemaSequence seq = new XmlSchemaSequence();
XmlSchemaAny any = new XmlSchemaAny();
if (isAny) {
type.AnyAttribute = new XmlSchemaAnyAttribute();
type.IsMixed = true;
any.MaxOccurs = decimal.MaxValue;
}
if (serializableMapping.NamespaceList.Length > 0)
any.Namespace = serializableMapping.NamespaceList;
any.ProcessContents = XmlSchemaContentProcessing.Lax;
if (serializableMapping.Schemas != null) {
foreach (XmlSchema schema in serializableMapping.Schemas.Schemas()) {
if (schema.TargetNamespace != XmlSchema.Namespace) {
schemas.Add(schema, true);
AddSchemaImport(schema.TargetNamespace, ns);
}
}
}
seq.Items.Add(any);
type.Particle = seq;
if (element != null)
element.SchemaType = type;
return type;
}
else if (serializableMapping.XsiType != null || serializableMapping.XsdType != null) {
XmlSchemaType type = serializableMapping.XsdType;
// for performance reasons we need to postpone merging of the serializable schemas
foreach (XmlSchema schema in serializableMapping.Schemas.Schemas()) {
if (schema.TargetNamespace != XmlSchema.Namespace) {
schemas.Add(schema, true);
AddSchemaImport(schema.TargetNamespace, ns);
if (!serializableMapping.XsiType.IsEmpty && serializableMapping.XsiType.Namespace == schema.TargetNamespace)
type = (XmlSchemaType)schema.SchemaTypes[serializableMapping.XsiType];
}
}
if (element != null) {
element.SchemaTypeName = serializableMapping.XsiType;
if (element.SchemaTypeName.IsEmpty)
element.SchemaType = type;
}
// check for duplicate top-level elements XmlAttributes
serializableMapping.CheckDuplicateElement(element, ns);
return type;
}
else if (serializableMapping.Schema != null) {
// this is the strongly-typed DataSet
XmlSchemaComplexType type = new XmlSchemaComplexType();
XmlSchemaAny any = new XmlSchemaAny();
XmlSchemaSequence seq = new XmlSchemaSequence();
seq.Items.Add(any);
type.Particle = seq;
string anyNs = serializableMapping.Schema.TargetNamespace;
any.Namespace = anyNs == null ? "" : anyNs;
XmlSchema existingSchema = schemas[anyNs];
if (existingSchema == null) {
schemas.Add(serializableMapping.Schema);
}
else if (existingSchema != serializableMapping.Schema) {
throw new InvalidOperationException(Res.GetString(Res.XmlDuplicateNamespace, anyNs));
}
if (element != null)
element.SchemaType = type;
// check for duplicate top-level elements XmlAttributes
serializableMapping.CheckDuplicateElement(element, ns);
return type;
}
else {
// DataSet
XmlSchemaComplexType type = new XmlSchemaComplexType();
XmlSchemaElement schemaElement = new XmlSchemaElement();
schemaElement.RefName = new XmlQualifiedName("schema", XmlSchema.Namespace);
XmlSchemaSequence seq = new XmlSchemaSequence();
seq.Items.Add(schemaElement);
seq.Items.Add(new XmlSchemaAny());
type.Particle = seq;
AddSchemaImport(XmlSchema.Namespace, ns);
if (element != null)
element.SchemaType = type;
return type;
}
}
default:
throw new ArgumentException(Res.GetString(Res.XmlInternalError), "mapping");
}
}
XmlSchemaType ExportMembersMapping(MembersMapping mapping, string ns) {
XmlSchemaComplexType type = new XmlSchemaComplexType();
ExportTypeMembers(type, mapping.Members, mapping.TypeName, ns, false, false);
if (mapping.XmlnsMember != null) {
AddXmlnsAnnotation(type, mapping.XmlnsMember.Name);
}
return type;
}
XmlSchemaType ExportAnonymousPrimitiveMapping(PrimitiveMapping mapping) {
if (mapping is EnumMapping) {
return ExportEnumMapping((EnumMapping)mapping, null);
}
else {
throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Unsuported anonymous mapping type: " + mapping.ToString()));
}
}
XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string ns) {
XmlQualifiedName qname;
if (mapping is EnumMapping) {
XmlSchemaType type = ExportEnumMapping((EnumMapping)mapping, ns);
qname = new XmlQualifiedName(type.Name, mapping.Namespace);
}
else {
if (mapping.TypeDesc.IsXsdType) {
qname = new XmlQualifiedName(mapping.TypeDesc.DataType.Name, XmlSchema.Namespace);
}
else {
qname = ExportNonXsdPrimitiveMapping(mapping, ns);
}
}
return qname;
}
void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElement element) {
// some of the items in the linked list differ only by CLR type. We don't need to
// export different schema types for these. Look further down the list for another
// entry with the same elements. If there is one, it will be exported later so
// just return its name now.
ArrayMapping currentMapping = mapping;
while (currentMapping.Next != null) {
currentMapping = currentMapping.Next;
}
XmlSchemaComplexType type = (XmlSchemaComplexType) types[currentMapping];
if (type == null) {
CheckForDuplicateType(currentMapping, currentMapping.Namespace);
type = new XmlSchemaComplexType();
if (!mapping.IsAnonymousType) {
type.Name = mapping.TypeName;
AddSchemaItem(type, mapping.Namespace, ns);
}
if (!currentMapping.IsAnonymousType)
types.Add(currentMapping, type);
XmlSchemaSequence seq = new XmlSchemaSequence();
ExportElementAccessors(seq, mapping.Elements, true, false, mapping.Namespace);
if (seq.Items.Count > 0) {
#if DEBUG
// we can have only one item for the array mapping
if (seq.Items.Count != 1)
throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Type " + mapping.TypeName + " from namespace '" + ns + "' is an invalid array mapping"));
#endif
if (seq.Items[0] is XmlSchemaChoice) {
type.Particle = (XmlSchemaChoice)seq.Items[0];
}
else {
type.Particle = seq;
}
}
}
else {
AddSchemaImport(mapping.Namespace, ns);
}
if (element != null) {
if (mapping.IsAnonymousType) {
element.SchemaType = type;
}
else {
element.SchemaTypeName = new XmlQualifiedName(type.Name, mapping.Namespace);
}
}
}
void ExportElementAccessors(XmlSchemaGroupBase group, ElementAccessor[] accessors, bool repeats, bool valueTypeOptional, string ns) {
if (accessors.Length == 0) return;
if (accessors.Length == 1) {
ExportElementAccessor(group, accessors[0], repeats, valueTypeOptional, ns);
}
else {
XmlSchemaChoice choice = new XmlSchemaChoice();
choice.MaxOccurs = repeats ? decimal.MaxValue : 1;
choice.MinOccurs = repeats ? 0 : 1;
for (int i = 0; i < accessors.Length; i++)
ExportElementAccessor(choice, accessors[i], false, valueTypeOptional, ns);
if (choice.Items.Count > 0) group.Items.Add(choice);
}
}
void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccessor accessor, bool valueTypeOptional, string ns) {
if (accessor == null) return;
XmlSchemaObjectCollection attributes;
if (type.ContentModel != null) {
if (type.ContentModel.Content is XmlSchemaComplexContentRestriction)
attributes = ((XmlSchemaComplexContentRestriction)type.ContentModel.Content).Attributes;
else if (type.ContentModel.Content is XmlSchemaComplexContentExtension)
attributes = ((XmlSchemaComplexContentExtension)type.ContentModel.Content).Attributes;
else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension)
attributes = ((XmlSchemaSimpleContentExtension)type.ContentModel.Content).Attributes;
else
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidContent, type.ContentModel.Content.GetType().Name));
}
else {
attributes = type.Attributes;
}
if (accessor.IsSpecialXmlNamespace) {
// add <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
AddSchemaImport(XmlReservedNs.NsXml, ns);
// generate <xsd:attribute ref="xml:lang" use="optional" />
XmlSchemaAttribute attribute = new XmlSchemaAttribute();
attribute.Use = XmlSchemaUse.Optional;
attribute.RefName = new XmlQualifiedName(accessor.Name, XmlReservedNs.NsXml);
attributes.Add(attribute);
}
else if (accessor.Any) {
if (type.ContentModel == null) {
type.AnyAttribute = new XmlSchemaAnyAttribute();
}
else {
XmlSchemaContent content = type.ContentModel.Content;
if (content is XmlSchemaComplexContentExtension) {
XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content;
extension.AnyAttribute = new XmlSchemaAnyAttribute();
}
else if (content is XmlSchemaComplexContentRestriction) {
XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)content;
restriction.AnyAttribute = new XmlSchemaAnyAttribute();
}
else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension) {
XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content;
extension.AnyAttribute = new XmlSchemaAnyAttribute();
}
}
}
else {
XmlSchemaAttribute attribute = new XmlSchemaAttribute();
attribute.Use = XmlSchemaUse.None;
if (!accessor.HasDefault && !valueTypeOptional && accessor.Mapping.TypeDesc.IsValueType) {
attribute.Use = XmlSchemaUse.Required;
}
attribute.Name = accessor.Name;
if (accessor.Namespace == null || accessor.Namespace == ns) {
// determine the form attribute value
XmlSchema schema = schemas[ns];
if (schema == null)
attribute.Form = accessor.Form == attributeFormDefault ? XmlSchemaForm.None : accessor.Form;
else {
attribute.Form = accessor.Form == schema.AttributeFormDefault ? XmlSchemaForm.None : accessor.Form;
}
attributes.Add(attribute);
}
else {
// we are going to add the attribute to the top-level items. "use" attribute should not be set
if (this.attributes[accessor] == null) {
attribute.Use = XmlSchemaUse.None;
attribute.Form = accessor.Form;
AddSchemaItem(attribute, accessor.Namespace, ns);
this.attributes.Add(accessor, accessor);
}
XmlSchemaAttribute refAttribute = new XmlSchemaAttribute();
refAttribute.Use = XmlSchemaUse.None;
refAttribute.RefName = new XmlQualifiedName(accessor.Name, accessor.Namespace);
attributes.Add(refAttribute);
AddSchemaImport(accessor.Namespace, ns);
}
if (accessor.Mapping is PrimitiveMapping) {
PrimitiveMapping pm = (PrimitiveMapping)accessor.Mapping;
if (pm.IsList) {
// create local simple type for the list-like attributes
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList();
if (pm.IsAnonymousType) {
list.ItemType = (XmlSchemaSimpleType)ExportAnonymousPrimitiveMapping(pm);
}
else {
list.ItemTypeName = ExportPrimitiveMapping(pm, accessor.Namespace == null ? ns : accessor.Namespace);
}
dataType.Content = list;
attribute.SchemaType = dataType;
}
else {
if (pm.IsAnonymousType) {
attribute.SchemaType = (XmlSchemaSimpleType)ExportAnonymousPrimitiveMapping(pm);
}
else {
attribute.SchemaTypeName = ExportPrimitiveMapping(pm, accessor.Namespace == null ? ns : accessor.Namespace);
}
}
}
else if (!(accessor.Mapping is SpecialMapping))
throw new InvalidOperationException(Res.GetString(Res.XmlInternalError));
if (accessor.HasDefault) {
attribute.DefaultValue = ExportDefaultValue(accessor.Mapping, accessor.Default);
}
}
}
void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor accessor, bool repeats, bool valueTypeOptional, string ns) {
if (accessor.Any && accessor.Name.Length == 0) {
XmlSchemaAny any = new XmlSchemaAny();
any.MinOccurs = 0;
any.MaxOccurs = repeats ? decimal.MaxValue : 1;
if (accessor.Namespace != null && accessor.Namespace.Length > 0 && accessor.Namespace != ns)
any.Namespace = accessor.Namespace;
group.Items.Add(any);
}
else {
XmlSchemaElement element = (XmlSchemaElement)elements[accessor];
int minOccurs = repeats || accessor.HasDefault || (!accessor.IsNullable && !accessor.Mapping.TypeDesc.IsValueType) || valueTypeOptional ? 0 : 1;
decimal maxOccurs = repeats || accessor.IsUnbounded ? decimal.MaxValue : 1;
if (element == null) {
element = new XmlSchemaElement();
element.IsNillable = accessor.IsNullable;
element.Name = accessor.Name;
if (accessor.HasDefault)
element.DefaultValue = ExportDefaultValue(accessor.Mapping, accessor.Default);
if (accessor.IsTopLevelInSchema) {
elements.Add(accessor, element);
element.Form = accessor.Form;
AddSchemaItem(element, accessor.Namespace, ns);
}
else {
element.MinOccurs = minOccurs;
element.MaxOccurs = maxOccurs;
// determine the form attribute value
XmlSchema schema = schemas[ns];
if (schema == null)
element.Form = accessor.Form == elementFormDefault ? XmlSchemaForm.None : accessor.Form;
else {
element.Form = accessor.Form == schema.ElementFormDefault ? XmlSchemaForm.None : accessor.Form;
}
}
ExportElementMapping(element, (TypeMapping)accessor.Mapping, accessor.Namespace, accessor.Any);
}
if (accessor.IsTopLevelInSchema) {
XmlSchemaElement refElement = new XmlSchemaElement();
refElement.RefName = new XmlQualifiedName(accessor.Name, accessor.Namespace);
refElement.MinOccurs = minOccurs;
refElement.MaxOccurs = maxOccurs;
group.Items.Add(refElement);
AddSchemaImport(accessor.Namespace, ns);
}
else {
group.Items.Add(element);
}
}
}
static internal string ExportDefaultValue(TypeMapping mapping, object value) {
if (!(mapping is PrimitiveMapping))
// should throw, but it will be a breaking change;
return null;
if (value == null || value == DBNull.Value)
return null;
if (mapping is EnumMapping) {
EnumMapping em = (EnumMapping)mapping;
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (value.GetType() != typeof(string)) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), value.GetType().FullName)));
#endif
// check the validity of the value
ConstantMapping[] c = em.Constants;
if (em.IsFlags) {
string[] names = new string[c.Length];
long[] ids = new long[c.Length];
Hashtable values = new Hashtable();
for (int i = 0; i < c.Length; i++) {
names[i] = c[i].XmlName;
ids[i] = 1 << i;
values.Add(c[i].Name, ids[i]);
}
long val = XmlCustomFormatter.ToEnum((string)value, values, em.TypeName, false);
return val != 0 ? XmlCustomFormatter.FromEnum(val, names, ids, mapping.TypeDesc.FullName) : null;
}
else {
for (int i = 0; i < c.Length; i++) {
if (c[i].Name == (string)value) {
return c[i].XmlName;
}
}
return null; // unknown value
}
}
PrimitiveMapping pm = (PrimitiveMapping)mapping;
if (!pm.TypeDesc.HasCustomFormatter) {
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (pm.TypeDesc.Type == null) {
throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Mapping for " + pm.TypeDesc.Name + " missing type property"));
}
#endif
if (pm.TypeDesc.FormatterName == "String")
return (string)value;
Type formatter = typeof(XmlConvert);
System.Reflection.MethodInfo format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type });
if (format != null)
return (string)format.Invoke(formatter, new Object[] {value});
}
else {
string defaultValue = XmlCustomFormatter.FromDefaultValue(value, pm.TypeDesc.FormatterName);
if (defaultValue == null)
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), pm.TypeDesc.Name));
return defaultValue;
}
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), pm.TypeDesc.Name));
}
void ExportRootIfNecessary(TypeScope typeScope) {
if (!needToExportRoot)
return;
foreach (TypeMapping mapping in typeScope.TypeMappings) {
if (mapping is StructMapping && mapping.TypeDesc.IsRoot) {
ExportDerivedMappings((StructMapping) mapping);
}
else if (mapping is ArrayMapping) {
ExportArrayMapping((ArrayMapping) mapping, mapping.Namespace, null);
}
else if (mapping is SerializableMapping) {
ExportSpecialMapping((SerializableMapping)mapping, mapping.Namespace, false, null);
}
}
}
XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, XmlSchemaElement element) {
if (mapping.TypeDesc.IsRoot) {
needToExportRoot = true;
return XmlQualifiedName.Empty;
}
if (mapping.IsAnonymousType) {
if (references[mapping] != null)
throw new InvalidOperationException(Res.GetString(Res.XmlCircularReference2, mapping.TypeDesc.Name, "AnonymousType", "false"));
references[mapping] = mapping;
}
XmlSchemaComplexType type = (XmlSchemaComplexType)types[mapping];
if (type == null) {
if (!mapping.IncludeInSchema) throw new InvalidOperationException(Res.GetString(Res.XmlCannotIncludeInSchema, mapping.TypeDesc.Name));
CheckForDuplicateType(mapping, mapping.Namespace);
type = new XmlSchemaComplexType();
if (!mapping.IsAnonymousType) {
type.Name = mapping.TypeName;
AddSchemaItem(type, mapping.Namespace, ns);
types.Add(mapping, type);
}
type.IsAbstract = mapping.TypeDesc.IsAbstract;
bool openModel = mapping.IsOpenModel;
if (mapping.BaseMapping != null && mapping.BaseMapping.IncludeInSchema) {
if (mapping.BaseMapping.IsAnonymousType) {
throw new InvalidOperationException(Res.GetString(Res.XmlAnonymousBaseType, mapping.TypeDesc.Name, mapping.BaseMapping.TypeDesc.Name, "AnonymousType", "false"));
}
if (mapping.HasSimpleContent) {
XmlSchemaSimpleContent model = new XmlSchemaSimpleContent();
XmlSchemaSimpleContentExtension extension = new XmlSchemaSimpleContentExtension();
extension.BaseTypeName = ExportStructMapping(mapping.BaseMapping, mapping.Namespace, null);
model.Content = extension;
type.ContentModel = model;
}
else {
XmlSchemaComplexContentExtension extension = new XmlSchemaComplexContentExtension();
extension.BaseTypeName = ExportStructMapping(mapping.BaseMapping, mapping.Namespace, null);
XmlSchemaComplexContent model = new XmlSchemaComplexContent();
model.Content = extension;
model.IsMixed = XmlSchemaImporter.IsMixed((XmlSchemaComplexType)types[mapping.BaseMapping]);
type.ContentModel = model;
}
openModel = false;
}
ExportTypeMembers(type, mapping.Members, mapping.TypeName, mapping.Namespace, mapping.HasSimpleContent, openModel);
ExportDerivedMappings(mapping);
if (mapping.XmlnsMember != null) {
AddXmlnsAnnotation(type, mapping.XmlnsMember.Name);
}
}
else {
AddSchemaImport(mapping.Namespace, ns);
}
if (mapping.IsAnonymousType) {
references[mapping] = null;
if (element != null)
element.SchemaType = type;
return XmlQualifiedName.Empty;
}
else {
XmlQualifiedName qname = new XmlQualifiedName(type.Name, mapping.Namespace);
if (element != null) element.SchemaTypeName = qname;
return qname;
}
}
void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] members, string name, string ns, bool hasSimpleContent, bool openModel) {
XmlSchemaGroupBase seq = new XmlSchemaSequence();
TypeMapping textMapping = null;
for (int i = 0; i < members.Length; i++) {
MemberMapping member = members[i];
if (member.Ignore)
continue;
if (member.Text != null) {
if (textMapping != null) {
throw new InvalidOperationException(Res.GetString(Res.XmlIllegalMultipleText, name));
}
textMapping = member.Text.Mapping;
}
if (member.Elements.Length > 0) {
bool repeats = member.TypeDesc.IsArrayLike &&
!(member.Elements.Length == 1 && member.Elements[0].Mapping is ArrayMapping);
bool valueTypeOptional = member.CheckSpecified != SpecifiedAccessor.None || member.CheckShouldPersist;
ExportElementAccessors(seq, member.Elements, repeats, valueTypeOptional, ns);
}
}
if (seq.Items.Count > 0) {
if (type.ContentModel != null) {
if (type.ContentModel.Content is XmlSchemaComplexContentRestriction)
((XmlSchemaComplexContentRestriction)type.ContentModel.Content).Particle = seq;
else if (type.ContentModel.Content is XmlSchemaComplexContentExtension)
((XmlSchemaComplexContentExtension)type.ContentModel.Content).Particle = seq;
else
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidContent, type.ContentModel.Content.GetType().Name));
}
else {
type.Particle = seq;
}
}
if (textMapping != null) {
if (hasSimpleContent) {
if (textMapping is PrimitiveMapping && seq.Items.Count == 0) {
PrimitiveMapping pm = (PrimitiveMapping)textMapping;
if (pm.IsList) {
type.IsMixed = true;
}
else {
if (pm.IsAnonymousType) {
throw new InvalidOperationException(Res.GetString(Res.XmlAnonymousBaseType, textMapping.TypeDesc.Name, pm.TypeDesc.Name, "AnonymousType", "false"));
}
// Create simpleContent
XmlSchemaSimpleContent model = new XmlSchemaSimpleContent();
XmlSchemaSimpleContentExtension ex = new XmlSchemaSimpleContentExtension();
model.Content = ex;
type.ContentModel = model;
ex.BaseTypeName = ExportPrimitiveMapping(pm, ns);
}
}
}
else {
type.IsMixed = true;
}
}
bool anyAttribute = false;
for (int i = 0; i < members.Length; i++) {
AttributeAccessor accessor = members[i].Attribute;
if (accessor != null) {
ExportAttributeAccessor(type, members[i].Attribute, members[i].CheckSpecified != SpecifiedAccessor.None || members[i].CheckShouldPersist, ns);
if (members[i].Attribute.Any)
anyAttribute = true;
}
}
if (openModel && !anyAttribute) {
AttributeAccessor any = new AttributeAccessor();
any.Any = true;
ExportAttributeAccessor(type, any, false, ns);
}
}
void ExportDerivedMappings(StructMapping mapping) {
if (mapping.IsAnonymousType)
return;
for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) {
if (derived.IncludeInSchema) ExportStructMapping(derived, derived.Namespace, null);
}
}
XmlSchemaType ExportEnumMapping(EnumMapping mapping, string ns) {
if (!mapping.IncludeInSchema) throw new InvalidOperationException(Res.GetString(Res.XmlCannotIncludeInSchema, mapping.TypeDesc.Name));
XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)types[mapping];
if (dataType == null) {
CheckForDuplicateType(mapping, mapping.Namespace);
dataType = new XmlSchemaSimpleType();
dataType.Name = mapping.TypeName;
if (!mapping.IsAnonymousType) {
types.Add(mapping, dataType);
AddSchemaItem(dataType, mapping.Namespace, ns);
}
XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
restriction.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);
for (int i = 0; i < mapping.Constants.Length; i++) {
ConstantMapping constant = mapping.Constants[i];
XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet();
enumeration.Value = constant.XmlName;
restriction.Facets.Add(enumeration);
}
if (!mapping.IsFlags) {
dataType.Content = restriction;
}
else {
XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList();
XmlSchemaSimpleType enumType = new XmlSchemaSimpleType();
enumType.Content = restriction;
list.ItemType = enumType;
dataType.Content = list;
}
}
if (!mapping.IsAnonymousType) {
AddSchemaImport(mapping.Namespace, ns);
}
return dataType;
}
void AddXmlnsAnnotation(XmlSchemaComplexType type, string xmlnsMemberName) {
XmlSchemaAnnotation annotation = new XmlSchemaAnnotation();
XmlSchemaAppInfo appinfo = new XmlSchemaAppInfo();
XmlDocument d = new XmlDocument();
XmlElement e = d.CreateElement("keepNamespaceDeclarations");
if (xmlnsMemberName != null)
e.InsertBefore(d.CreateTextNode(xmlnsMemberName), null);
appinfo.Markup = new XmlNode[] {e};
annotation.Items.Add(appinfo);
type.Annotation = annotation;
}
}
}
| |
using System.ComponentModel;
using System.Data;
using System.Xml;
using Epi.Data;
namespace Epi.Fields
{
/// <summary>
/// Number Field.
/// </summary>
public class NumberField : InputTextBoxField, IPatternable
{
#region Private Members
private string pattern = string.Empty;
private string lower = string.Empty;
private string upper = string.Empty;
private XmlElement viewElement;
private XmlNode fieldNode;
private BackgroundWorker _updater;
private BackgroundWorker _inserter;
#endregion Private Members
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="page">The page this field belongs to</param>
public NumberField(Page page) : base(page)
{
Construct();
}
/// <summary>
/// NumberField
/// </summary>
/// <param name="page">Page</param>
/// <param name="viewElement">XML view element</param>
public NumberField(Page page, XmlElement viewElement)
: base(page)
{
this.viewElement = viewElement;
this.Page = page;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
public NumberField(View view) : base(view)
{
Construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
/// <param name="fieldNode">Xml Field Node</param>
public NumberField(View view, XmlNode fieldNode) : base(view)
{
Construct();
this.fieldNode = fieldNode;
this.view.Project.Metadata.GetFieldData(this, this.fieldNode);
}
/// <summary>
/// Load from row
/// </summary>
/// <param name="row">Row</param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
pattern = row[ColumnNames.PATTERN].ToString();
pattern = pattern == "None" ? "" : pattern;
lower = row[ColumnNames.LOWER].ToString();
upper = row[ColumnNames.UPPER].ToString();
}
public NumberField Clone()
{
NumberField clone = (NumberField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
private void Construct()
{
genericDbColumnType = GenericDbColumnType.Double;
this.dbColumnType = DbType.Double;
}
#endregion Constructors
#region Public Events
#endregion
#region Public Properties
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.Number;
}
}
public override string GetDbSpecificColumnType()
{
return GetProject().CollectedData.GetDatabase().GetDbSpecificColumnType(GenericDbColumnType.Double);
}
///// <summary>
///// Returns a fully-typed current record value
///// </summary>
//public Single CurrentRecordValue
//{
// get
// {
// if (base.CurrentRecordValueObject == null) return ;
// else return CurrentRecordValueObject.ToString();
// }
// set
// {
// base.CurrentRecordValueObject = value;
// }
//}
/// <summary>
/// Pattern
/// </summary>
public string Pattern
{
get
{
return (pattern);
}
set
{
pattern = value == "None" ? "" : value;
}
}
/// <summary>
/// Lower
/// </summary>
public string Lower
{
get
{
return (lower);
}
set
{
lower = value;
}
}
/// <summary>
/// Upper
/// </summary>
public string Upper
{
get
{
return (upper);
}
set
{
upper = value;
}
}
#endregion Public Properties
#region Public Methods
///// <summary>
///// Saves the current field location
///// </summary>
//public override void SaveFieldLocation()
//{
// Metadata.UpdateControlPosition(this);
// Metadata.UpdatePromptPosition(this);
//}
#endregion
#region Private Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
}
///// <summary>
///// Inserts the field to the database
///// </summary>
//protected override void InsertField()
//{
// insertStarted = true;
// _inserter = new BackgroundWorker();
// _inserter.DoWork += new DoWorkEventHandler(inserter_DoWork);
// _inserter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_inserter_RunWorkerCompleted);
// _inserter.RunWorkerAsync();
//}
//void _inserter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldInserted(this);
//}
//void inserter_DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// this.Id = GetMetadata().CreateField(this);
// base.OnFieldAdded();
// fieldsWaitingToUpdate--;
// }
//}
///// <summary>
///// Update the field to the database
///// </summary>
//protected override void UpdateField()
//{
// _updater = new BackgroundWorker();
// _updater.DoWork += new DoWorkEventHandler(DoWork);
// _updater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_updater_RunWorkerCompleted);
// _updater.RunWorkerAsync();
//}
//void _updater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldUpdated(this);
//}
//private void DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// GetMetadata().UpdateField(this);
// fieldsWaitingToUpdate--;
// }
//}
#endregion
#region Event Handlers
#endregion Event Handlers
/// <summary>
/// The view element of the field
/// </summary>
public XmlElement ViewElement
{
get
{
return viewElement;
}
set
{
viewElement = value;
}
}
}
}
| |
using EPiServer.Commerce.Catalog.ContentTypes;
using EPiServer.Commerce.Catalog.Linking;
using EPiServer.Commerce.SpecializedProperties;
using EPiServer.Core;
using EPiServer.Filters;
using EPiServer.Reference.Commerce.Site.Features.Global.Market.Services;
using EPiServer.Reference.Commerce.Site.Features.Global.Product.Controllers;
using EPiServer.Reference.Commerce.Site.Features.Global.Product.Models;
using EPiServer.Reference.Commerce.Site.Features.Global.Product.ViewModels;
using EPiServer.Reference.Commerce.Site.Features.Global.Shared.Services;
using EPiServer.Reference.Commerce.Site.Infrastructure.Facades;
using EPiServer.Web.Routing;
using FluentAssertions;
using Mediachase.Commerce;
using Mediachase.Commerce.Catalog;
using Mediachase.Commerce.Pricing;
using Moq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using EPiServer.Globalization;
using Xunit;
namespace EPiServer.Reference.Commerce.Site.Tests.Features.Product.Controllers
{
public class ProductControllerTests : IDisposable
{
[Fact]
public void Index_WhenVariationIdIsNull_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
SetRelation(fashionProduct, Enumerable.Empty<ProductVariation>());
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, null);
}
// Assert
{
Assert.IsType(typeof(HttpNotFoundResult), actionResult);
}
}
[Fact]
public void Index_WhenVariationIdIsEmpty_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
SetRelation(fashionProduct, Enumerable.Empty<ProductVariation>());
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, string.Empty);
}
// Assert
{
Assert.IsType(typeof(HttpNotFoundResult), actionResult);
}
}
[Fact]
public void Index_WhenNoVariationExists_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
SetRelation(fashionProduct, Enumerable.Empty<ProductVariation>());
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, "something");
}
// Assert
{
Assert.IsType(typeof(HttpNotFoundResult), actionResult);
}
}
[Fact]
public void Index_WhenSelectedVariationDontExist_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
var fashionVariant = CreateFashionVariant();
SetRelation(fashionProduct, fashionVariant);
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, "doNotExist");
}
// Assert
{
Assert.IsType(typeof(HttpNotFoundResult), actionResult);
}
}
[Fact]
public void Index_WhenSelectedVariationExist_ShouldSetVariationToSelectedVariation()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// setup
{
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
SetRelation(fashionProduct, fashionVariant);
productController = CreateController();
}
// execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<FashionVariant>(fashionVariant, model.Variation);
}
}
[Fact]
public void Index_WhenSelectedVariationExist_ShouldSetProductToRoutedProduct()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<FashionProduct>(fashionProduct, model.Product);
}
}
[Fact]
public void Index_WhenSelectedVariationExist_ShouldSetOriginalPriceToDefaultPrice()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
Mock<IPriceValue> mockDefaultPrice = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
SetRelation(fashionProduct, fashionVariant);
mockDefaultPrice = CreatePriceValueMock(25);
SetDefaultPriceService(mockDefaultPrice.Object);
var mockDiscountPrice = CreatePriceValueMock(20);
SetDiscountPriceService(mockDiscountPrice.Object);
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<Money>(mockDefaultPrice.Object.UnitPrice, model.ListingPrice);
}
}
[Fact]
public void Index_WhenSelectedVariationExist_ShouldSetPriceToDiscountPrice()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
Mock<IPriceValue> mockDiscountPrice = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
SetRelation(fashionProduct, fashionVariant);
var mockDefaultPrice = CreatePriceValueMock(25);
SetDefaultPriceService(mockDefaultPrice.Object);
mockDiscountPrice = CreatePriceValueMock(20);
SetDiscountPriceService(mockDiscountPrice.Object);
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<Money>(mockDiscountPrice.Object.UnitPrice, model.DiscountedPrice.Value);
}
}
[Fact]
public void Index_WhenSelectedVariationExist_ShouldSetColorToSelectedVariationColor()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
string color = null;
ActionResult actionResult = null;
// Setup
{
color = "green";
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
SetColor(fashionVariant, color);
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<string>(color, model.Color);
}
}
[Fact]
public void Index_WhenSelectedVariationExist_ShouldSetSizeToSelectedVariationSize()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
string size = null;
ActionResult actionResult = null;
// Setup
{
size = "small";
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
SetSize(fashionVariant, size);
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<string>(size, model.Size);
}
}
[Fact]
public void Index_WhenSelectedVariationDontHaveAssets_ShouldSetImagesToOneItemWithEmptyLink()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<string>(string.Empty, model.Images.Single());
}
}
[Fact]
public void Index_WhenSelectedVariationHasImageAssets_ShouldSetImagesToLinkFromImage()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
string imageLink = null;
ActionResult actionResult = null;
// Setup
{
imageLink = "http://www.episerver.com";
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
var imageMedia = CreateImageMedia(new ContentReference(237), imageLink);
SetMediaCollection(fashionVariant, imageMedia);
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<string>(imageLink, model.Images.Single());
}
}
[Fact]
public void Index_WhenAvailableColorsAreEmptyForVariation_ShouldSetColorsToEmpty()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant();
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
Assert.Equal<int>(0, model.Colors.Count());
}
}
[Fact]
public void Index_WhenAvailableColorsContainsItems_ShouldSetTextToItemValue()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant1 = null;
FashionVariant fashionVariant2 = null;
FashionVariant fashionVariant3 = null;
ProductController productController = null;
ItemCollection<string> colors = null;
ActionResult actionResult = null;
// Setup
{
colors = new ItemCollection<string>() { "green", "red" };
fashionProduct = CreateFashionProduct();
SetAvailableColors(fashionProduct, colors);
SetAvailableSizes(fashionProduct, new ItemCollection<string> { "small", "medium" });
fashionVariant1 = CreateFashionVariant("small", "green");
fashionVariant2 = CreateFashionVariant("medium", "red");
fashionVariant3 = CreateFashionVariant("medium", "green");
SetRelation(fashionProduct, new[] { fashionVariant1, fashionVariant2, fashionVariant3 });
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant1.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
var expectedColors = String.Join(";", colors);
var modelColorTexts = String.Join(";", model.Colors.Select(x => x.Text));
Assert.Equal<string>(expectedColors, modelColorTexts);
}
}
[Fact]
public void Index_WhenAvailableColorsContainsItems_ShouldSetValueToItemValue()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant1 = null;
FashionVariant fashionVariant2 = null;
FashionVariant fashionVariant3 = null;
ProductController productController = null;
ItemCollection<string> colors = null;
ActionResult actionResult = null;
// Setup
{
colors = new ItemCollection<string>() { "green", "red" };
fashionProduct = CreateFashionProduct();
SetAvailableColors(fashionProduct, colors);
SetAvailableSizes(fashionProduct, new ItemCollection<string> { "small", "medium" });
fashionVariant1 = CreateFashionVariant("small", "green");
fashionVariant2 = CreateFashionVariant("medium", "red");
fashionVariant3 = CreateFashionVariant("medium", "green");
SetRelation(fashionProduct, new[] { fashionVariant1, fashionVariant2, fashionVariant3 });
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant1.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
var expectedColors = String.Join(";", colors);
var modelColorValues = String.Join(";", model.Colors.Select(x => x.Value));
Assert.Equal<string>(expectedColors, modelColorValues);
}
}
[Fact]
public void Index_WhenAvailableColorsContainsItems_ShouldSetSelectedToFalse()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant1 = null;
FashionVariant fashionVariant2 = null;
FashionVariant fashionVariant3 = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
SetAvailableColors(fashionProduct, new ItemCollection<string>() { "green", "red" });
SetAvailableSizes(fashionProduct, new ItemCollection<string> { "small", "medium" });
fashionVariant1 = CreateFashionVariant("small", "green");
fashionVariant2 = CreateFashionVariant("medium", "red");
fashionVariant3 = CreateFashionVariant("medium", "green");
SetRelation(fashionProduct, new[] { fashionVariant1, fashionVariant2, fashionVariant3 });
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant1.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
var expectedColors = String.Join(";", new[] { false, false });
var modelColorsSelected = String.Join(";", model.Colors.Select(x => x.Selected));
Assert.Equal<string>(expectedColors, modelColorsSelected);
}
}
[Fact]
public void Index_WhenAvailableSizesContainsItems_ShouldSetTextToItemValue()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ItemCollection<string> sizes = null;
ActionResult actionResult = null;
// Setup
{
sizes = new ItemCollection<string>() { "medium" };
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant("medium", "red");
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
var expectedSizes = String.Join(";", sizes);
var modelSizeTexts = String.Join(";", model.Sizes.Select(x => x.Text));
Assert.Equal<string>(expectedSizes, modelSizeTexts);
}
}
[Fact]
public void Index_WhenAvailableSizesContainsItems_ShouldSetValueToItemValue()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ItemCollection<string> sizes = null;
ActionResult actionResult = null;
// Setup
{
sizes = new ItemCollection<string>() { "medium" };
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant("medium", "red");
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
var expectedSizes = String.Join(";", sizes);
var modelSizeValues = String.Join(";", model.Sizes.Select(x => x.Value));
Assert.Equal<string>(expectedSizes, modelSizeValues);
}
}
[Fact]
public void Index_WhenAvailableSizesContainsItems_ShouldSetSelectedToFalse()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
fashionProduct = CreateFashionProduct();
fashionVariant = CreateFashionVariant("medium", "red");
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
var expectedSizes = String.Join(";", new[] { false });
var modelSizesSelected = String.Join(";", model.Sizes.Select(x => x.Selected));
Assert.Equal<string>(expectedSizes, modelSizesSelected);
}
}
[Fact]
public void Index_WhenAvailableSizesContainsDelayPublishItems_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", "medium" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
// setup variant with publish date in future
fashionVariant = CreateFashionVariant();
fashionVariant.StartPublish = DateTime.UtcNow.AddDays(7); // pulish date is future
fashionVariant.StopPublish = DateTime.UtcNow.AddDays(17);
fashionVariant.Status = VersionStatus.DelayedPublish;
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
Assert.IsType(typeof(HttpNotFoundResult), actionResult);
}
}
[Fact]
public void Index_WhenAvailableSizesContainsExpiredItems_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", "medium" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
// setup variant was expired.
fashionVariant = CreateFashionVariant();
fashionVariant.StartPublish = DateTime.UtcNow.AddDays(-17);
fashionVariant.StopPublish = DateTime.UtcNow.AddDays(-7);
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
Assert.IsType(typeof(HttpNotFoundResult), actionResult);
}
}
[Fact]
public void Index_WhenAvailableSizesContainsUnpublishItems_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", "medium" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
// setup variant with inactive
fashionVariant = CreateFashionVariant();
fashionVariant.IsPendingPublish = true;
fashionVariant.Status = VersionStatus.CheckedIn;
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
Assert.IsType(typeof(HttpNotFoundResult), actionResult);
}
}
[Fact]
public void Index_WhenAvailableSizesContainsItemUnavailabelInCurrentMarket_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariant = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", "medium" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
// setup variant unavailable in default market
fashionVariant = CreateFashionVariant();
fashionVariant.MarketFilter = new ItemCollection<string>() { "Default" };
SetRelation(fashionProduct, fashionVariant);
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariant.Code);
}
// Assert
{
Assert.IsType(typeof(HttpNotFoundResult), actionResult);
}
}
[Fact]
public void Index_WhenIsInEditModeAndHasNoVariation_ShouldReturnProductWithoutVariationView()
{
FashionProduct fashionProduct = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
_isInEditMode = true;
fashionProduct = CreateFashionProduct();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, "notexist");
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
model.Product.ShouldBeEquivalentTo(fashionProduct);
}
}
[Fact]
public void Index_WhenVariationCodeHasValue_ShouldSetColorsToTheAvailableColorsForTheVariationSize()
{
const string variationColorBlue = "blue";
const string variationColorWhite = "white";
FashionProduct fashionProduct = null;
FashionVariant fashionVariantSmallBlue = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", "medium" };
var colors = new ItemCollection<string>() { "red", variationColorBlue, "yellow", variationColorWhite, "green" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
SetAvailableColors(fashionProduct, colors);
fashionVariantSmallBlue = CreateFashionVariant("small", variationColorBlue);
var fashionVariantSmallWhite = CreateFashionVariant("small", variationColorWhite);
SetRelation(fashionProduct, new[] { fashionVariantSmallBlue, fashionVariantSmallWhite });
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariantSmallBlue.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
var expectedColors = String.Join(";", new[] { variationColorBlue, variationColorWhite });
var modelColors = String.Join(";", model.Colors.Select(x => x.Value));
Assert.Equal<string>(expectedColors, modelColors);
}
}
[Fact]
public void Index_WhenVariationCodeHasValue_ShouldSetSizesToTheAvailableSizesForTheVariationColor()
{
const string variationSizeMedium = "medium";
const string variationSizeXlarge = "x-large";
FashionProduct fashionProduct = null;
FashionVariant fashionVariantMediumRed = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", variationSizeMedium, "large", variationSizeXlarge, "xx-large" };
var colors = new ItemCollection<string>() { "red" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
SetAvailableColors(fashionProduct, colors);
fashionVariantMediumRed = CreateFashionVariant(variationSizeMedium, "red");
var fashionVariantXlargeRed = CreateFashionVariant(variationSizeXlarge, "red");
SetRelation(fashionProduct, new[] { fashionVariantMediumRed, fashionVariantXlargeRed });
MockPrices();
productController = CreateController();
}
// Execute
{
actionResult = productController.Index(fashionProduct, fashionVariantMediumRed.Code);
}
// Assert
{
var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model;
var expectedSizes = String.Join(";", new[] { variationSizeMedium, variationSizeXlarge });
var modelSizes = String.Join(";", model.Sizes.Select(x => x.Value));
Assert.Equal<string>(expectedSizes, modelSizes);
}
}
[Fact]
public void SelectVariant_WhenColorAndSizeHasValues_ShouldGetVariantWithSelectedColorAndSize()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariantSmallGreen = null;
FashionVariant fashionVariantSmallRed = null;
FashionVariant fashionVariantMediumGreen = null;
FashionVariant fashionVariantMediumRed = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", "medium" };
var colors = new ItemCollection<string>() { "green", "red" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
SetAvailableColors(fashionProduct, colors);
fashionVariantSmallGreen = CreateFashionVariant("small", "green");
fashionVariantSmallRed = CreateFashionVariant("small", "red");
fashionVariantMediumGreen = CreateFashionVariant("medium", "green");
fashionVariantMediumRed = CreateFashionVariant("medium", "red");
SetRelation(fashionProduct, new[]
{
fashionVariantSmallGreen,
fashionVariantSmallRed,
fashionVariantMediumGreen,
fashionVariantMediumRed,
});
productController = CreateController();
}
// Execute
{
actionResult = productController.SelectVariant(fashionProduct, "red", "small");
}
// Assert
{
var selectedCode = ((RedirectToRouteResult)actionResult).RouteValues["variationCode"] as string;
Assert.Equal<string>("redsmall", selectedCode);
}
}
[Fact]
public void SelectVariant_WhenCanNotFoundBySize_ShouldTryGetVariantWithSelectedColorOnly()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariantSmallGreen = null;
FashionVariant fashionVariantMediumRed = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", "medium" };
var colors = new ItemCollection<string>() { "green", "red" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
SetAvailableColors(fashionProduct, colors);
fashionVariantSmallGreen = CreateFashionVariant("small", "green");
fashionVariantMediumRed = CreateFashionVariant("medium", "red");
SetRelation(fashionProduct, new[]
{
fashionVariantSmallGreen,
fashionVariantMediumRed,
});
productController = CreateController();
}
// Execute
{
actionResult = productController.SelectVariant(fashionProduct, "red", "small");
}
// Assert
{
var selectedCode = ((RedirectToRouteResult)actionResult).RouteValues["variationCode"] as string;
Assert.Equal<string>("redmedium", selectedCode);
}
}
[Fact]
public void SelectVariant_WhenCanNotFoundBySizeOrColor_ShouldReturnHttpNotFoundResult()
{
FashionProduct fashionProduct = null;
FashionVariant fashionVariantSmallGreen = null;
FashionVariant fashionVariantMediumRed = null;
ProductController productController = null;
ActionResult actionResult = null;
// Setup
{
var sizes = new ItemCollection<string>() { "small", "medium" };
var colors = new ItemCollection<string>() { "green", "red" };
fashionProduct = CreateFashionProduct();
SetAvailableSizes(fashionProduct, sizes);
SetAvailableColors(fashionProduct, colors);
fashionVariantSmallGreen = CreateFashionVariant("small", "green");
fashionVariantMediumRed = CreateFashionVariant("medium", "red");
SetRelation(fashionProduct, new[]
{
fashionVariantSmallGreen,
fashionVariantMediumRed,
});
productController = CreateController();
}
// Execute
{
actionResult = productController.SelectVariant(fashionProduct, "yellow", "small");
}
// Assert
{
Assert.IsType<HttpNotFoundResult>(actionResult);
}
}
private readonly Mock<IPromotionService> _promotionServiceMock;
private readonly Mock<IContentLoader> _contentLoaderMock;
private readonly Mock<IPriceService> _priceServiceMock;
private readonly Mock<ICurrentMarket> _currentMarketMock;
private readonly FilterPublished _filterPublished;
private readonly Mock<CurrencyService> _currencyserviceMock;
private readonly Mock<IRelationRepository> _relationRepositoryMock;
private readonly Mock<CookieService> _cookieServiceMock;
private readonly Mock<UrlResolver> _urlResolverMock;
private readonly Mock<HttpContextBase> _httpContextBaseMock;
private readonly Mock<IMarket> _marketMock;
private readonly Mock<AppContextFacade> _appContextFacadeMock;
private readonly Mock<LanguageResolver> _languageResolverMock;
private readonly Currency _defaultCurrency;
private bool _isInEditMode;
public ProductControllerTests()
{
_defaultCurrency = Currency.USD;
_urlResolverMock = new Mock<UrlResolver>();
_contentLoaderMock = new Mock<IContentLoader>();
_cookieServiceMock = new Mock<CookieService>();
_priceServiceMock = new Mock<IPriceService>();
_relationRepositoryMock = new Mock<IRelationRepository>();
_promotionServiceMock = new Mock<IPromotionService>();
var mockPublishedStateAssessor = new Mock<IPublishedStateAssessor>();
mockPublishedStateAssessor.Setup(x => x.IsPublished(It.IsAny<IContent>(), It.IsAny<PublishedStateCondition>()))
.Returns((IContent content, PublishedStateCondition condition) =>
{
var contentVersionable = content as IVersionable;
if (contentVersionable != null)
{
if (contentVersionable.Status == VersionStatus.Published &&
contentVersionable.StartPublish < DateTime.UtcNow &&
contentVersionable.StopPublish > DateTime.UtcNow)
{
return true;
}
}
return false;
}
);
_filterPublished = new FilterPublished(mockPublishedStateAssessor.Object);
_marketMock = new Mock<IMarket>();
_marketMock.Setup(x => x.DefaultCurrency).Returns(_defaultCurrency);
_marketMock.Setup(x => x.MarketId).Returns(new MarketId("Default"));
_marketMock.Setup(x => x.MarketName).Returns("Default");
_marketMock.Setup(x => x.IsEnabled).Returns(true);
_marketMock.Setup(x => x.DefaultLanguage).Returns(new CultureInfo("en"));
_currentMarketMock = new Mock<ICurrentMarket>();
_currentMarketMock.Setup(x => x.GetCurrentMarket()).Returns(_marketMock.Object);
_currencyserviceMock = new Mock<CurrencyService>(_currentMarketMock.Object, _cookieServiceMock.Object);
_currencyserviceMock.Setup(x => x.GetCurrentCurrency()).Returns(_defaultCurrency);
_appContextFacadeMock = new Mock<AppContextFacade>();
_appContextFacadeMock.Setup(x => x.ApplicationId).Returns(Guid.NewGuid);
var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection {
{"X-Requested-With", "XMLHttpRequest"}
});
_httpContextBaseMock = new Mock<HttpContextBase>();
_httpContextBaseMock.SetupGet(x => x.Request).Returns(request.Object);
_languageResolverMock = new Mock<LanguageResolver>();
_languageResolverMock.Setup(x => x.GetPreferredCulture()).Returns(CultureInfo.GetCultureInfo("en"));
SetGetItems(Enumerable.Empty<ContentReference>(), Enumerable.Empty<IContent>());
SetDefaultCurrency(null);
}
public void Dispose()
{
_isInEditMode = false;
}
private ProductController CreateController()
{
var controller = new ProductController(
_promotionServiceMock.Object,
_contentLoaderMock.Object,
_priceServiceMock.Object,
_currentMarketMock.Object,
_currencyserviceMock.Object,
_relationRepositoryMock.Object,
_appContextFacadeMock.Object,
_urlResolverMock.Object,
_filterPublished,
_languageResolverMock.Object,
() => _isInEditMode);
controller.ControllerContext = new ControllerContext(_httpContextBaseMock.Object, new RouteData(), controller);
return controller;
}
private static FashionVariant CreateFashionVariant(string size, string color)
{
var fashionVariant = CreateFashionVariant(color + size);
SetSize(fashionVariant, size);
SetColor(fashionVariant, color);
return fashionVariant;
}
private static FashionVariant CreateFashionVariant(string code = "myVariant")
{
var fashionVariant = new FashionVariant
{
ContentLink = new ContentReference(740),
Code = code,
IsDeleted = false,
IsPendingPublish = false,
Status = VersionStatus.Published,
StartPublish = DateTime.UtcNow.AddDays(-7),
StopPublish = DateTime.UtcNow.AddDays(7),
MarketFilter = new ItemCollection<string>() { "USA" }
};
return fashionVariant;
}
private static FashionProduct CreateFashionProduct()
{
var fashionProduct = new FashionProduct
{
ContentLink = new ContentReference(741),
Code = "myProduct",
IsDeleted = false,
IsPendingPublish = false,
Status = VersionStatus.Published,
StartPublish = DateTime.UtcNow.AddDays(-7),
StopPublish = DateTime.UtcNow.AddDays(7),
MarketFilter = new ItemCollection<string>() { "USA" }
};
SetAvailableColors(fashionProduct, new ItemCollection<string>());
SetAvailableSizes(fashionProduct, new ItemCollection<string>());
return fashionProduct;
}
private static void SetAvailableColors(FashionProduct product, ItemCollection<string> colors)
{
product.AvailableColors = colors;
}
private static void SetAvailableSizes(FashionProduct product, ItemCollection<string> sizes)
{
product.AvailableSizes = sizes;
}
private static void SetColor(FashionVariant fashionVariant, string color)
{
fashionVariant.Color = color;
}
private static void SetSize(FashionVariant fashionVariant, string size)
{
fashionVariant.Size = size;
}
private void SetRelation(IContent source, IContent target)
{
SetRelation(source, new[] { target });
}
private void SetRelation(IContent source, IEnumerable<IContent> targets)
{
SetRelation(source, targets.Select(x => new ProductVariation() { Source = source.ContentLink, Target = x.ContentLink }));
SetGetItems(new[] { source.ContentLink }, new[] { source });
SetGetItems(targets.Select(x => x.ContentLink), targets);
}
private void SetRelation(IContent setup, IEnumerable<ProductVariation> result)
{
_relationRepositoryMock.Setup(x => x.GetRelationsBySource<ProductVariation>(setup.ContentLink)).Returns(result);
}
private void SetGetItems(IEnumerable<ContentReference> setup, IEnumerable<IContent> result)
{
_contentLoaderMock.Setup(x => x.GetItems(setup, CultureInfo.GetCultureInfo("en"))).Returns(result);
}
private void SetDefaultCurrency(string currency)
{
_cookieServiceMock.Setup(x => x.Get("Currency")).Returns(currency);
}
private void SetDefaultPriceService(IPriceValue returnedPrice)
{
_priceServiceMock
.Setup(x => x.GetDefaultPrice(It.IsAny<MarketId>(), It.IsAny<DateTime>(), It.IsAny<CatalogKey>(), _defaultCurrency))
.Returns(returnedPrice);
}
private void SetDiscountPriceService(IPriceValue returnedPrice)
{
_promotionServiceMock
.Setup(x => x.GetDiscountPrice(It.IsAny<CatalogKey>(), It.IsAny<MarketId>(), _defaultCurrency))
.Returns(returnedPrice);
}
private Mock<IPriceValue> CreatePriceValueMock(decimal amount)
{
var mockPriceValue = new Mock<IPriceValue>();
mockPriceValue.Setup(x => x.ValidFrom).Returns(DateTime.MinValue);
mockPriceValue.Setup(x => x.ValidUntil).Returns(DateTime.MaxValue);
mockPriceValue.Setup(x => x.UnitPrice).Returns(new Money(amount, _defaultCurrency));
return mockPriceValue;
}
private void MockPrices()
{
var mockDefaultPrice = CreatePriceValueMock(25);
SetDefaultPriceService(mockDefaultPrice.Object);
var mockDiscountPrice = CreatePriceValueMock(20);
SetDiscountPriceService(mockDiscountPrice.Object);
}
private CommerceMedia CreateImageMedia(ContentReference contentLink, string imageLink)
{
IContentImage contentImage;
var imageMedia = new CommerceMedia { AssetLink = contentLink };
_contentLoaderMock.Setup(x => x.TryGet(imageMedia.AssetLink, out contentImage)).Returns(true);
_urlResolverMock.Setup(x => x.GetUrl(imageMedia.AssetLink)).Returns(imageLink);
return imageMedia;
}
private static void SetMediaCollection(IAssetContainer assetContainer, CommerceMedia media)
{
assetContainer.CommerceMediaCollection = new ItemCollection<CommerceMedia>() { media };
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
namespace EZOper.TechTester.CSharpWebSI.Areas.ZApi
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System.Net.Http.Headers
{
public class MediaTypeHeaderValue : ICloneable
{
private const string charSet = "charset";
private ObjectCollection<NameValueHeaderValue> _parameters;
private string _mediaType;
public string CharSet
{
get
{
NameValueHeaderValue charSetParameter = NameValueHeaderValue.Find(_parameters, charSet);
if (charSetParameter != null)
{
return charSetParameter.Value;
}
return null;
}
set
{
// We don't prevent a user from setting whitespace-only charsets. Like we can't prevent a user from
// setting a non-existing charset.
NameValueHeaderValue charSetParameter = NameValueHeaderValue.Find(_parameters, charSet);
if (string.IsNullOrEmpty(value))
{
// Remove charset parameter
if (charSetParameter != null)
{
_parameters.Remove(charSetParameter);
}
}
else
{
if (charSetParameter != null)
{
charSetParameter.Value = value;
}
else
{
Parameters.Add(new NameValueHeaderValue(charSet, value));
}
}
}
}
public ICollection<NameValueHeaderValue> Parameters
{
get
{
if (_parameters == null)
{
_parameters = new ObjectCollection<NameValueHeaderValue>();
}
return _parameters;
}
}
public string MediaType
{
get { return _mediaType; }
set
{
CheckMediaTypeFormat(value, "value");
_mediaType = value;
}
}
internal MediaTypeHeaderValue()
{
// Used by the parser to create a new instance of this type.
}
protected MediaTypeHeaderValue(MediaTypeHeaderValue source)
{
Contract.Requires(source != null);
_mediaType = source._mediaType;
if (source._parameters != null)
{
foreach (var parameter in source._parameters)
{
this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone());
}
}
}
public MediaTypeHeaderValue(string mediaType)
{
CheckMediaTypeFormat(mediaType, "mediaType");
_mediaType = mediaType;
}
public override string ToString()
{
return _mediaType + NameValueHeaderValue.ToString(_parameters, ';', true);
}
public override bool Equals(object obj)
{
MediaTypeHeaderValue other = obj as MediaTypeHeaderValue;
if (other == null)
{
return false;
}
return string.Equals(_mediaType, other._mediaType, StringComparison.OrdinalIgnoreCase) &&
HeaderUtilities.AreEqualCollections(_parameters, other._parameters);
}
public override int GetHashCode()
{
// The media-type string is case-insensitive.
return StringComparer.OrdinalIgnoreCase.GetHashCode(_mediaType) ^ NameValueHeaderValue.GetHashCode(_parameters);
}
public static MediaTypeHeaderValue Parse(string input)
{
int index = 0;
return (MediaTypeHeaderValue)MediaTypeHeaderParser.SingleValueParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out MediaTypeHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (MediaTypeHeaderParser.SingleValueParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (MediaTypeHeaderValue)output;
return true;
}
return false;
}
internal static int GetMediaTypeLength(string input, int startIndex,
Func<MediaTypeHeaderValue> mediaTypeCreator, out MediaTypeHeaderValue parsedValue)
{
Contract.Requires(mediaTypeCreator != null);
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespace. If not, we'll return 0.
string mediaType = null;
int mediaTypeLength = MediaTypeHeaderValue.GetMediaTypeExpressionLength(input, startIndex, out mediaType);
if (mediaTypeLength == 0)
{
return 0;
}
int current = startIndex + mediaTypeLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
MediaTypeHeaderValue mediaTypeHeader = null;
// If we're not done and we have a parameter delimiter, then we have a list of parameters.
if ((current < input.Length) && (input[current] == ';'))
{
mediaTypeHeader = mediaTypeCreator();
mediaTypeHeader._mediaType = mediaType;
current++; // skip delimiter.
int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
(ObjectCollection<NameValueHeaderValue>)mediaTypeHeader.Parameters);
if (parameterLength == 0)
{
return 0;
}
parsedValue = mediaTypeHeader;
return current + parameterLength - startIndex;
}
// We have a media type without parameters.
mediaTypeHeader = mediaTypeCreator();
mediaTypeHeader._mediaType = mediaType;
parsedValue = mediaTypeHeader;
return current - startIndex;
}
private static int GetMediaTypeExpressionLength(string input, int startIndex, out string mediaType)
{
Contract.Requires((input != null) && (input.Length > 0) && (startIndex < input.Length));
// This method just parses the "type/subtype" string, it does not parse parameters.
mediaType = null;
// Parse the type, i.e. <type> in media type string "<type>/<subtype>; param1=value1; param2=value2"
int typeLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (typeLength == 0)
{
return 0;
}
int current = startIndex + typeLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Parse the separator between type and subtype
if ((current >= input.Length) || (input[current] != '/'))
{
return 0;
}
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Parse the subtype, i.e. <subtype> in media type string "<type>/<subtype>; param1=value1; param2=value2"
int subtypeLength = HttpRuleParser.GetTokenLength(input, current);
if (subtypeLength == 0)
{
return 0;
}
// If there are no whitespace between <type> and <subtype> in <type>/<subtype> get the media type using
// one Substring call. Otherwise get substrings for <type> and <subtype> and combine them.
int mediatTypeLength = current + subtypeLength - startIndex;
if (typeLength + subtypeLength + 1 == mediatTypeLength)
{
mediaType = input.Substring(startIndex, mediatTypeLength);
}
else
{
mediaType = input.Substring(startIndex, typeLength) + "/" + input.Substring(current, subtypeLength);
}
return mediatTypeLength;
}
private static void CheckMediaTypeFormat(string mediaType, string parameterName)
{
if (string.IsNullOrEmpty(mediaType))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
// When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed.
// Also no LWS between type and subtype are allowed.
string tempMediaType;
int mediaTypeLength = GetMediaTypeExpressionLength(mediaType, 0, out tempMediaType);
if ((mediaTypeLength == 0) || (tempMediaType.Length != mediaType.Length))
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, mediaType));
}
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new MediaTypeHeaderValue(this);
}
}
}
| |
namespace Stripe
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public abstract class ServiceNested<TEntityReturned> : Service<TEntityReturned>
where TEntityReturned : IStripeEntity
{
protected ServiceNested()
: base(null)
{
}
protected ServiceNested(IStripeClient client)
: base(client)
{
}
protected TEntityReturned CreateNestedEntity(
string parentId,
BaseOptions options,
RequestOptions requestOptions)
{
return this.Request(
HttpMethod.Post,
this.ClassUrl(parentId),
options,
requestOptions);
}
protected Task<TEntityReturned> CreateNestedEntityAsync(
string parentId,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync(
HttpMethod.Post,
this.ClassUrl(parentId),
options,
requestOptions,
cancellationToken);
}
protected TEntityReturned DeleteNestedEntity(
string parentId,
string id,
BaseOptions options,
RequestOptions requestOptions)
{
return this.Request(
HttpMethod.Delete,
this.InstanceUrl(parentId, id),
options,
requestOptions);
}
protected Task<TEntityReturned> DeleteNestedEntityAsync(
string parentId,
string id,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync(
HttpMethod.Delete,
this.InstanceUrl(parentId, id),
options,
requestOptions,
cancellationToken);
}
protected TEntityReturned GetNestedEntity(
string parentId,
string id,
BaseOptions options,
RequestOptions requestOptions)
{
return this.Request(
HttpMethod.Get,
this.InstanceUrl(parentId, id),
options,
requestOptions);
}
protected Task<TEntityReturned> GetNestedEntityAsync(
string parentId,
string id,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync(
HttpMethod.Get,
this.InstanceUrl(parentId, id),
options,
requestOptions,
cancellationToken);
}
protected StripeList<TEntityReturned> ListNestedEntities(
string parentId,
ListOptions options,
RequestOptions requestOptions)
{
return this.Request<StripeList<TEntityReturned>>(
HttpMethod.Get,
this.ClassUrl(parentId),
options,
requestOptions);
}
protected Task<StripeList<TEntityReturned>> ListNestedEntitiesAsync(
string parentId,
ListOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync<StripeList<TEntityReturned>>(
HttpMethod.Get,
this.ClassUrl(parentId),
options,
requestOptions,
cancellationToken);
}
protected IEnumerable<TEntityReturned> ListNestedEntitiesAutoPaging(
string parentId,
ListOptions options,
RequestOptions requestOptions)
{
return this.ListRequestAutoPaging<TEntityReturned>(
this.ClassUrl(parentId),
options,
requestOptions);
}
protected IAsyncEnumerable<TEntityReturned> ListNestedEntitiesAutoPagingAsync(
string parentId,
ListOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.ListRequestAutoPagingAsync<TEntityReturned>(
this.ClassUrl(parentId),
options,
requestOptions,
cancellationToken);
}
protected TEntityReturned UpdateNestedEntity(
string parentId,
string id,
BaseOptions options,
RequestOptions requestOptions)
{
return this.Request(
HttpMethod.Post,
this.InstanceUrl(parentId, id),
options,
requestOptions);
}
protected Task<TEntityReturned> UpdateNestedEntityAsync(
string parentId,
string id,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync(
HttpMethod.Post,
this.InstanceUrl(parentId, id),
options,
requestOptions,
cancellationToken);
}
protected virtual string ClassUrl(string parentId)
{
if (string.IsNullOrWhiteSpace(parentId))
{
throw new ArgumentException(
"The parent resource ID cannot be null or whitespace.",
nameof(parentId));
}
return this.BasePath.Replace("{PARENT_ID}", parentId);
}
protected virtual string InstanceUrl(string parentId, string id)
{
if (string.IsNullOrWhiteSpace(parentId))
{
throw new ArgumentException(
"The parent resource ID cannot be null or whitespace.",
nameof(parentId));
}
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentException(
"The resource ID cannot be null or whitespace.",
nameof(id));
}
return $"{this.ClassUrl(parentId)}/{WebUtility.UrlEncode(id)}";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobOperations operations.
/// </summary>
public partial interface IJobOperations
{
/// <summary>
/// Gets lifetime summary statistics for all of the jobs in the
/// specified account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all jobs that have ever existed in
/// the account, from account creation to the last update time of the
/// statistics.
/// </remarks>
/// <param name='jobGetAllLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<JobStatistics,JobGetAllLifetimeStatisticsHeaders>> GetAllLifetimeStatisticsWithHttpMessagesAsync(JobGetAllLifetimeStatisticsOptions jobGetAllLifetimeStatisticsOptions = default(JobGetAllLifetimeStatisticsOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a job.
/// </summary>
/// <remarks>
/// Deleting a job also deletes all tasks that are part of that job,
/// and all job statistics. This also overrides the retention period
/// for task data; that is, if the job contains tasks which are still
/// retained on compute nodes, the Batch services deletes those tasks'
/// working directories and all their contents.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to delete.
/// </param>
/// <param name='jobDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobDeleteHeaders>> DeleteWithHttpMessagesAsync(string jobId, JobDeleteOptions jobDeleteOptions = default(JobDeleteOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the specified job.
/// </summary>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CloudJob,JobGetHeaders>> GetWithHttpMessagesAsync(string jobId, JobGetOptions jobGetOptions = default(JobGetOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of the specified job.
/// </summary>
/// <remarks>
/// This replaces only the job properties specified in the request. For
/// example, if the job has constraints, and a request does not specify
/// the constraints element, then the job keeps the existing
/// constraints.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job whose properties you want to update.
/// </param>
/// <param name='jobPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobPatchHeaders>> PatchWithHttpMessagesAsync(string jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions = default(JobPatchOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of the specified job.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the job. For
/// example, if the job has constraints associated with it and if
/// constraints is not specified with this request, then the Batch
/// service will remove the existing constraints.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job whose properties you want to update.
/// </param>
/// <param name='jobUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobUpdateHeaders>> UpdateWithHttpMessagesAsync(string jobId, JobUpdateParameter jobUpdateParameter, JobUpdateOptions jobUpdateOptions = default(JobUpdateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Disables the specified job, preventing new tasks from running.
/// </summary>
/// <remarks>
/// The Batch Service immediately moves the job to the disabling state.
/// Batch then uses the disableTasks parameter to determine what to do
/// with the currently running tasks of the job. The job remains in the
/// disabling state until the disable operation is completed and all
/// tasks have been dealt with according to the disableTasks option;
/// the job then moves to the disabled state. No new tasks are started
/// under the job until it moves back to active state. If you try to
/// disable a job that is in any state other than active, disabling, or
/// disabled, the request fails with status code 409.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to disable.
/// </param>
/// <param name='disableTasks'>
/// What to do with active tasks associated with the job. requeue -
/// Terminate running tasks and requeue them. The tasks will run again
/// when the job is enabled. terminate - Terminate running tasks. The
/// tasks will not run again. wait - Allow currently running tasks to
/// complete. Possible values include: 'requeue', 'terminate', 'wait'
/// </param>
/// <param name='jobDisableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobDisableHeaders>> DisableWithHttpMessagesAsync(string jobId, DisableJobOption disableTasks, JobDisableOptions jobDisableOptions = default(JobDisableOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Enables the specified job, allowing new tasks to run.
/// </summary>
/// <remarks>
/// When you call this API, the Batch service sets a disabled job to
/// the enabling state. After the this operation is completed, the job
/// moves to the active state, and scheduling of new tasks under the
/// job resumes. The Batch service does not allow a task to remain in
/// the active state for more than 7 days. Therefore, if you enable a
/// job containing active tasks which were added more than 7 days ago,
/// those tasks will not run.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to enable.
/// </param>
/// <param name='jobEnableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobEnableHeaders>> EnableWithHttpMessagesAsync(string jobId, JobEnableOptions jobEnableOptions = default(JobEnableOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Terminates the specified job, marking it as completed.
/// </summary>
/// <remarks>
/// When a Terminate Job request is received, the Batch service sets
/// the job to the terminating state. The Batch service then terminates
/// any active or running tasks associated with the job, and runs any
/// required Job Release tasks. The job then moves into the completed
/// state.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to terminate.
/// </param>
/// <param name='terminateReason'>
/// The text you want to appear as the job's TerminateReason. The
/// default is 'UserTerminate'.
/// </param>
/// <param name='jobTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobTerminateHeaders>> TerminateWithHttpMessagesAsync(string jobId, string terminateReason = default(string), JobTerminateOptions jobTerminateOptions = default(JobTerminateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Adds a job to the specified account.
/// </summary>
/// <remarks>
/// The Batch service supports two ways to control the work done as
/// part of a job. In the first approach, the user specifies a Job
/// Manager task. The Batch service launches this task when it is ready
/// to start the job. The Job Manager task controls all other tasks
/// that run under this job, by using the Task APIs. In the second
/// approach, the user directly controls the execution of tasks under
/// an active job, by using the Task APIs. Also note: when naming jobs,
/// avoid including sensitive information such as user names or secret
/// project names. This information may appear in telemetry logs
/// accessible to Microsoft Support engineers.
/// </remarks>
/// <param name='job'>
/// The job to be added.
/// </param>
/// <param name='jobAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobAddHeaders>> AddWithHttpMessagesAsync(JobAddParameter job, JobAddOptions jobAddOptions = default(JobAddOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='jobListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListHeaders>> ListWithHttpMessagesAsync(JobListOptions jobListOptions = default(JobListOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the jobs that have been created under the specified job
/// schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The ID of the job schedule from which you want to get a list of
/// jobs.
/// </param>
/// <param name='jobListFromJobScheduleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleWithHttpMessagesAsync(string jobScheduleId, JobListFromJobScheduleOptions jobListFromJobScheduleOptions = default(JobListFromJobScheduleOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release
/// task for the specified job across the compute nodes where the job
/// has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release task status on
/// all compute nodes that have run the Job Preparation or Job Release
/// task. This includes nodes which have since been removed from the
/// pool.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusWithHttpMessagesAsync(string jobId, JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions = default(JobListPreparationAndReleaseTaskStatusOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the task counts for the specified job.
/// </summary>
/// <remarks>
/// Task counts provide a count of the tasks by active, running or
/// completed task state, and a count of tasks which succeeded or
/// failed. Tasks in the preparing state are counted as running. If the
/// validationStatus is unvalidated, then the Batch service has not
/// been able to check state counts against the task states as reported
/// in the List Tasks API. The validationStatus may be unvalidated if
/// the job contains more than 200,000 tasks.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobGetTaskCountsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<TaskCounts,JobGetTaskCountsHeaders>> GetTaskCountsWithHttpMessagesAsync(string jobId, JobGetTaskCountsOptions jobGetTaskCountsOptions = default(JobGetTaskCountsOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, JobListNextOptions jobListNextOptions = default(JobListNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the jobs that have been created under the specified job
/// schedule.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListFromJobScheduleNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleNextWithHttpMessagesAsync(string nextPageLink, JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions = default(JobListFromJobScheduleNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release
/// task for the specified job across the compute nodes where the job
/// has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release task status on
/// all compute nodes that have run the Job Preparation or Job Release
/// task. This includes nodes which have since been removed from the
/// pool.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusNextWithHttpMessagesAsync(string nextPageLink, JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = default(JobListPreparationAndReleaseTaskStatusNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using LRWarehouse.Business;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net.Http;
using ILPathways.Business;
using ILPathways.Utilities;
namespace Isle.BizServices
{
public class UploadServices
{
//Services
ContentServices contentService = new ContentServices();
//Globals
string SITE_ROOT = UtilityManager.GetAppKeyValue( "siteRoot", "http://ioer.ilsharedlearning.org" );
string SITE_HOST_NAME = UtilityManager.GetAppKeyValue( "siteHostName", "ioer.ilsharedlearning.org" );
int MAX_FILE_SIZE = UtilityManager.GetAppKeyValue( "maxDocumentSize", 35000000 );
//Handle uploading a user profile image
public void UploadContentImage()
{
}
//Handle uploading a library image
public void UploadLibraryImage()
{
}
//Handle uploading a collection image
public void UploadCollectionImage()
{
}
/// <summary>
/// Handle uploading a content item custom image that replaces the thumbnail.
/// Will select only the first file from either the posted files or the google drive IDs, depending on which is available (and in that order).
/// NOTE: currently relies on a workaround in AjaxUploadService to handle things related to IOER.Controllers
/// </summary>
/// <param name="contentID"></param>
/// <param name="postedFiles"></param>
/// <param name="googleIDs"></param>
/// <param name="user"></param>
/// <param name="valid"></param>
/// <param name="status"></param>
/// <returns>URL to the newly available image</returns>
public Image UploadContentImage( int contentID, HttpFileCollection postedFiles, List<GoogleDriveFileData> googleFiles, Patron user, string gdAccessToken, string savingFolder, ref bool valid, ref string status )
{
//Verify user
if ( user == null || user.Id == 0 )
{
valid = false;
status = "You must be logged in to update the image.";
return null;
}
//Verify content
var content = contentService.Get( contentID );
if ( content == null || content.Id == 0 )
{
valid = false;
status = "Invalid content ID";
return null;
}
//Verify permissions
if( !CanUserEditContent( content.Id, content.CreatedById, user ) )
{
valid = false;
status = "You do not have permission to make that change.";
return null;
}
//Get the finalized image
Image image = CreateImageFromSource( contentID, postedFiles, googleFiles, gdAccessToken, ref valid, ref status );
if ( !valid )
{
return null;
}
//Do the update and return the image's URL
WriteContentImage( content, image, savingFolder, ref valid, ref status );
if ( !valid )
{
return null;
}
return image;
}
//Handle uploading files to a content item - does not handle replacing files
public List<FileStatus> UploadContentAttachments( int contentID, HttpFileCollection postedFiles, List<GoogleDriveFileData> googleFiles, Patron user, string gdAccessToken, string filePath, string savingUrl, ref bool valid, ref string status )
{
var results = new List<FileStatus>();
//Verify user
if ( user == null || user.Id == 0 )
{
valid = false;
status = "You must be logged in to upload files.";
return null;
}
//Verify content
var content = contentService.Get( contentID );
if ( content == null || content.Id == 0 )
{
valid = false;
status = "Invalid content ID";
return null;
}
//Verify permissions
if ( !CanUserEditContent( content.Id, content.CreatedById, user ) )
{
valid = false;
status = "You do not have permission to make that change.";
return null;
}
//Validate and save each file, one by one
for ( var i = 0; i < postedFiles.Count; i++ )
{
try
{
var file = postedFiles[ i ];
ValidateFile( file.InputStream, ref valid, ref status );
if ( !valid )
{
results.Add( new FileStatus()
{
Successful = false,
Status = status,
Name = file.FileName
} );
continue;
}
var fileStatus = CreateContentWithFile( content, file.InputStream, user, file.FileName, file.ContentType, filePath, savingUrl, ref valid, ref status );
results.Add( fileStatus );
}
catch ( Exception ex )
{
results.Add( new FileStatus()
{
Status = "Error uploading this file: " + ex.Message,
Successful = false,
Name = postedFiles[i].FileName
} );
}
}
foreach ( var gdFile in googleFiles )
{
try
{
var file = GetFileFromGoogleDrive( gdFile, gdAccessToken );
ValidateFile( file.ContentStream, ref valid, ref status );
if ( !valid )
{
results.Add( new FileStatus()
{
Successful = false,
Status = status,
Name = file.Name
} );
continue;
}
var fileStatus = CreateContentWithFile( content, file.ContentStream, user, file.Name, file.MimeType, filePath, savingUrl, ref valid, ref status );
results.Add( fileStatus );
}
catch ( Exception ex )
{
results.Add( new FileStatus() {
Status = "Error retrieving file from Google Drive: " + ex.Message,
Successful = false,
Name = gdFile.Name,
} );
}
}
return results;
}
#region Helper Methods
//Create a new content item from a file - does not handle replacing files
protected FileStatus CreateContentWithFile( ContentItem parent, Stream fileStream, Patron user, string fileName, string mimeType, string filePath, string savingUrl, ref bool valid, ref string status )
{
var fileStatus = new FileStatus();
try
{
//Get bytes from file stream
var temp = new MemoryStream();
fileStream.Position = 0;
fileStream.CopyTo( temp );
var fileBytes = temp.ToArray();
temp.Dispose();
fileStream.Dispose();
//Build content item
var attachment = new ContentItem()
{
ParentId = parent.Id,
Title = fileName,
StatusId = ContentItem.INPROGRESS_STATUS,
PrivilegeTypeId = ContentItem.PUBLIC_PRIVILEGE,
TypeId = ContentItem.DOCUMENT_CONTENT_ID,
MimeType = mimeType,
CreatedById = user.Id,
Created = DateTime.Now,
LastUpdatedById = user.Id,
SortOrder = 10
};
//NOTE - cannot save file the normal way here due to FileResourceController living in IOER namespace - would require circular reference
//Construct document object
var doc = new DocumentVersion()
{
RowId = Guid.NewGuid(),
CreatedById = user.Id,
Created = DateTime.Now,
FileDate = DateTime.Now,
LastUpdatedById = user.Id,
FileName = FileSystemHelper.SanitizeFilename( Path.GetFileNameWithoutExtension( fileName ) + Path.GetExtension( fileName ).ToLower() ),
MimeType = mimeType,
FilePath = filePath,
};
doc.Title = Path.GetFileNameWithoutExtension( doc.FileName );
doc.ResourceUrl = savingUrl + "/" + doc.FileName;
//Update file status object
fileStatus.Name = doc.FileName;
fileStatus.Url = doc.ResourceUrl;
//Save document
SaveFile( fileBytes, doc.FilePath, doc.FileName, ref valid, ref status );
if ( !valid )
{
fileStatus.Successful = false;
fileStatus.Status = "Error writing document to disk: " + status;
return fileStatus;
}
//Set resource data
doc.SetResourceData( fileBytes.LongLength, fileBytes );
var docID = contentService.DocumentVersionCreate( doc, ref status );
if ( string.IsNullOrWhiteSpace( docID ) )
{
valid = false;
fileStatus.Successful = false;
fileStatus.Status = "Error setting resource data: " + status;
return fileStatus;
}
doc.RowId = new Guid( docID );
//Create content
attachment.DocumentRowId = doc.RowId;
attachment.DocumentUrl = doc.ResourceUrl;
var fileID = contentService.Create( attachment, ref status );
if ( fileID == 0 )
{
valid = false;
fileStatus.Successful = false;
fileStatus.Status = "Error updating content item after uploading document: " + status;
return fileStatus;
}
//Success - hopefully covered all the bases
valid = true;
status = "okay";
fileStatus.ContentId = fileID;
fileStatus.Successful = true;
fileStatus.Status = "okay";
}
catch ( Exception ex )
{
valid = false;
status = ex.Message;
fileStatus.Successful = false;
fileStatus.Status = "Error creating resource: " + status;
}
return fileStatus;
}
protected void SaveFile( byte[] bytes, string folder, string fileName, ref bool valid, ref string status )
{
try
{
FileSystemHelper.CreateDirectory( folder );
var diskFile = folder + "\\" + fileName;
File.WriteAllBytes( diskFile, bytes );
valid = true;
status = "okay";
}
catch ( Exception ex )
{
valid = false;
status = ex.Message;
LoggingHelper.LogError( ex, "UploadServices.SaveFile( " + folder + ", " + fileName + ")" );
}
}
//Given a set of posted files and a set of google file data, find the first available file and attempt to process it as an image
protected Image CreateImageFromSource( int contentID, HttpFileCollection postedFiles, List<GoogleDriveFileData> googleFiles, string gdAccessToken, ref bool valid, ref string status )
{
Image image;
try
{
if ( postedFiles.Count > 0 )
{
//Select file
var file = postedFiles[ 0 ];
//Validate type
if ( !IsValidMimeType( file.ContentType, new List<string>() { "jpg", "jpeg", "png", "gif", "bmp" } ) )
{
valid = false;
status = "You must select an image.";
return null;
}
//Validate file
ValidateFile( file.InputStream, ref valid, ref status );
if ( !valid )
{
valid = false;
return null;
}
//Resize and convert
image = ProcessImage( file.InputStream, file.ContentType, contentID.ToString(), ImageFormat.Png, 400, 300 );
}
else if ( googleFiles.Count() > 0 )
{
//Select file
var file = googleFiles.First();
//Validate type
if ( !IsValidMimeType( file.MimeType, new List<string>() { "jpg", "jpeg", "png", "gif", "bmp" } ) )
{
valid = false;
status = "You must select an image.";
return null;
}
//Get image
var rawFile = GetFileFromGoogleDrive( googleFiles.First(), gdAccessToken );
//Validate file
ValidateFile( rawFile.ContentStream, ref valid, ref status );
if ( !valid )
{
valid = false;
return null;
}
//Resize and convert
image = ProcessImage( rawFile.ContentStream, rawFile.MimeType, rawFile.Name, ImageFormat.Png, 400, 300 );
}
else
{
throw new Exception( "You must select an image" );
}
}
catch ( Exception ex )
{
valid = false;
status = ex.Message;
return null;
}
//Return result
if ( image == null )
{
valid = false;
status = "Error creating image";
return null;
}
valid = true;
status = "okay";
return image;
}
//
//Validate file
public void ValidateFile( Stream inputStream, ref bool valid, ref string status )
{
//Check size
if ( inputStream.Length > MAX_FILE_SIZE )
{
valid = false;
status = "File is too large. Maximum allowed size is " + ( MAX_FILE_SIZE / 1024 ) + " KB.";
return;
}
//Check for viruses
new VirusScanner().Scan( inputStream, ref valid, ref status );
}
//General image processing
protected Image ProcessImage( Stream inputStream, string contentType, string outputName, ImageFormat outputFormat, int outputWidth, int outputHeight )
{
//Convert stream to bitmap to handle resizing
var newImage = new Bitmap( Image.FromStream( inputStream ), new Size() { Width = outputWidth, Height = outputHeight } );
//Convert bitmap to new format to handle switching output formats
var newStream = new MemoryStream();
newImage.Save( newStream, outputFormat );
//Return the finalized image
var final = Image.FromStream( newStream );
return final;
}
//
//Get file from google
protected GoogleDriveFileData GetFileFromGoogleDrive( GoogleDriveFileData data, string accessToken )
{
var getter = new HttpClient();
getter.DefaultRequestHeaders.Add( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36" );
getter.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue( "Bearer", accessToken );
var result = getter.GetAsync( data.Url ).Result.Content;
data.ContentString = result.ReadAsStringAsync().Result;
data.ContentBytes = result.ReadAsByteArrayAsync().Result;
data.ContentStream = result.ReadAsStreamAsync().Result;
return data;
}
//
//Check to see if the user is able to edit content
protected bool CanUserEditContent( int contentID, int contentCreatedById, Patron user )
{
var partner = ContentServices.ContentPartner_Get( contentID, user.Id );
var privileges = SecurityManager.GetGroupObjectPrivileges( user, "IOER.controls.Authoring" );
return
user.TopAuthorization < ( int ) EUserRole.StateAdministrator || //If user is admin...
contentCreatedById == user.Id || //Or if user is the creator of the content...
privileges.WritePrivilege > ( int ) EPrivilegeDepth.Region || //Or if the user has sufficient write privileges..
( partner != null && partner.PartnerTypeId >= 2 ); //Or if the user is a partner with sufficient access...
}
//
//Check to see if the mime type contains a value from a list of strings
protected bool IsValidMimeType( string mimeType, List<string> values )
{
var valid = false;
foreach ( var item in values )
{
if ( mimeType.IndexOf( item ) > -1 )
{
valid = true;
}
}
return valid;
}
//
//Create thumbnail images using the data from the uploaded image
protected void CreateContentThumbnailFromImageBytes( ContentItem content, byte[] imageBytes )
{
//If relevant, create thumbnail
if ( UtilityManager.GetAppKeyValue( "creatingThumbnails" ) == "yes" )
{
//Write placeholder to thumbnail folder
var thumbnailFolder = ILPathways.Utilities.UtilityManager.GetAppKeyValue( "serverThumbnailFolder", @"\\OERDATASTORE\OerThumbs\large\" );
File.WriteAllBytes( thumbnailFolder + content.RowId + ".png", imageBytes );
//Replace existing thumbnail if applicable
if ( content.ResourceIntId > 0 )
{
File.WriteAllBytes( thumbnailFolder + content.ResourceIntId + "-large.png", imageBytes );
}
}
}
//
//Store an uploaded content image
protected void WriteContentImage( ContentItem content, Image image, string savingFolder, ref bool valid, ref string status )
{
try
{
var savingName = "list" + content.Id.ToString() + ".png";
var store = new ImageStore()
{
FileName = savingName,
FileDate = DateTime.Now
};
//Convert image to byte[] and store
var imageStream = new MemoryStream();
image.Save( imageStream, ImageFormat.Png );
var imageBytes = imageStream.ToArray();
store.SetImageData( imageBytes.LongLength, imageBytes );
FileSystemHelper.HandleDocumentCaching( savingFolder, store, true );
contentService.Update( content );
//Create Thumbnails
CreateContentThumbnailFromImageBytes( content, imageBytes );
}
catch ( Exception ex )
{
valid = false;
status = ex.Message;
}
valid = true;
status = "okay";
}
#endregion
#region Helper Classes
public class GoogleDriveFileData
{
public string Id { get; set; }
public string Name { get; set; }
public string MimeType { get; set; }
public string Url { get; set; }
public string ContentString { get; set; }
public byte[] ContentBytes { get; set; }
public Stream ContentStream { get; set; }
}
public class FileStatus
{
public int ContentId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Status { get; set; }
public bool Successful { get; set; }
}
#endregion
}
}
| |
#region MIT
//
// Gorgon.
// Copyright (C) 2017 Michael Winsor
//
// 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
// 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.
//
// Created: February 24, 2017 12:20:41 AM
//
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Gorgon.Core;
using Gorgon.Graphics.Fonts.Properties;
using DX = SharpDX;
namespace Gorgon.Graphics.Fonts.Codecs
{
/// <summary>
/// The base class used to define functionality to allow applications to write their own codecs for reading/writing font data.
/// </summary>
/// <remarks>
/// <para>
/// Implementors that want to create their own font import/export functionality should do so by inheriting from this class. It contains functionality that will allow the fonts to be created and registered
/// with a <seealso cref="GorgonFontFactory"/>.
/// </para>
/// </remarks>
public abstract class GorgonFontCodec
: IGorgonFontCodec
{
#region Properties.
/// <summary>
/// Property to return the font factory containing cached font data.
/// </summary>
protected GorgonFontFactory Factory
{
get;
}
/// <summary>
/// Property to return the default filename extension for font files.
/// </summary>
public abstract string DefaultFileExtension
{
get;
}
/// <summary>
/// Property to return whether the codec supports decoding of font data.
/// </summary>
/// <remarks>
/// If this value is <b>false</b>, then the codec is effectively write only.
/// </remarks>
public abstract bool CanDecode
{
get;
}
/// <summary>
/// Property to return whether the codec supports encoding of font data.
/// </summary>
/// <remarks>
/// If this value is <b>false</b>, then the codec is effectively read only.
/// </remarks>
public abstract bool CanEncode
{
get;
}
/// <summary>
/// Property to return whether the codec supports fonts with outlines.
/// </summary>
public abstract bool SupportsFontOutlines
{
get;
}
/// <summary>
/// Property to return the common file name extension(s) for a codec.
/// </summary>
public IReadOnlyList<string> CodecCommonExtensions
{
get;
protected set;
}
/// <summary>
/// Property to return the friendly description of the codec.
/// </summary>
public abstract string CodecDescription
{
get;
}
/// <summary>
/// Property to return the abbreviated name of the codec (e.g. GorFont).
/// </summary>
public abstract string Codec
{
get;
}
/// <summary>
/// Property to return the name of this object.
/// </summary>
/// <remarks>
/// For best practises, the name should only be set once during the lifetime of an object. Hence, this interface only provides a read-only implementation of this
/// property.
/// </remarks>
string IGorgonNamedObject.Name => Codec;
#endregion
#region Methods.
/// <summary>
/// Function to write the font data to the stream.
/// </summary>
/// <param name="fontData">The font data to write.</param>
/// <param name="stream">The stream to write into.</param>
/// <remarks>
/// <para>
/// Implementors must override this method to write out the font data in the expected format.
/// </para>
/// </remarks>
protected abstract void OnWriteFontData(GorgonFont fontData, Stream stream);
/// <summary>
/// Function to read the meta data for font data within a stream.
/// </summary>
/// <param name="stream">The stream containing the metadata to read.</param>
/// <returns>
/// The font meta data as a <see cref="GorgonFontInfo"/> value.
/// </returns>
protected abstract GorgonFontInfo OnGetMetaData(Stream stream);
/// <summary>
/// Function to load the font data, with the specified size, from a stream.
/// </summary>
/// <param name="name">The name to assign to the font.</param>
/// <param name="stream">The stream containing the font data.</param>
/// <returns>A new <seealso cref="GorgonFont"/>, or, an existing font from the <seealso cref="GorgonFontFactory"/> cache.</returns>
protected abstract GorgonFont OnLoadFromStream(string name, Stream stream);
/// <summary>
/// Function to load the font data, with the specified size, from a stream.
/// </summary>
/// <param name="name">The name to assign to the font.</param>
/// <param name="stream">The stream containing the font data.</param>
/// <returns>A new <seealso cref="GorgonFont"/>, or, an existing font from the <seealso cref="GorgonFontFactory"/> cache.</returns>
protected abstract Task<GorgonFont> OnLoadFromStreamAsync(string name, Stream stream);
/// <summary>
/// Function to read the meta data for font data within a stream.
/// </summary>
/// <param name="stream">The stream containing the metadata to read.</param>
/// <returns>
/// The font meta data as a <see cref="GorgonFontInfo"/> value.
/// </returns>
/// <exception cref="IOException">Thrown when the <paramref name="stream"/> is write-only or if the stream cannot perform seek operations.
/// <para>-or-</para>
/// <para>Thrown if the file is corrupt or can't be read by the codec.</para>
/// </exception>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/> parameter is <b>null</b>.</exception>
/// <exception cref="IOException">Thrown when the <paramref name="stream"/> is write-only or if the stream cannot perform seek operations.</exception>
/// <exception cref="EndOfStreamException">Thrown when an attempt to read beyond the end of the stream is made.</exception>
public GorgonFontInfo GetMetaData(Stream stream)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new IOException(Resources.GORGFX_ERR_STREAM_WRITE_ONLY);
}
if (!stream.CanSeek)
{
throw new IOException(Resources.GORGFX_ERR_STREAM_NO_SEEK);
}
if (stream.Length - stream.Position < sizeof(ulong))
{
throw new EndOfStreamException();
}
long streamPosition = stream.Position;
try
{
return OnGetMetaData(stream);
}
finally
{
stream.Position = streamPosition;
}
}
/// <summary>
/// Function to determine if this codec can read the font data within the stream or not.
/// </summary>
/// <param name="stream">The stream that is used to read the font data.</param>
/// <returns><b>true</b> if the codec can read the file, <b>false</b> if not.</returns>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/> parameter is <b>null</b>.</exception>
/// <exception cref="IOException">Thrown when the <paramref name="stream"/> is write-only or if the stream cannot perform seek operations.</exception>
/// <exception cref="EndOfStreamException">Thrown when an attempt to read beyond the end of the stream is made.</exception>
/// <remarks>
/// <para>
/// Implementors should ensure that the stream position is restored prior to exiting this method. Failure to do so may cause problems when reading the data from the stream.
/// </para>
/// </remarks>
public abstract bool IsReadable(Stream stream);
/// <summary>
/// Function to asynchronously load a font from a stream.
/// </summary>
/// <param name="stream">The stream containing the font data to read.</param>
/// <param name="name">The name of the font.</param>
/// <returns>A <see cref="GorgonFont"/> containing the font data from the stream.</returns>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/>, or the <paramref name="name"/> parameter is <b>null</b>.</exception>
/// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="name"/> parameter is empty.</exception>
/// <exception cref="ArgumentException">Thrown when the <paramref name="stream"/> is write only.</exception>
/// <exception cref="EndOfStreamException">Thrown when the amount of data requested exceeds the size of the stream minus its current position.</exception>
public async Task<GorgonFont> FromStreamAsync(Stream stream, string name)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new ArgumentException(Resources.GORGFX_ERR_STREAM_WRITE_ONLY, nameof(stream));
}
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentEmptyException(nameof(name));
}
Stream externalStream = stream;
try
{
if (!stream.CanSeek)
{
externalStream = new DX.DataStream((int)stream.Length, true, true);
stream.CopyTo(externalStream);
externalStream.Position = 0;
}
GorgonFont result = await OnLoadFromStreamAsync(name, externalStream);
return result;
}
finally
{
if (externalStream != stream)
{
externalStream.Dispose();
}
}
}
/// <summary>
/// Function to load a font from a stream.
/// </summary>
/// <param name="stream">The stream containing the font data to read.</param>
/// <param name="name">The name of the font.</param>
/// <returns>A <see cref="GorgonFont"/> containing the font data from the stream.</returns>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/>, or the <paramref name="name"/> parameter is <b>null</b>.</exception>
/// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="name"/> parameter is empty.</exception>
/// <exception cref="ArgumentException">Thrown when the <paramref name="stream"/> is write only.</exception>
/// <exception cref="EndOfStreamException">Thrown when the amount of data requested exceeds the size of the stream minus its current position.</exception>
public GorgonFont FromStream(Stream stream, string name)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new ArgumentException(Resources.GORGFX_ERR_STREAM_WRITE_ONLY, nameof(stream));
}
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentEmptyException(nameof(name));
}
Stream externalStream = stream;
try
{
if (!stream.CanSeek)
{
externalStream = new DX.DataStream((int)stream.Length, true, true);
stream.CopyTo(externalStream);
externalStream.Position = 0;
}
return OnLoadFromStream(name, externalStream);
}
finally
{
if (externalStream != stream)
{
externalStream.Dispose();
}
}
}
/// <summary>
/// Function to persist a <see cref="GorgonFont"/> to a file on the physical file system.
/// </summary>
/// <param name="fontData">A <see cref="GorgonFont"/> to persist to the stream.</param>
/// <param name="filePath">The path to the file that will hold the font data.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="filePath"/>, or the <paramref name="fontData"/> parameter is <b>null</b>.</exception>
/// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="filePath"/> is empty..</exception>
/// <exception cref="GorgonException">Thrown when the font data in the stream has a pixel format that is unsupported.</exception>
public void Save(GorgonFont fontData, string filePath)
{
FileStream stream = null;
if (fontData is null)
{
throw new ArgumentNullException(nameof(fontData));
}
if (filePath is null)
{
throw new ArgumentNullException(nameof(filePath));
}
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentEmptyException(nameof(filePath));
}
try
{
stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
OnWriteFontData(fontData, stream);
}
finally
{
stream?.Dispose();
}
}
/// <summary>
/// Function to persist a <see cref="GorgonFont"/> to a stream.
/// </summary>
/// <param name="fontData">A <see cref="GorgonFont"/> to persist to the stream.</param>
/// <param name="stream">The stream that will receive the font data.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/>, or the <paramref name="fontData"/> parameter is <b>null</b>.</exception>
/// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="stream"/> is read only.</exception>
/// <exception cref="GorgonException">Thrown when the font data in the stream has a pixel format that is unsupported.</exception>
public void Save(GorgonFont fontData, Stream stream)
{
if (fontData is null)
{
throw new ArgumentNullException(nameof(fontData));
}
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanWrite)
{
throw new IOException(Resources.GORGFX_ERR_STREAM_READ_ONLY);
}
if (!stream.CanSeek)
{
throw new IOException(Resources.GORGFX_ERR_STREAM_NO_SEEK);
}
OnWriteFontData(fontData, stream);
}
/// <summary>
/// Function to asynchronously load a font from a file on the physical file system.
/// </summary>
/// <param name="filePath">Path to the file to load.</param>
/// <param name="name">[Optional] The name of the font.</param>
/// <returns>A <see cref="GorgonFont"/> containing the font data from the stream.</returns>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="filePath"/> parameter is <b>null</b>.</exception>
public async Task<GorgonFont> FromFileAsync(string filePath, string name = null)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentEmptyException(nameof(filePath));
}
if (string.IsNullOrWhiteSpace(name))
{
name = filePath;
}
using FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
return await OnLoadFromStreamAsync(name, stream);
}
/// <summary>
/// Function to load a font from a file on the physical file system.
/// </summary>
/// <param name="filePath">Path to the file to load.</param>
/// <param name="name">[Optional] The name of the font.</param>
/// <returns>A <see cref="GorgonFont"/> containing the font data from the stream.</returns>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="filePath"/> parameter is <b>null</b>.</exception>
public GorgonFont FromFile(string filePath, string name = null)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentEmptyException(nameof(filePath));
}
if (string.IsNullOrWhiteSpace(name))
{
name = filePath;
}
using FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
return OnLoadFromStream(name, stream);
}
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="string" /> that represents this instance.
/// </returns>
public override string ToString() => string.Format(Resources.GORGFX_TOSTR_FONT_CODEC, Codec);
#endregion
#region Constructor/Finalizer.
/// <summary>
/// Initializes a new instance of the <see cref="GorgonFontCodec"/> class.
/// </summary>
/// <param name="factory">The font factory that holds cached font information.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="factory"/> parameter is <b>null</b>.</exception>
protected GorgonFontCodec(GorgonFontFactory factory)
{
Factory = factory ?? throw new ArgumentNullException(nameof(factory));
CodecCommonExtensions = Array.Empty<string>();
}
#endregion
}
}
| |
using System;
using System.Collections.Specialized;
using MbUnit.Framework;
using Moq;
using Subtext.Extensibility.Interfaces;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Providers;
using Subtext.Framework.Services;
using Subtext.Framework.Web.HttpModules;
namespace UnitTests.Subtext.Framework.Services
{
[TestFixture]
public class BlogLookupServiceTests
{
private static HostInfo CreateHostInfo()
{
return new HostInfo(new NameValueCollection());
}
[Test]
public void Request_WithMatchingHost_ReturnsCorrespondingBlog()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns(new Blog { Host = "example.com" });
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(CreateHostInfo));
//act
BlogLookupResult result =
service.Lookup(new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false));
//assert
Assert.IsNotNull(result.Blog);
Assert.IsNull(result.AlternateUrl);
}
[Test]
public void Request_WithNonMatchingHostButAlternativeHostMatches_ReturnsAlternativeHost()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns(new Blog { Host = "www.example.com" });
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(CreateHostInfo));
//act
BlogLookupResult result =
service.Lookup(new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false));
//assert
Assert.IsNull(result.Blog);
Assert.AreEqual("http://www.example.com/foo/bar", result.AlternateUrl.ToString());
}
[Test]
public void Request_MatchingActiveAlias_RedirectsToPrimary()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("blog.example.com", It.IsAny<string>())).Returns(new Blog { Host = "www.example.com" });
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(CreateHostInfo));
//act
BlogLookupResult result =
service.Lookup(new BlogRequest("blog.example.com", string.Empty,
new Uri("http://blog.example.com/foo/bar"), false));
//assert
Assert.IsNull(result.Blog);
Assert.AreEqual("http://www.example.com/foo/bar", result.AlternateUrl.ToString());
}
[Test]
public void Request_MatchingActiveAliasWithSubfolder_RedirectsToPrimaryWithoutSubfolder()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("blog.example.com", "sub")).Returns(new Blog { Host = "www.example.com", Subfolder = "" });
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(CreateHostInfo));
//act
BlogLookupResult result =
service.Lookup(new BlogRequest("blog.example.com", "sub", new Uri("http://blog.example.com/sub/foo/bar"),
false));
//assert
Assert.IsNull(result.Blog);
Assert.AreEqual("http://www.example.com/foo/bar", result.AlternateUrl.ToString());
}
[Test]
public void Request_MatchingActiveAliasWithoutSubfolder_RedirectsToPrimaryWithSubfolder()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("blog.example.com", string.Empty)).Returns(new Blog { Host = "www.example.com", Subfolder = "sub" });
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(CreateHostInfo));
//act
BlogLookupResult result =
service.Lookup(new BlogRequest("blog.example.com", string.Empty,
new Uri("http://blog.example.com/foo/bar"), false));
//assert
Assert.IsNull(result.Blog);
Assert.AreEqual("http://www.example.com/sub/foo/bar", result.AlternateUrl.ToString());
}
[Test]
public void Request_MatchingActiveAliasWithSubfolder_RedirectsToPrimaryWithDifferentSubfolder()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("blog.example.com", "notsub")).Returns(new Blog { Host = "www.example.com", Subfolder = "sub" });
repository.Setup(r => r.GetBlogByDomainAlias("blog.example.com", "notsub", It.IsAny<bool>())).Returns(
new Blog { Host = "www.example.com", Subfolder = "sub" });
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(CreateHostInfo));
//act
BlogLookupResult result =
service.Lookup(new BlogRequest("blog.example.com", "notsub",
new Uri("http://blog.example.com/notsub/foo/bar"), false));
//assert
Assert.IsNull(result.Blog);
Assert.AreEqual("http://www.example.com/sub/foo/bar", result.AlternateUrl.ToString());
}
[Test]
public void Request_NotMatchingAnyBlog_ReturnsNull()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
var pagedCollection = new Mock<IPagedCollection<Blog>>();
pagedCollection.Setup(p => p.MaxItems).Returns(0);
repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
pagedCollection.Object);
var appSettings = new NameValueCollection();
appSettings.Add("AggregateEnabled", "false");
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(() => new HostInfo(appSettings)));
//act
BlogLookupResult result =
service.Lookup(new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false));
//assert
Assert.IsNull(result);
}
[Test]
public void RequestNotMatchingAnyBlog_ButWithAggregateBlogsEnabledAndActiveBlogsInTheSystem_ReturnsAggregateBlog()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
var onlyBlog = new Blog { Host = "example.com", Subfolder = "not-sub" };
var pagedCollection = new PagedCollection<Blog> { onlyBlog };
pagedCollection.MaxItems = 1;
repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
pagedCollection);
var appSettings = new NameValueCollection();
appSettings.Add("AggregateEnabled", "true");
var hostInfo = new HostInfo(appSettings);
var service = new BlogLookupService(repository.Object,
new LazyNotNull<HostInfo>(() => hostInfo));
var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false);
//act
BlogLookupResult result = service.Lookup(blogRequest);
//assert
Assert.AreSame(hostInfo.AggregateBlog, result.Blog);
}
[Test]
public void RequestWithSubfolderNotMatchingAnyBlog_ButWithAggregateBlogsEnabledAndMoreThanOneActiveBlogsInTheSystem_ReturnsNull()
{
//arrange
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
var blog1 = new Blog { Host = "example.com", Subfolder = "not-sub" };
var blog2 = new Blog { Host = "example.com", Subfolder = "not-sub-2" };
var pagedCollection = new PagedCollection<Blog> { blog1, blog2 };
pagedCollection.MaxItems = 2;
repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
pagedCollection);
var appSettings = new NameValueCollection();
appSettings.Add("AggregateEnabled", "true");
var hostInfo = new HostInfo(appSettings);
var service = new BlogLookupService(repository.Object,
new LazyNotNull<HostInfo>(() => hostInfo));
var blogRequest = new BlogRequest("example.com", "blog1234", new Uri("http://example.com/foo/bar"), false);
//act
BlogLookupResult result = service.Lookup(blogRequest);
//assert
Assert.IsNull(result);
}
/// <summary>
/// This test makes sure we deal gracefully with a common deployment problem.
/// A user sets up the blog on his/her local machine (aka "localhost"), then
/// deploys the database to their production server. The hostname in the db
/// should be changed to the new domain.
/// </summary>
[Test]
public void
RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithMatchingHostButDifferentSubfolder_RedirectsToOnlyBlog
()
{
//arrange
var onlyBlog = new Blog { Host = "example.com", Subfolder = "not-sub" };
var pagedCollection = new PagedCollection<Blog> { onlyBlog };
pagedCollection.MaxItems = 1;
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("example.com", "sub")).Returns((Blog)null);
repository.Setup(r => r.GetBlog("example.com", "not-sub")).Returns(onlyBlog);
repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
pagedCollection);
var appSettings = new NameValueCollection();
appSettings.Add("AggregateEnabled", "false");
var hostInfo = new HostInfo(appSettings);
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(() => hostInfo));
var blogRequest = new BlogRequest("example.com", "sub", new Uri("http://example.com/Subtext.Web/sub/bar"),
false, RequestLocation.Blog, "/Subtext.Web");
//act
BlogLookupResult result = service.Lookup(blogRequest);
//assert
Assert.IsNull(result.Blog);
Assert.AreEqual("http://example.com/Subtext.Web/not-sub/bar", result.AlternateUrl.ToString());
}
/// <summary>
/// This test makes sure we deal gracefully with a common deployment problem.
/// A user sets up the blog on his/her local machine (aka "localhost"), then
/// deploys the database to their production server. The hostname in the db
/// should be changed to the new domain.
/// </summary>
[Test]
public void RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithLocalHost_ReturnsThatBlogAndUpdatesItsHost()
{
//arrange
var onlyBlog = new Blog { Host = "localhost", Subfolder = "" };
var pagedCollection = new PagedCollection<Blog> { onlyBlog };
pagedCollection.MaxItems = 1;
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
pagedCollection);
var appSettings = new NameValueCollection();
appSettings.Add("AggregateEnabled", "false");
var hostInfo = new HostInfo(appSettings);
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(() => hostInfo));
var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false);
//act
BlogLookupResult result = service.Lookup(blogRequest);
//assert
Assert.IsNotNull(result.Blog);
Assert.IsNull(result.AlternateUrl);
Assert.AreEqual("example.com", result.Blog.Host);
Assert.AreEqual("example.com", onlyBlog.Host);
repository.Verify(r => r.UpdateBlog(It.IsAny<Blog>()));
}
/// <summary>
/// This test makes sure we deal gracefully with a common deployment problem.
/// A user sets up the blog on his/her local machine (aka "localhost"), then
/// deploys the database to their production server. The hostname in the db
/// should be changed to the new domain.
/// </summary>
[Test]
public void
RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithLocalHostButNotMatchingSubfolder_ReturnsUpdatesItsHostThenRedirectsToSubfolder
()
{
//arrange
var onlyBlog = new Blog { Host = "localhost", Subfolder = "sub" };
var pagedCollection = new PagedCollection<Blog> { onlyBlog };
pagedCollection.MaxItems = 1;
var repository = new Mock<ObjectRepository>();
repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
pagedCollection);
var appSettings = new NameValueCollection();
appSettings.Add("AggregateEnabled", "false");
var hostInfo = new HostInfo(appSettings);
var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(() => hostInfo));
var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false);
//act
BlogLookupResult result = service.Lookup(blogRequest);
//assert
Assert.IsNull(result.Blog);
Assert.IsNotNull(result.AlternateUrl);
Assert.AreEqual("http://example.com/sub/foo/bar", result.AlternateUrl.ToString());
Assert.AreEqual("example.com", onlyBlog.Host);
repository.Verify(r => r.UpdateBlog(It.IsAny<Blog>()));
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
namespace XenAdmin.Controls
{
partial class MultiSelectTreeView
{
public sealed class MultiSelectTreeSelectedNodeCollection : IList<MultiSelectTreeNode>
{
private readonly MultiSelectTreeView _parent;
public MultiSelectTreeSelectedNodeCollection(MultiSelectTreeView parent)
{
Util.ThrowIfParameterNull(parent, "parent");
_parent = parent;
}
public void SetContents(IEnumerable<MultiSelectTreeNode> items)
{
Util.ThrowIfParameterNull(items, "items");
IList<MultiSelectTreeNode> itemsAsList = items as IList<MultiSelectTreeNode>;
int itemsCount = itemsAsList != null ? itemsAsList.Count : (new List<MultiSelectTreeNode>(items).Count);
bool different = itemsCount != Count;
if (!different)
{
List<MultiSelectTreeNode> existing = new List<MultiSelectTreeNode>(this);
// check if contents are different.
foreach (MultiSelectTreeNode node in items)
{
int index = existing.IndexOf(node);
if (index < 0)
{
different = true;
break;
}
else
{
existing.RemoveAt(index);
}
}
different |= existing.Count > 0;
}
if (different)
{
_parent._selectionChanged = false;
_parent.UnselectAllNodes(TreeViewAction.Unknown);
foreach (MultiSelectTreeNode item in items)
{
_parent.SelectNode(item, true, TreeViewAction.Unknown);
}
_parent.OnSelectionsChanged();
}
}
#region IList<TreeNode> Members
public int IndexOf(MultiSelectTreeNode item)
{
return _parent._selectedNodes.IndexOf(item);
}
public void Insert(int index, MultiSelectTreeNode item)
{
_parent._selectionChanged = false;
_parent.SelectNode(item, true, TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
}
public void RemoveAt(int index)
{
MultiSelectTreeNode item = _parent._selectedNodes[index];
_parent._selectionChanged = false;
_parent.SelectNode(item, false, TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
}
public MultiSelectTreeNode this[int index]
{
get
{
return _parent._selectedNodes[index];
}
set
{
throw new InvalidOperationException();
}
}
#endregion
#region ICollection<TreeNode> Members
public void Add(MultiSelectTreeNode item)
{
_parent._selectionChanged = false;
_parent.SelectNode(item, true, TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
}
public void Clear()
{
_parent._selectionChanged = false;
_parent.UnselectAllNodes(TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
}
public bool Contains(MultiSelectTreeNode item)
{
return _parent._selectedNodes.Contains(item);
}
public void CopyTo(MultiSelectTreeNode[] array, int arrayIndex)
{
_parent._selectedNodes.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _parent._selectedNodes.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(MultiSelectTreeNode item)
{
bool ret = Contains(item);
_parent._selectionChanged = false;
_parent.SelectNode(item, false, TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
return ret;
}
#endregion
#region IEnumerable<MultiSelectTreeNode> Members
public IEnumerator<MultiSelectTreeNode> GetEnumerator()
{
return _parent._selectedNodes.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
private class InternalSelectedNodeCollection : Collection<MultiSelectTreeNode>
{
protected override void ClearItems()
{
List<MultiSelectTreeNode> nodes = new List<MultiSelectTreeNode>(this);
base.ClearItems();
foreach (MultiSelectTreeNode node in nodes)
{
((IMultiSelectTreeNode)node).SetSelected(false);
}
}
protected override void InsertItem(int index, MultiSelectTreeNode item)
{
base.InsertItem(index, item);
((IMultiSelectTreeNode)item).SetSelected(true);
}
protected override void RemoveItem(int index)
{
MultiSelectTreeNode node = this[index];
base.RemoveItem(index);
((IMultiSelectTreeNode)node).SetSelected(false);
}
protected override void SetItem(int index, MultiSelectTreeNode item)
{
MultiSelectTreeNode toRemove = this[index];
base.SetItem(index, item);
((IMultiSelectTreeNode)toRemove).SetSelected(false);
((IMultiSelectTreeNode)item).SetSelected(true);
}
}
}
}
| |
/*
* 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 log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Grid
{
public class GridServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IGridService m_GridService;
public GridServerPostHandler(IGridService service) :
base("POST", "/grid")
{
m_GridService = service;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
switch (method)
{
case "register":
return Register(request);
case "deregister":
return Deregister(request);
case "get_neighbours":
return GetNeighbours(request);
case "get_region_by_uuid":
return GetRegionByUUID(request);
case "get_region_by_position":
return GetRegionByPosition(request);
case "get_region_by_name":
return GetRegionByName(request);
case "get_regions_by_name":
return GetRegionsByName(request);
case "get_region_range":
return GetRegionRange(request);
case "get_default_regions":
return GetDefaultRegions(request);
case "get_fallback_regions":
return GetFallbackRegions(request);
case "get_hyperlinks":
return GetHyperlinks(request);
case "get_region_flags":
return GetRegionFlags(request);
}
m_log.DebugFormat("[GRID HANDLER]: unknown method {0} request {1}", method.Length, method);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID HANDLER]: Exception {0}", e);
}
return FailureResult();
}
#region Method-specific handlers
byte[] Register(Dictionary<string, object> request)
{
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to register region");
int versionNumberMin = 0, versionNumberMax = 0;
if (request.ContainsKey("VERSIONMIN"))
Int32.TryParse(request["VERSIONMIN"].ToString(), out versionNumberMin);
else
m_log.WarnFormat("[GRID HANDLER]: no minimum protocol version in request to register region");
if (request.ContainsKey("VERSIONMAX"))
Int32.TryParse(request["VERSIONMAX"].ToString(), out versionNumberMax);
else
m_log.WarnFormat("[GRID HANDLER]: no maximum protocol version in request to register region");
// Check the protocol version
if ((versionNumberMin > ProtocolVersions.ServerProtocolVersionMax && versionNumberMax < ProtocolVersions.ServerProtocolVersionMax))
{
// Can't do, there is no overlap in the acceptable ranges
return FailureResult();
}
Dictionary<string, object> rinfoData = new Dictionary<string, object>();
GridRegion rinfo = null;
try
{
foreach (KeyValuePair<string, object> kvp in request)
rinfoData[kvp.Key] = kvp.Value.ToString();
rinfo = new GridRegion(rinfoData);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID HANDLER]: exception unpacking region data: {0}", e);
}
string result = "Error communicating with grid service";
if (rinfo != null)
result = m_GridService.RegisterRegion(scopeID, rinfo);
if (result == String.Empty)
return SuccessResult();
else
return FailureResult(result);
}
byte[] Deregister(Dictionary<string, object> request)
{
UUID regionID = UUID.Zero;
if (request.ContainsKey("REGIONID"))
UUID.TryParse(request["REGIONID"].ToString(), out regionID);
else
m_log.WarnFormat("[GRID HANDLER]: no regionID in request to deregister region");
bool result = m_GridService.DeregisterRegion(regionID);
if (result)
return SuccessResult();
else
return FailureResult();
}
byte[] GetNeighbours(Dictionary<string, object> request)
{
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours");
UUID regionID = UUID.Zero;
if (request.ContainsKey("REGIONID"))
UUID.TryParse(request["REGIONID"].ToString(), out regionID);
else
m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours");
List<GridRegion> rinfos = m_GridService.GetNeighbours(scopeID, regionID);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionByUUID(Dictionary<string, object> request)
{
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours");
UUID regionID = UUID.Zero;
if (request.ContainsKey("REGIONID"))
UUID.TryParse(request["REGIONID"].ToString(), out regionID);
else
m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours");
GridRegion rinfo = m_GridService.GetRegionByUUID(scopeID, regionID);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if (rinfo == null)
result["result"] = "null";
else
result["result"] = rinfo.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionByPosition(Dictionary<string, object> request)
{
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by position");
int x = 0, y = 0;
if (request.ContainsKey("X"))
Int32.TryParse(request["X"].ToString(), out x);
else
m_log.WarnFormat("[GRID HANDLER]: no X in request to get region by position");
if (request.ContainsKey("Y"))
Int32.TryParse(request["Y"].ToString(), out y);
else
m_log.WarnFormat("[GRID HANDLER]: no Y in request to get region by position");
GridRegion rinfo = m_GridService.GetRegionByPosition(scopeID, x, y);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if (rinfo == null)
result["result"] = "null";
else
result["result"] = rinfo.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionByName(Dictionary<string, object> request)
{
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by name");
string regionName = string.Empty;
if (request.ContainsKey("NAME"))
regionName = request["NAME"].ToString();
else
m_log.WarnFormat("[GRID HANDLER]: no name in request to get region by name");
GridRegion rinfo = m_GridService.GetRegionByName(scopeID, regionName);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if (rinfo == null)
result["result"] = "null";
else
result["result"] = rinfo.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionsByName(Dictionary<string, object> request)
{
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get regions by name");
string regionName = string.Empty;
if (request.ContainsKey("NAME"))
regionName = request["NAME"].ToString();
else
m_log.WarnFormat("[GRID HANDLER]: no NAME in request to get regions by name");
int max = 0;
if (request.ContainsKey("MAX"))
Int32.TryParse(request["MAX"].ToString(), out max);
else
m_log.WarnFormat("[GRID HANDLER]: no MAX in request to get regions by name");
List<GridRegion> rinfos = m_GridService.GetRegionsByName(scopeID, regionName, max);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionRange(Dictionary<string, object> request)
{
//m_log.DebugFormat("[GRID HANDLER]: GetRegionRange");
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range");
int xmin = 0, xmax = 0, ymin = 0, ymax = 0;
if (request.ContainsKey("XMIN"))
Int32.TryParse(request["XMIN"].ToString(), out xmin);
else
m_log.WarnFormat("[GRID HANDLER]: no XMIN in request to get region range");
if (request.ContainsKey("XMAX"))
Int32.TryParse(request["XMAX"].ToString(), out xmax);
else
m_log.WarnFormat("[GRID HANDLER]: no XMAX in request to get region range");
if (request.ContainsKey("YMIN"))
Int32.TryParse(request["YMIN"].ToString(), out ymin);
else
m_log.WarnFormat("[GRID HANDLER]: no YMIN in request to get region range");
if (request.ContainsKey("YMAX"))
Int32.TryParse(request["YMAX"].ToString(), out ymax);
else
m_log.WarnFormat("[GRID HANDLER]: no YMAX in request to get region range");
List<GridRegion> rinfos = m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetDefaultRegions(Dictionary<string, object> request)
{
//m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions");
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range");
List<GridRegion> rinfos = m_GridService.GetDefaultRegions(scopeID);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetFallbackRegions(Dictionary<string, object> request)
{
//m_log.DebugFormat("[GRID HANDLER]: GetRegionRange");
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get fallback regions");
int x = 0, y = 0;
if (request.ContainsKey("X"))
Int32.TryParse(request["X"].ToString(), out x);
else
m_log.WarnFormat("[GRID HANDLER]: no X in request to get fallback regions");
if (request.ContainsKey("Y"))
Int32.TryParse(request["Y"].ToString(), out y);
else
m_log.WarnFormat("[GRID HANDLER]: no Y in request to get fallback regions");
List<GridRegion> rinfos = m_GridService.GetFallbackRegions(scopeID, x, y);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetHyperlinks(Dictionary<string, object> request)
{
//m_log.DebugFormat("[GRID HANDLER]: GetHyperlinks");
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get linked regions");
List<GridRegion> rinfos = m_GridService.GetHyperlinks(scopeID);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionFlags(Dictionary<string, object> request)
{
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours");
UUID regionID = UUID.Zero;
if (request.ContainsKey("REGIONID"))
UUID.TryParse(request["REGIONID"].ToString(), out regionID);
else
m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours");
int flags = m_GridService.GetRegionFlags(scopeID, regionID);
// m_log.DebugFormat("[GRID HANDLER]: flags for region {0}: {1}", regionID, flags);
Dictionary<string, object> result = new Dictionary<string, object>();
result["result"] = flags.ToString();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
#endregion
#region Misc
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] FailureResult()
{
return FailureResult(String.Empty);
}
private byte[] FailureResult(string msg)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
XmlElement message = doc.CreateElement("", "Message", "");
message.AppendChild(doc.CreateTextNode(msg));
rootElement.AppendChild(message);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Descriptors.ShapePlacementStrategy;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
using OrchardCore.Placements.Services;
using OrchardCore.Placements.ViewModels;
using OrchardCore.Routing;
using OrchardCore.Settings;
namespace OrchardCore.Placements.Controllers
{
public class AdminController : Controller
{
private readonly ILogger _logger;
private readonly IAuthorizationService _authorizationService;
private readonly PlacementsManager _placementsManager;
private readonly IHtmlLocalizer H;
private readonly IStringLocalizer S;
private readonly INotifier _notifier;
private readonly ISiteService _siteService;
private readonly dynamic New;
public AdminController(
ILogger<AdminController> logger,
IAuthorizationService authorizationService,
PlacementsManager placementsManager,
IHtmlLocalizer<AdminController> htmlLocalizer,
IStringLocalizer<AdminController> stringLocalizer,
INotifier notifier,
ISiteService siteService,
IShapeFactory shapeFactory)
{
_logger = logger;
_authorizationService = authorizationService;
_placementsManager = placementsManager;
_notifier = notifier;
_siteService = siteService;
New = shapeFactory;
H = htmlLocalizer;
S = stringLocalizer;
}
public async Task<IActionResult> Index(ContentOptions options, PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
var shapeTypes = await _placementsManager.ListShapePlacementsAsync();
var shapeList = shapeTypes.Select(entry => new ShapePlacementViewModel
{
ShapeType = entry.Key
}).ToList();
if (!string.IsNullOrWhiteSpace(options.Search))
{
shapeList = shapeList.Where(x => x.ShapeType.Contains(options.Search, StringComparison.OrdinalIgnoreCase)).ToList();
}
var count = shapeList.Count();
shapeList = shapeList.OrderBy(x => x.ShapeType)
.Skip(pager.GetStartIndex())
.Take(pager.PageSize).ToList();
var pagerShape = (await New.Pager(pager)).TotalItemCount(count);
var model = new ListShapePlacementsViewModel
{
ShapePlacements = shapeList,
Pager = pagerShape,
Options = options,
};
model.Options.ContentsBulkAction = new List<SelectListItem>() {
new SelectListItem() { Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove) }
};
return View("Index", model);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.Filter")]
public ActionResult IndexFilterPOST(ListShapePlacementsViewModel model)
{
return RedirectToAction(nameof(Index), new RouteValueDictionary {
{ "Options.Search", model.Options.Search }
});
}
public async Task<IActionResult> Create(string suggestion, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}
var template = new PlacementNode[] { new PlacementNode() };
var viewModel = new EditShapePlacementViewModel
{
Creating = true,
ShapeType = suggestion,
Nodes = JsonConvert.SerializeObject(template, Formatting.Indented)
};
ViewData["ReturnUrl"] = returnUrl;
return View("Edit", viewModel);
}
public async Task<IActionResult> Edit(string shapeType, string displayType = null, string contentType = null, string contentPart = null, string differentiator = null, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}
var placementNodes = (await _placementsManager.GetShapePlacementsAsync(shapeType))?.ToList() ?? new List<PlacementNode>();
if (!placementNodes.Any() || ShouldCreateNode(placementNodes, displayType, contentType, contentPart, differentiator))
{
var generatedNode = new PlacementNode
{
DisplayType = displayType,
Differentiator = differentiator
};
if (!string.IsNullOrEmpty(contentType))
{
generatedNode.Filters.Add("contentType", new JArray(contentType));
}
if (!string.IsNullOrEmpty(contentPart))
{
generatedNode.Filters.Add("contentPart", new JArray(contentPart));
}
placementNodes.Add(generatedNode);
}
var viewModel = new EditShapePlacementViewModel
{
ShapeType = shapeType,
Nodes = JsonConvert.SerializeObject(placementNodes, Formatting.Indented)
};
ViewData["ReturnUrl"] = returnUrl;
return View(viewModel);
}
[HttpPost, ActionName("Edit")]
public async Task<IActionResult> Edit(EditShapePlacementViewModel viewModel, string submit, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}
ViewData["ReturnUrl"] = returnUrl;
if (viewModel.Creating && await _placementsManager.GetShapePlacementsAsync(viewModel.ShapeType) != null)
{
// Prevent overriding existing rules on creation
await _notifier.WarningAsync(H["Placement rules for \"{0}\" already exists. Please edit existing rule.", viewModel.ShapeType]);
return View(viewModel);
}
try
{
IEnumerable<PlacementNode> placementNodes = JsonConvert.DeserializeObject<PlacementNode[]>(viewModel.Nodes) ?? new PlacementNode[0];
// Remove empty nodes
placementNodes = placementNodes.Where(node => !IsEmpty(node));
if (placementNodes.Any())
{
// Save
await _placementsManager.UpdateShapePlacementsAsync(viewModel.ShapeType, placementNodes);
viewModel.Creating = false;
await _notifier.SuccessAsync(H["The \"{0}\" placement have been saved.", viewModel.ShapeType]);
}
else if (viewModel.Creating)
{
await _notifier.WarningAsync(H["The \"{0}\" placement is empty.", viewModel.ShapeType]);
return View(viewModel);
}
else
{
// Remove if empty
await _placementsManager.RemoveShapePlacementsAsync(viewModel.ShapeType);
await _notifier.SuccessAsync(H["The \"{0}\" placement has been deleted.", viewModel.ShapeType]);
}
}
catch (JsonReaderException jsonException)
{
await _notifier.ErrorAsync(H["An error occurred while parsing the placement<br/>{0}", jsonException.Message]);
return View(viewModel);
}
catch (Exception e)
{
await _notifier.ErrorAsync(H["An error occurred while saving the placement."]);
_logger.LogError(e, "An error occurred while saving the placement.");
return View(viewModel);
}
if (submit != "SaveAndContinue")
{
return RedirectToReturnUrlOrIndex(returnUrl);
}
return View(viewModel);
}
[HttpPost, ActionName("Delete")]
public async Task<IActionResult> Delete(string shapeType, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}
await _placementsManager.RemoveShapePlacementsAsync(shapeType);
await _notifier.SuccessAsync(H["The \"{0}\" placement has been deleted.", shapeType]);
return RedirectToReturnUrlOrIndex(returnUrl);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.BulkAction")]
public async Task<ActionResult> IndexPost(ViewModels.ContentOptions options, IEnumerable<string> itemIds)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}
if (itemIds?.Count() > 0)
{
switch (options.BulkAction)
{
case ContentsBulkAction.None:
break;
case ContentsBulkAction.Remove:
foreach (var item in itemIds)
{
await _placementsManager.RemoveShapePlacementsAsync(item);
}
await _notifier.SuccessAsync(H["Placements successfully removed."]);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return RedirectToAction(nameof(Index));
}
private IActionResult RedirectToReturnUrlOrIndex(string returnUrl)
{
if ((String.IsNullOrEmpty(returnUrl) == false) && (Url.IsLocalUrl(returnUrl)))
{
return this.Redirect(returnUrl, true);
}
else
{
return RedirectToAction(nameof(Index));
}
}
private static bool ShouldCreateNode(IEnumerable<PlacementNode> nodes, string displayType, string contentType, string contentPart, string differentiator)
{
if (string.IsNullOrEmpty(displayType) && string.IsNullOrEmpty(differentiator))
{
return false;
}
else
{
return !nodes.Any(node =>
(string.IsNullOrEmpty(displayType) || node.DisplayType == displayType) &&
(string.IsNullOrEmpty(contentType) || (node.Filters.ContainsKey("contentType") && FilterEquals(node.Filters["contentType"], contentType))) &&
(string.IsNullOrEmpty(contentPart) || (node.Filters.ContainsKey("contentPart") && FilterEquals(node.Filters["contentPart"], contentPart))) &&
(string.IsNullOrEmpty(differentiator) || node.Differentiator == differentiator));
}
}
private static bool IsEmpty(PlacementNode node)
{
return string.IsNullOrEmpty(node.Location)
&& string.IsNullOrEmpty(node.ShapeType)
&& (node.Alternates == null || node.Alternates.Length == 0)
&& (node.Wrappers == null || node.Wrappers.Length == 0);
}
private static bool FilterEquals(JToken token, string value)
{
if (token is JArray)
{
var tokenValues = token.Values<string>();
return tokenValues.Count() == 1 && tokenValues.First() == value;
}
else
{
return token.Value<string>() == value;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// ReSharper disable UnusedMember.Global
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
namespace System.Management.Automation
{
internal static class ArrayOps
{
internal static object[] SlicingIndex(object target, object[] indexes, Func<object, object, object> indexer)
{
var result = new object[indexes.Length];
int j = 0;
foreach (object t in indexes)
{
var value = indexer(target, t);
if (value != AutomationNull.Value)
{
result[j++] = value;
}
}
if (j != indexes.Length)
{
var shortResult = new object[j];
Array.Copy(result, shortResult, j);
return shortResult;
}
return result;
}
/// <summary>
/// Efficiently multiplies collection by integer.
/// </summary>
/// <param name="array">Collection to multiply.</param>
/// <param name="times">Number of times the collection is to be multiplied/copied.</param>
/// <returns>Collection multiplied by integer.</returns>
internal static T[] Multiply<T>(T[] array, uint times)
{
Diagnostics.Assert(array != null, "Caller should verify the arguments for array multiplication");
if (times == 1)
{
return array;
}
if (times == 0 || array.Length == 0)
{
return new T[0]; // don't use Utils.EmptyArray, always return a new array
}
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context != null &&
context.LanguageMode == PSLanguageMode.RestrictedLanguage && (array.Length * times) > 1024)
{
throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException),
null, "ArrayMultiplyToolongInDataSection", ParserStrings.ArrayMultiplyToolongInDataSection, 1024);
}
var uncheckedLength = array.Length * times;
int elements = -1;
try
{
elements = checked((int)uncheckedLength);
}
catch (OverflowException)
{
LanguagePrimitives.ThrowInvalidCastException(uncheckedLength, typeof(int));
}
// Make the minimum number of calls to Array.Copy by doubling the array up to
// the most significant bit in times, then do one final Array.Copy to get the
// remaining copies.
T[] result = new T[elements];
int resultLength = array.Length;
Array.Copy(array, 0, result, 0, resultLength);
times >>= 1;
while (times != 0)
{
Array.Copy(result, 0, result, resultLength, resultLength);
resultLength *= 2;
times >>= 1;
}
if (result.Length != resultLength)
{
Array.Copy(result, 0, result, resultLength, (result.Length - resultLength));
}
return result;
}
internal static object GetMDArrayValue(Array array, int[] indexes, bool slicing)
{
if (array.Rank != indexes.Length)
{
ReportIndexingError(array, indexes, null);
}
for (int i = 0; i < indexes.Length; ++i)
{
int ub = array.GetUpperBound(i);
int lb = array.GetLowerBound(i);
if (indexes[i] < lb)
{
indexes[i] = indexes[i] + ub + 1;
}
if (indexes[i] < lb || indexes[i] > ub)
{
// In strict mode, don't return, fall through and let Array.GetValue raise an exception.
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context != null && !context.IsStrictVersion(3))
{
// If we're slicing, return AutomationNull.Value to signal no result)
return slicing ? AutomationNull.Value : null;
}
}
}
// All indexes have been validated, so this won't raise an exception.
return array.GetValue(indexes);
}
internal static object GetMDArrayValueOrSlice(Array array, object indexes)
{
Exception whyFailed = null;
int[] indexArray = null;
try
{
indexArray = (int[])LanguagePrimitives.ConvertTo(indexes, typeof(int[]), NumberFormatInfo.InvariantInfo);
}
catch (InvalidCastException ice)
{
// Ignore an exception here as we may actually be looking at an array of arrays
// which could still be ok. Save the exception as we may use it later...
whyFailed = ice;
}
if (indexArray != null)
{
if (indexArray.Length != array.Rank)
{
// rank failed to match so error...
ReportIndexingError(array, indexes, null);
}
return GetMDArrayValue(array, indexArray, false);
}
var indexList = new List<int[]>();
var ie = LanguagePrimitives.GetEnumerator(indexes);
while (EnumerableOps.MoveNext(null, ie))
{
var currentIndex = EnumerableOps.Current(ie);
try
{
indexArray = LanguagePrimitives.ConvertTo<int[]>(currentIndex);
}
catch (InvalidCastException)
{
indexArray = null;
}
if (indexArray == null || indexArray.Length != array.Rank)
{
if (whyFailed != null)
{
// If the first fails, report the original exception and all indices
ReportIndexingError(array, indexes, whyFailed);
Diagnostics.Assert(false, "ReportIndexingError must throw");
}
// If the second or subsequent index fails, report the failure for just that index
ReportIndexingError(array, currentIndex, null);
Diagnostics.Assert(false, "ReportIndexingError must throw");
}
// Only use whyFailed the first time through, otherwise
whyFailed = null;
indexList.Add(indexArray);
}
// Optimistically assume all indices are valid so the result array is the same size.
// If that turns out to be wrong, we'll just copy the elements produced.
var result = new object[indexList.Count];
int j = 0;
foreach (var i in indexList)
{
var value = GetMDArrayValue(array, i, true);
if (value != AutomationNull.Value)
{
result[j++] = value;
}
}
if (j != indexList.Count)
{
var shortResult = new object[j];
Array.Copy(result, shortResult, j);
return shortResult;
}
return result;
}
private static void ReportIndexingError(Array array, object index, Exception reason)
{
// Convert this index into something printable (we hope)...
string msgString = IndexStringMessage(index);
if (reason == null)
{
throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), null,
"NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, array.Rank, msgString);
}
throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), null,
"NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, reason, array.Rank, msgString);
}
internal static string IndexStringMessage(object index)
{
// Convert this index into something printable (we hope)...
string msgString = PSObject.ToString(null, index, ",", null, null, true, true);
if (msgString.Length > 20)
msgString = msgString.Substring(0, 20) + " ...";
return msgString;
}
internal static object SetMDArrayValue(Array array, int[] indexes, object value)
{
if (array.Rank != indexes.Length)
{
ReportIndexingError(array, indexes, null);
}
for (int i = 0; i < indexes.Length; ++i)
{
int ub = array.GetUpperBound(i);
int lb = array.GetLowerBound(i);
if (indexes[i] < lb)
{
indexes[i] = indexes[i] + ub + 1;
}
}
array.SetValue(value, indexes);
return value;
}
internal static object GetNonIndexable(object target, object[] indices)
{
// We want to allow:
// $x[0]
// and
// $x[-1]
// to be the same as
// $x
// But disallow anything else:
// if in the strict mode, throw exception
// otherwise, return AutomationNull.Value to signal no result
if (indices.Length == 1)
{
var index = indices[0];
if (index != null && (LanguagePrimitives.Equals(0, index) || LanguagePrimitives.Equals(-1, index)))
{
return target;
}
}
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context == null || !context.IsStrictVersion(2))
{
return AutomationNull.Value;
}
throw InterpreterError.NewInterpreterException(target, typeof(RuntimeException), null, "CannotIndex",
ParserStrings.CannotIndex, target.GetType());
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// Remoting Infrastructure Sink for making calls across context
// boundaries.
//
namespace System.Runtime.Remoting.Channels {
using System;
using System.Collections;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
/* package scope */
// deliberately not [serializable]
internal class CrossContextChannel : InternalSink, IMessageSink
{
private const String _channelName = "XCTX";
private const int _channelCapability = 0;
private const String _channelURI = "XCTX_URI";
[System.Security.SecuritySafeCritical] // auto-generated
static CrossContextChannel()
{
}
private static CrossContextChannel messageSink
{
get { return Thread.GetDomain().RemotingData.ChannelServicesData.xctxmessageSink; }
set { Thread.GetDomain().RemotingData.ChannelServicesData.xctxmessageSink = value; }
}
private static Object staticSyncObject = new Object();
private static InternalCrossContextDelegate s_xctxDel = new InternalCrossContextDelegate(SyncProcessMessageCallback);
internal static IMessageSink MessageSink
{
get
{
if (messageSink == null)
{
CrossContextChannel tmpSink = new CrossContextChannel();
lock (staticSyncObject)
{
if (messageSink == null)
{
messageSink = tmpSink;
}
}
//Interlocked.CompareExchange(out messageSink, tmpSink, null);
}
return messageSink;
}
}
[System.Security.SecurityCritical] // auto-generated
internal static Object SyncProcessMessageCallback(Object[] args)
{
IMessage reqMsg = args[0] as IMessage;
Context srvCtx = args[1] as Context;
IMessage replyMsg = null;
// If profiling of remoting is active, must tell the profiler that we have received
// a message.
if (RemotingServices.CORProfilerTrackRemoting())
{
Guid g = Guid.Empty;
if (RemotingServices.CORProfilerTrackRemotingCookie())
{
Object obj = reqMsg.Properties["CORProfilerCookie"];
if (obj != null)
{
g = (Guid) obj;
}
}
RemotingServices.CORProfilerRemotingServerReceivingMessage(g, false);
}
Message.DebugOut("::::::::::::::::::::::::: CrossContext Channel: passing to ServerContextChain");
// Server side notifications for dynamic sinks are done
// in the x-context channel ... this is to maintain
// symmetry of the point of notification between
// the client and server context
srvCtx.NotifyDynamicSinks(
reqMsg,
false, // bCliSide
true, // bStart
false, // bAsync
true); // bNotifyGlobals
replyMsg = srvCtx.GetServerContextChain().SyncProcessMessage(reqMsg);
srvCtx.NotifyDynamicSinks(
replyMsg,
false, // bCliSide
false, // bStart
false, // bAsync
true); // bNotifyGlobals
Message.DebugOut("::::::::::::::::::::::::: CrossContext Channel: back from ServerContextChain");
// If profiling of remoting is active, must tell the profiler that we are sending a
// reply message.
if (RemotingServices.CORProfilerTrackRemoting())
{
Guid g;
RemotingServices.CORProfilerRemotingServerSendingReply(out g, false);
if (RemotingServices.CORProfilerTrackRemotingCookie())
{
replyMsg.Properties["CORProfilerCookie"] = g;
}
}
return replyMsg;
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessage SyncProcessMessage(IMessage reqMsg)
{
Object[] args = new Object[] { null, null };
IMessage replyMsg = null;
try
{
Message.DebugOut("\n::::::::::::::::::::::::: CrossContext Channel: [....] call starting");
IMessage errMsg = ValidateMessage(reqMsg);
if (errMsg != null)
{
return errMsg;
}
ServerIdentity srvID = GetServerIdentity(reqMsg);
Message.DebugOut("Got Server identity \n");
BCLDebug.Assert(null != srvID,"null != srvID");
BCLDebug.Assert(null != srvID.ServerContext, "null != srvID.ServerContext");
args[0] = reqMsg;
args[1] = srvID.ServerContext;
replyMsg = (IMessage) Thread.CurrentThread.InternalCrossContextCallback(srvID.ServerContext, s_xctxDel, args);
}
catch(Exception e)
{
Message.DebugOut("Arrgh.. XCTXSink::throwing exception " + e + "\n");
replyMsg = new ReturnMessage(e, (IMethodCallMessage)reqMsg);
if (reqMsg!=null)
{
((ReturnMessage)replyMsg).SetLogicalCallContext(
(LogicalCallContext)
reqMsg.Properties[Message.CallContextKey]);
}
}
Message.DebugOut("::::::::::::::::::::::::::: CrossContext Channel: [....] call returning!!\n");
return replyMsg;
}
[System.Security.SecurityCritical] // auto-generated
internal static Object AsyncProcessMessageCallback(Object[] args)
{
AsyncWorkItem workItem = null;
IMessage reqMsg = (IMessage) args[0];
IMessageSink replySink = (IMessageSink) args[1];
Context oldCtx = (Context) args[2];
Context srvCtx = (Context) args[3];
IMessageCtrl msgCtrl = null;
// we use the work item just as our replySink in this case
if (replySink != null)
{
workItem = new AsyncWorkItem(replySink, oldCtx);
}
Message.DebugOut("::::::::::::::::::::::::: CrossContext Channel: passing to ServerContextChain");
srvCtx.NotifyDynamicSinks(
reqMsg,
false, // bCliSide
true, // bStart
true, // bAsync
true); // bNotifyGlobals
// call the server context chain
msgCtrl =
srvCtx.GetServerContextChain().AsyncProcessMessage(
reqMsg,
(IMessageSink)workItem);
// Note: for async calls, we will do the return notification
// for dynamic properties only when the async call
// completes (i.e. when the replySink gets called)
Message.DebugOut("::::::::::::::::::::::::: CrossContext Channel: back from ServerContextChain");
return msgCtrl;
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessageCtrl AsyncProcessMessage(IMessage reqMsg, IMessageSink replySink)
{
Message.DebugOut("::::::::::::::::::::::::::: CrossContext Channel: Async call starting!!\n");
// One way Async notifications may potentially pass a null reply sink.
IMessage errMsg = ValidateMessage(reqMsg);
Object[] args = new Object[] { null, null, null, null };
IMessageCtrl msgCtrl = null;
if (errMsg != null)
{
if (replySink!=null)
{
replySink.SyncProcessMessage(errMsg);
}
}
else
{
ServerIdentity srvID = GetServerIdentity(reqMsg);
// If active, notify the profiler that an asynchronous remoting message was received.
if (RemotingServices.CORProfilerTrackRemotingAsync())
{
Guid g = Guid.Empty;
if (RemotingServices.CORProfilerTrackRemotingCookie())
{
Object obj = reqMsg.Properties["CORProfilerCookie"];
if (obj != null)
{
g = (Guid) obj;
}
}
RemotingServices.CORProfilerRemotingServerReceivingMessage(g, true);
// Only wrap the replySink if the call wants a reply
if (replySink != null)
{
// Now wrap the reply sink in our own so that we can notify the profiler of
// when the reply is sent. Upon invocation, it will notify the profiler
// then pass control on to the replySink passed in above.
IMessageSink profSink = new ServerAsyncReplyTerminatorSink(replySink);
// Replace the reply sink with our own
replySink = profSink;
}
}
Context srvCtx = srvID.ServerContext;
if (srvCtx.IsThreadPoolAware)
{
// this is the case when we do not queue the work item since the
// server context claims to be doing its own threading.
args[0] = reqMsg;
args[1] = replySink;
args[2] = Thread.CurrentContext;
args[3] = srvCtx;
InternalCrossContextDelegate xctxDel = new InternalCrossContextDelegate(AsyncProcessMessageCallback);
msgCtrl = (IMessageCtrl) Thread.CurrentThread.InternalCrossContextCallback(srvCtx, xctxDel, args);
}
else
{
AsyncWorkItem workItem = null;
// This is the case where we take care of returning the calling
// thread asap by using the ThreadPool for completing the call.
// we use a more elaborate WorkItem and delegate the work to the thread pool
workItem = new AsyncWorkItem(reqMsg,
replySink,
Thread.CurrentContext,
srvID);
WaitCallback threadFunc = new WaitCallback(workItem.FinishAsyncWork);
// Note: Dynamic sinks are notified in the threadFunc
ThreadPool.QueueUserWorkItem(threadFunc);
}
}
Message.DebugOut("::::::::::::::::::::::::::: CrossContext Channel: Async call returning!!\n");
return msgCtrl;
} // AsyncProcessMessage
[System.Security.SecurityCritical] // auto-generated
internal static Object DoAsyncDispatchCallback(Object[] args)
{
AsyncWorkItem workItem = null;
IMessage reqMsg = (IMessage) args[0];
IMessageSink replySink = (IMessageSink) args[1];
Context oldCtx = (Context) args[2];
Context srvCtx = (Context) args[3];
IMessageCtrl msgCtrl = null;
// we use the work item just as our replySink in this case
if (replySink != null)
{
workItem = new AsyncWorkItem(replySink, oldCtx);
}
Message.DebugOut("::::::::::::::::::::::::: CrossContext Channel: passing to ServerContextChain");
// call the server context chain
msgCtrl =
srvCtx.GetServerContextChain().AsyncProcessMessage(reqMsg, (IMessageSink)workItem);
Message.DebugOut("::::::::::::::::::::::::: CrossContext Channel: back from ServerContextChain");
return msgCtrl;
}
[System.Security.SecurityCritical] // auto-generated
internal static IMessageCtrl DoAsyncDispatch(IMessage reqMsg, IMessageSink replySink)
{
Object[] args = new Object[] { null, null, null, null };
ServerIdentity srvID = GetServerIdentity(reqMsg);
// If active, notify the profiler that an asynchronous remoting message was received.
if (RemotingServices.CORProfilerTrackRemotingAsync())
{
Guid g = Guid.Empty;
if (RemotingServices.CORProfilerTrackRemotingCookie())
{
Object obj = reqMsg.Properties["CORProfilerCookie"];
if (obj != null)
g = (Guid) obj;
}
RemotingServices.CORProfilerRemotingServerReceivingMessage(g, true);
// Only wrap the replySink if the call wants a reply
if (replySink != null)
{
// Now wrap the reply sink in our own so that we can notify the profiler of
// when the reply is sent. Upon invocation, it will notify the profiler
// then pass control on to the replySink passed in above.
IMessageSink profSink =
new ServerAsyncReplyTerminatorSink(replySink);
// Replace the reply sink with our own
replySink = profSink;
}
}
IMessageCtrl msgCtrl = null;
Context srvCtx = srvID.ServerContext;
//if (srvCtx.IsThreadPoolAware)
//{
// this is the case when we do not queue the work item since the
// server context claims to be doing its own threading.
args[0] = reqMsg;
args[1] = replySink;
args[2] = Thread.CurrentContext;
args[3] = srvCtx;
InternalCrossContextDelegate xctxDel = new InternalCrossContextDelegate(DoAsyncDispatchCallback);
msgCtrl = (IMessageCtrl) Thread.CurrentThread.InternalCrossContextCallback(srvCtx, xctxDel, args);
//}
return msgCtrl;
} // DoDispatch
public IMessageSink NextSink
{
[System.Security.SecurityCritical] // auto-generated
get
{
// We are a terminating sink for this chain.
return null;
}
}
}
/* package */
internal class AsyncWorkItem : IMessageSink
{
// the replySink passed in to us in AsyncProcessMsg
private IMessageSink _replySink;
// the server identity we are calling
private ServerIdentity _srvID;
// the original context of the thread calling AsyncProcessMsg
private Context _oldCtx;
[System.Security.SecurityCritical] // auto-generated
private LogicalCallContext _callCtx;
// the request msg passed in
private IMessage _reqMsg;
[System.Security.SecurityCritical] // auto-generated
internal AsyncWorkItem(IMessageSink replySink, Context oldCtx)
: this(null, replySink, oldCtx, null) {
}
[System.Security.SecurityCritical] // auto-generated
internal AsyncWorkItem(IMessage reqMsg, IMessageSink replySink, Context oldCtx, ServerIdentity srvID)
{
_reqMsg = reqMsg;
_replySink = replySink;
_oldCtx = oldCtx;
_callCtx = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
_srvID = srvID;
}
[System.Security.SecurityCritical] // auto-generated
internal static Object SyncProcessMessageCallback(Object[] args)
{
IMessageSink replySink = (IMessageSink) args[0];
IMessage msg = (IMessage) args[1];
return replySink.SyncProcessMessage(msg);
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessage SyncProcessMessage(IMessage msg)
{
// This gets called when the called object finishes the AsyncWork...
// This is called irrespective of whether we delegated the initial
// work to a thread pool thread or not. Quite likely it will be
// called on a user thread (i.e. a thread different from the
// forward call thread)
// we just switch back to the old context before calling
// the next replySink
IMessage retMsg = null;
if (_replySink != null)
{
// This assert covers the common case (ThreadPool)
// and checks that the reply thread for the async call
// indeed emerges from the server context.
BCLDebug.Assert(
(_srvID == null)
|| (_srvID.ServerContext == Thread.CurrentContext),
"Thread expected to be in the server context!");
// Call the dynamic sinks to notify that the async call
// has completed
Thread.CurrentContext.NotifyDynamicSinks(
msg, // this is the async reply
false, // bCliSide
false, // bStart
true, // bAsync
true); // bNotifyGlobals
Object[] args = new Object[] { _replySink, msg };
InternalCrossContextDelegate xctxDel = new InternalCrossContextDelegate(SyncProcessMessageCallback);
retMsg = (IMessage) Thread.CurrentThread.InternalCrossContextCallback(_oldCtx, xctxDel, args);
}
return retMsg;
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
{
// Can't call the reply sink asynchronously!
throw new NotSupportedException(
Environment.GetResourceString("NotSupported_Method"));
}
public IMessageSink NextSink
{
[System.Security.SecurityCritical] // auto-generated
get
{
return _replySink;
}
}
[System.Security.SecurityCritical] // auto-generated
internal static Object FinishAsyncWorkCallback(Object[] args)
{
AsyncWorkItem This = (AsyncWorkItem) args[0];
Context srvCtx = This._srvID.ServerContext;
LogicalCallContext threadPoolCallCtx =
CallContext.SetLogicalCallContext(This._callCtx);
// Call the server context chain Async. We provide workItem as our
// replySink ... this will cause the replySink.ProcessMessage
// to switch back to the context of the original caller thread.
// Call the dynamic sinks to notify that the async call
// is starting
srvCtx.NotifyDynamicSinks(
This._reqMsg,
false, // bCliSide
true, // bStart
true, // bAsync
true); // bNotifyGlobals
// <
IMessageCtrl ctrl =
srvCtx.GetServerContextChain().AsyncProcessMessage(
This._reqMsg,
(IMessageSink)This);
// change back to the old context
CallContext.SetLogicalCallContext(threadPoolCallCtx);
return null;
}
/* package */
[System.Security.SecurityCritical] // auto-generated
internal virtual void FinishAsyncWork(Object stateIgnored)
{
InternalCrossContextDelegate xctxDel = new InternalCrossContextDelegate(FinishAsyncWorkCallback);
Object[] args = new Object[] { this };
Thread.CurrentThread.InternalCrossContextCallback(_srvID.ServerContext, xctxDel, args);
}
}
}
| |
using System.Windows.Controls;
using DevExpress.Internal;
using DevExpress.Mvvm.UI.Native;
using NUnit.Framework;
using System;
using System.IO.Packaging;
using System.Linq;
using System.Security.Permissions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace DevExpress.Mvvm.UI.Tests {
[TestFixture]
public class NotificationTests {
[TearDown]
public void TearDown() {
if(CustomNotifier.positioner != null) {
Assert.AreEqual(0, CustomNotifier.positioner.Items.Count(i => i != null));
}
}
[Test]
public void PositionerTest() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 3);
Point p;
Assert.AreEqual(true, pos.HasEmptySlot());
p = pos.Add("item1", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20, p.Y);
p = pos.Add("item2", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20 + 50 + 10, p.Y);
p = pos.Add("item3", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20 + 50 + 10 + 50 + 10, p.Y);
Assert.AreEqual(false, pos.HasEmptySlot());
pos.Remove("item2");
p = pos.Add("item4", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20 + 50 + 10, p.Y);
pos.Remove("item3");
p = pos.Add("item5", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20 + 50 + 10 + 50 + 10, p.Y);
Assert.AreEqual(false, pos.HasEmptySlot());
pos.Remove("item1");
Assert.AreEqual(true, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.BottomRight, 3);
p = pos.Add("item1", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20, p.Y);
p = pos.Add("item2", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20 - 50 - 10, p.Y);
p = pos.Add("item3", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20 - 50 - 10 - 50 - 10, p.Y);
Assert.AreEqual(false, pos.HasEmptySlot());
pos.Remove("item2");
p = pos.Add("item4", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20 - 50 - 10, p.Y);
pos.Remove("item3");
p = pos.Add("item5", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20 - 50 - 10 - 50 - 10, p.Y);
Assert.AreEqual(false, pos.HasEmptySlot());
pos.Remove("item1");
Assert.AreEqual(true, pos.HasEmptySlot());
}
[Test]
public void PositionerTest2() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 480);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 460);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 250), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 100);
pos.Add("item1", 200, 100);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 360), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 100);
pos.Add("item1", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
}
[Test]
public void PositionerTest3() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(10, 25, 790, 575), NotificationPosition.TopRight, 100);
Point p = pos.Add("item1", 200, 100);
Assert.AreEqual(10 + 790 - 200, p.X);
Assert.AreEqual(25 + 20, p.Y);
pos = new NotificationPositioner<string>();
pos.Update(new Rect(10, 25, 790, 575), NotificationPosition.BottomRight, 100);
p = pos.Add("item1", 200, 100);
Assert.AreEqual(10 + 790 - 200, p.X);
Assert.AreEqual(600 - 20 - 100, p.Y);
}
[Test]
public void PositionerTest4() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 480);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 460);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 300), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 100);
pos.Add("item1", 200, 100);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 410), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 100);
pos.Add("item1", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
}
[Test]
public void PositionerHasSlotTest() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 3);
pos.Add("item1", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
pos.Remove("item1");
Assert.AreEqual(true, pos.HasEmptySlot());
pos.Add("item2", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
pos.Add("item3", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
pos.Add("item4", 200, 100);
Assert.AreEqual(false, pos.HasEmptySlot());
}
static void WaitWithDispatcher(Task<NotificationResult> task) {
while(task.Status != TaskStatus.RanToCompletion && task.Status != TaskStatus.Faulted) {
DispatcherUtil.DoEvents();
}
}
public static class DispatcherUtil {
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents() {
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
System.Windows.Forms.Application.DoEvents();
}
private static object ExitFrame(object frame) {
((DispatcherFrame)frame).Continue = false;
return null;
}
}
[Test]
public void ResultsTest() {
CustomNotification toast;
Task<NotificationResult> task;
var notifier = new CustomNotifier();
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.TimedOut, task.Result);
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
toast.Activate();
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.Activated, task.Result);
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
toast.Dismiss();
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.UserCanceled, task.Result);
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
toast.Hide();
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.ApplicationHidden, task.Result);
var tasks = Enumerable.Range(0, 10).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void UpdatingPositionerTest() {
CustomNotification toast;
Task<NotificationResult> task;
var notifier = new CustomNotifier();
var tasks = Enumerable.Range(0, 5).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
notifier.UpdatePositioner(NotificationPosition.TopRight, 2);
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.TimedOut, task.Result);
tasks = Enumerable.Range(0, 10).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
notifier.UpdatePositioner(NotificationPosition.TopRight, 2);
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void ShowingTooManyToastsTest() {
var notifier = new CustomNotifier();
notifier.UpdatePositioner(NotificationPosition.TopRight, 100);
var tasks = Enumerable.Range(0, 100).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void SettingApplicationIDToNullTest() {
var service = new NotificationService();
service.ApplicationId = "";
service.ApplicationId = null;
Assert.IsTrue(true);
}
[Test]
public void RemovePostponedNotificationTest() {
var notifier = new CustomNotifier();
notifier.UpdatePositioner(NotificationPosition.TopRight, 1);
var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();
toasts[2].Hide();
tasks.ToList().ForEach(WaitWithDispatcher);
Assert.AreEqual(NotificationResult.TimedOut, tasks[0].Result);
Assert.AreEqual(NotificationResult.TimedOut, tasks[1].Result);
Assert.AreEqual(NotificationResult.ApplicationHidden, tasks[2].Result);
}
class TestScreen : IScreen {
public Rect bounds;
public Rect GetWorkingArea() {
return bounds;
}
public void Changed() {
if(WorkingAreaChanged != null)
WorkingAreaChanged();
}
public event Action WorkingAreaChanged;
}
[Test]
public void BasicResolutionChangedHandlingTest() {
var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
var notifier = new CustomNotifier(testScreen);
notifier.UpdatePositioner(NotificationPosition.BottomRight, 2);
var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();
var pos = CustomNotifier.positioner;
var ps = pos.Items.Select(i => pos.GetItemPosition(i)).ToList();
Assert.AreEqual(new Point(615, 390), ps[0]);
Assert.AreEqual(new Point(615, 290), ps[1]);
testScreen.bounds = new Rect(0, 0, 800, 600);
testScreen.Changed();
pos = CustomNotifier.positioner;
ps = pos.Items.Select(i => pos.GetItemPosition(i)).ToList();
Assert.AreEqual(new Point(415, 490), ps[0]);
Assert.AreEqual(new Point(415, 390), ps[1]);
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void NotificationsArentLostOnPositionerUpdateTest() {
var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
var notifier1 = new CustomNotifier(testScreen);
var notifier2 = new CustomNotifier(testScreen);
var positioner = CustomNotifier.positioner;
notifier1.UpdatePositioner(NotificationPosition.BottomRight, 5);
var toasts1 = Enumerable.Range(0, 1).Select(_ => new CustomNotification(null, notifier1)).ToList();
var toasts2 = Enumerable.Range(0, 1).Select(_ => new CustomNotification(null, notifier2)).ToList();
var tasks1 = toasts1.Select(toast => notifier1.ShowAsync(toast, 1)).ToList();
var tasks2 = toasts2.Select(toast => notifier2.ShowAsync(toast, 1)).ToList();
tasks1.Union(tasks2).ToList().ForEach(WaitWithDispatcher);
tasks1.Union(tasks2).ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void UpdatePositionerTest() {
var testScreen = new TestScreen { bounds = new Rect(0, 0, 800, 600) };
var notifier = new CustomNotifier(testScreen);
var pos = CustomNotifier.positioner;
var toast = new CustomNotification(null, notifier);
var task = notifier.ShowAsync(toast, 1);
var p1 = CustomNotifier.positioner.GetItemPosition(CustomNotifier.positioner.Items[0]);
Assert.AreEqual(415, p1.X);
Assert.AreEqual(20, p1.Y);
notifier.UpdatePositioner(NotificationPosition.BottomRight, 3);
p1 = CustomNotifier.positioner.GetItemPosition(CustomNotifier.positioner.Items[0]);
Assert.AreEqual(415, p1.X);
Assert.AreEqual(490, p1.Y);
WaitWithDispatcher(task);
}
[Test]
public void ResolutionChangingTest() {
var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
var notifier = new CustomNotifier(testScreen);
notifier.UpdatePositioner(NotificationPosition.BottomRight, 2);
var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();
Assert.AreEqual(2, CustomNotifier.positioner.Items.Count(i => i != null));
testScreen.bounds = new Rect(0, 0, 800, 600);
testScreen.Changed();
Assert.AreEqual(2, CustomNotifier.positioner.Items.Count(i => i != null));
tasks.ToList().ForEach(WaitWithDispatcher);
}
[Test]
public void PositionUpdateTest() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 3);
Point p;
p = pos.Add("item1", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20, p.Y);
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.BottomRight, 3);
p = pos.GetItemPosition("item1");
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 20 - 50, p.Y);
}
[Test]
public void GetBackgroundTest() {
string _ = PackUriHelper.UriSchemePack;
Action<byte, byte, byte, string> assertMatch = (r, g, b, icon) => {
string path = string.Format("pack://application:,,,/{0};component/Icons/{1}", "DevExpress.Mvvm.Tests.Free", icon);
Uri uri = new Uri(path, UriKind.Absolute);
var bmp = new System.Drawing.Bitmap(Application.GetResourceStream(uri).Stream);
Assert.AreEqual(System.Windows.Media.Color.FromRgb(r, g, b), BackgroundCalculator.GetBestMatch(bmp));
};
assertMatch(9, 74, 178, "icon1.ico");
assertMatch(210, 71, 38, "icon2.ico");
assertMatch(81, 51, 171, "icon3.ico");
assertMatch(210, 71, 38, "icon4.ico");
assertMatch(81, 51, 171, "icon5.ico");
assertMatch(0, 130, 153, "icon6.ico");
assertMatch(9, 74, 178, "icon7.ico");
}
[Test]
public void ThrowOnApplicationIDNullTest() {
var service = new NotificationService();
if(!service.AreWin8NotificationsAvailable)
return;
try {
service.CreatePredefinedNotification("", "", "");
Assert.Fail();
} catch(ArgumentNullException e) {
Assert.AreEqual("ApplicationId", e.ParamName);
}
}
[Test]
public void UpdateCustomToastPositionTest() {
var service = new NotificationService();
var toast = service.CreateCustomNotification(null);
Assert.AreEqual(NotificationPosition.TopRight, CustomNotifier.positioner.position);
service.CustomNotificationPosition = NotificationPosition.BottomRight;
Assert.AreEqual(NotificationPosition.BottomRight, CustomNotifier.positioner.position);
service = new NotificationService();
service.CustomNotificationPosition = NotificationPosition.BottomRight;
toast = service.CreateCustomNotification(null);
Assert.AreEqual(NotificationPosition.BottomRight, CustomNotifier.positioner.position);
service.CustomNotificationPosition = NotificationPosition.TopRight;
Assert.AreEqual(NotificationPosition.TopRight, CustomNotifier.positioner.position);
}
[Test]
public void ResettingTimerOfHiddenNotificationTest() {
var customNotifier = new CustomNotifier(new TestScreen());
var toast = new CustomNotification(null, customNotifier);
customNotifier.ShowAsync(toast);
customNotifier.Hide(toast);
customNotifier.ResetTimer(toast);
customNotifier.StopTimer(toast);
}
class TestTemplateSelector : DataTemplateSelector {
public bool Called = false;
public override DataTemplate SelectTemplate(object item, DependencyObject container) {
Called = true;
return base.SelectTemplate(item, container);
}
}
[Test]
public void CustomNotificationTemplateSelectorTest() {
var customNotifier = new CustomNotifier(new TestScreen { bounds = new Rect(0, 0, 1000, 500) });
var selector = new TestTemplateSelector();
customNotifier.ContentTemplateSelector = selector;
var toast = new CustomNotification(null, customNotifier);
WaitWithDispatcher(customNotifier.ShowAsync(toast, 1));
Assert.IsTrue(selector.Called);
}
[Test]
public void ThrowOnAutoHeight() {
var style = new Style();
style.Setters.Add(new Setter(FrameworkElement.HeightProperty, double.NaN));
var service = new NotificationService();
service.CustomNotificationStyle = style;
var toast = service.CreateCustomNotification(null);
try {
toast.ShowAsync();
Assert.Fail();
} catch(InvalidOperationException) { }
}
[Test]
public void ConvertTimeSpanToMilliseconds() {
var service = new NotificationService();
service.CustomNotificationDuration = TimeSpan.MaxValue;
var toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(int.MaxValue, toast.duration);
service.CustomNotificationDuration = TimeSpan.MinValue;
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(0, toast.duration);
service.CustomNotificationDuration = TimeSpan.FromMilliseconds((double)int.MaxValue + int.MaxValue);
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(int.MaxValue, toast.duration);
service.CustomNotificationDuration = TimeSpan.FromMilliseconds(int.MaxValue);
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(int.MaxValue, toast.duration);
service.CustomNotificationDuration = TimeSpan.FromMilliseconds(150);
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(150, toast.duration);
service.CustomNotificationDuration = TimeSpan.FromMilliseconds(1);
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(1, toast.duration);
}
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Globalization.CalendarTests
{
// GregorianCalendar.GetWeekOfYears(DateTime, CalendarWeekRule, DayOfWeek)
public class GregorianCalendarGetWeekOfYears
{
private const int c_DAYS_PER_WEEK = 7;
private static readonly int[] s_daysInMonth365 =
{
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
private static readonly int[] s_daysInMonth366 =
{
0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
#region Positive tests
// PosTest1: leap year, any month other than February and any day
[Fact]
public void PosTest1()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month, day;
CalendarWeekRule rule;
DayOfWeek firstDayOfWeek;
rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
year = GetALeapYear(myCalendar);
//Get a random value beween 1 and 12 not including 2.
do
{
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
} while (2 == month);
//Get a day beween 1 and last day of the month
day = TestLibrary.Generator.GetInt32(-55) % s_daysInMonth366[month] + 1;
ExecutePosTest("001", "002", myCalendar, year, month, day, rule, firstDayOfWeek);
}
// PosTest2: leap year, any day in February
[Fact]
public void PosTest2()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month, day;
CalendarWeekRule rule;
DayOfWeek firstDayOfWeek;
year = GetALeapYear(myCalendar);
month = 2;
//Get a day beween 1 and the last day of the month
day = TestLibrary.Generator.GetInt32(-55) % s_daysInMonth366[month] + 1;
rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
ExecutePosTest("003", "004", myCalendar, year, month, day, rule, firstDayOfWeek);
}
// PosTest3: common year, February, any day
[Fact]
public void PosTest3()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month, day;
CalendarWeekRule rule;
DayOfWeek firstDayOfWeek;
year = GetACommonYear(myCalendar);
month = 2;
//Get a day beween 1 and the last day of the month
day = TestLibrary.Generator.GetInt32(-55) % s_daysInMonth365[month] + 1;
rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
ExecutePosTest("005", "006", myCalendar, year, month, day, rule, firstDayOfWeek);
}
// PosTest4: common year, any day in any month other than February
[Fact]
public void PosTest4()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month, day;
CalendarWeekRule rule;
DayOfWeek firstDayOfWeek;
year = GetACommonYear(myCalendar);
//Get a random value beween 1 and 12 not including 2.
do
{
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
}
while (2 == month);
//Get a day beween 1 and the last day of the month
day = TestLibrary.Generator.GetInt32(-55) % s_daysInMonth365[month] + 1;
rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
ExecutePosTest("007", "008", myCalendar, year, month, day, rule, firstDayOfWeek);
}
// PosTest5: Maximum supported year, any month and any day
[Fact]
public void PosTest5()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month, day;
CalendarWeekRule rule;
DayOfWeek firstDayOfWeek;
year = myCalendar.MaxSupportedDateTime.Year;
//Get a random value beween 1 and 12
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
//Get a day beween 1 and the last day of the month
day = TestLibrary.Generator.GetInt32(-55) % s_daysInMonth365[month] + 1;
rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
ExecutePosTest("009", "010", myCalendar, year, month, day, rule, firstDayOfWeek);
}
// PosTest6: Minimum supported year, any month
[Fact]
public void PosTest6()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month, day;
CalendarWeekRule rule;
DayOfWeek firstDayOfWeek;
year = myCalendar.MinSupportedDateTime.Year;
//Get a random value beween 1 and 12
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
//Get a day beween 1 and the last day of the month
day = TestLibrary.Generator.GetInt32(-55) % s_daysInMonth365[month] + 1;
rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
ExecutePosTest("011", "012", myCalendar, year, month, day, rule, firstDayOfWeek);
}
// PosTest7: Any year, any month, any day
[Fact]
public void PosTest7()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month, day;
CalendarWeekRule rule;
DayOfWeek firstDayOfWeek;
year = this.GetAYear(myCalendar);
//Get a random value beween 1 and 12
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
//Get a day beween 1 and the last day of the month
day = TestLibrary.Generator.GetInt32(-55) % s_daysInMonth365[month] + 1;
rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
ExecutePosTest("013", "014", myCalendar, year, month, day, rule, firstDayOfWeek);
}
#endregion
#region Helper methods for postive tests
private int GetDayOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek, int weekOfYear, Calendar myCalendar)
{
int retVal = -367;
int offset = 0;
int dayOfWeekForJan1, dayOfYear, dayOfWeek;
dayOfYear = myCalendar.GetDayOfYear(time); //1-based
dayOfWeek = (int)myCalendar.GetDayOfWeek(time) - (int)firstDayOfWeek + 1; //1-based
if (dayOfWeek <= 0)
dayOfWeek += c_DAYS_PER_WEEK; //Make it a positive value
dayOfWeekForJan1 = dayOfWeek - (dayOfYear - 1) % c_DAYS_PER_WEEK; //1-based
if (dayOfWeekForJan1 <= 0)
dayOfWeekForJan1 += c_DAYS_PER_WEEK; //Make it a positive value
// When the day of specific time falls on the previous year,
// return the number of days from January 1 directly.
// There could be 6 weeks within a month.
if (time.Month == 1 && weekOfYear > 6)
{
return dayOfWeek - dayOfWeekForJan1 + 1;
}
switch (rule)
{
case CalendarWeekRule.FirstDay:
offset = dayOfWeek - dayOfWeekForJan1;
break;
case CalendarWeekRule.FirstFourDayWeek:
if (dayOfWeekForJan1 <= 4)
{
offset = dayOfWeek - dayOfWeekForJan1;
}
else
{
offset = dayOfWeek + c_DAYS_PER_WEEK - dayOfWeekForJan1;
}
break;
case CalendarWeekRule.FirstFullWeek:
if (dayOfWeekForJan1 == 1)
{
offset = dayOfWeek - dayOfWeekForJan1;
}
else
{
offset = dayOfWeek + c_DAYS_PER_WEEK - dayOfWeekForJan1;
}
break;
}
retVal = (weekOfYear - 1) * c_DAYS_PER_WEEK + offset + 1;
return retVal;
}
private void ExecutePosTest(string errorNum1, string errorNum2, Calendar myCalendar, int year,
int month, int day, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
DateTime time;
int actualDayOfYear, expectedDayOfYear;
int weekOfYear;
time = myCalendar.ToDateTime(year, month, day, 0, 0, 0, 0);
expectedDayOfYear = myCalendar.GetDayOfYear(time);
weekOfYear = myCalendar.GetWeekOfYear(time, rule, firstDayOfWeek);
actualDayOfYear = this.GetDayOfYear(time, rule, firstDayOfWeek, weekOfYear, myCalendar);
Assert.Equal(expectedDayOfYear, actualDayOfYear);
}
#endregion
#region Negative Tests
// NegTest1: firstDayOfWeek is too large.
[Fact]
public void NegTest1()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
DateTime time = DateTime.Now;
CalendarWeekRule rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
DayOfWeek firstDayOfWeek = (DayOfWeek)(7 + TestLibrary.Generator.GetInt32(-55) % (int.MaxValue - 6));
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.GetWeekOfYear(time, rule, firstDayOfWeek);
});
}
// NegTest2: firstDayOfWeek is less than minimum value supported
[Fact]
public void NegTest2()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
DateTime time = DateTime.Now;
CalendarWeekRule rule = (CalendarWeekRule)(TestLibrary.Generator.GetInt32(-55) % 3);
DayOfWeek firstDayOfWeek = (DayOfWeek)(-1 * TestLibrary.Generator.GetInt32(-55) - 1);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.GetWeekOfYear(time, rule, firstDayOfWeek);
});
}
// NegTest3: rule is a too large value
[Fact]
public void NegTest3()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
DateTime time = DateTime.Now;
CalendarWeekRule rule = (CalendarWeekRule)(3 + TestLibrary.Generator.GetInt32(-55) % (int.MaxValue - 2));
DayOfWeek firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.GetWeekOfYear(time, rule, firstDayOfWeek);
});
}
// NegTest4: rule is less than maximum supported value
[Fact]
public void NegTest4()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
DateTime time = DateTime.Now;
CalendarWeekRule rule = (CalendarWeekRule)(-1 * TestLibrary.Generator.GetInt32(-55) - 1);
DayOfWeek firstDayOfWeek = (DayOfWeek)(TestLibrary.Generator.GetInt32(-55) % 7);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.GetWeekOfYear(time, rule, firstDayOfWeek);
});
}
#endregion
#region Helper methods for all the tests
//Get a random year beween minmum supported year and maximum supported year of the specified calendar
private int GetAYear(Calendar calendar)
{
int retVal;
int maxYear, minYear;
maxYear = calendar.MaxSupportedDateTime.Year;
minYear = calendar.MinSupportedDateTime.Year;
retVal = minYear + TestLibrary.Generator.GetInt32(-55) % (maxYear + 1 - minYear);
return retVal;
}
//Get a leap year of the specified calendar
private int GetALeapYear(Calendar calendar)
{
int retVal;
// A leap year is any year divisible by 4 except for centennial years(those ending in 00)
// which are only leap years if they are divisible by 400.
retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0
retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400
// if retVal was 100, 200, or 300 the above logic will result in 0
if (0 == retVal)
{
retVal = 400;
}
return retVal;
}
//Get a common year of the specified calendar
private int GetACommonYear(Calendar calendar)
{
int retVal;
do
{
retVal = GetAYear(calendar);
}
while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400);
return retVal;
}
//Get text represntation of the input parmeters
private string GetParamsInfo(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
string str;
str = string.Format("\nThe specified time: {0}).", time);
str += string.Format("\nThe calendar week rule: {0}", rule);
str += string.Format("\nThe first day of week: {0}", firstDayOfWeek);
return str;
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// DSACryptoServiceProvider.cs
//
// CSP-based implementation of DSA
//
namespace System.Security.Cryptography {
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// Object layout of the DSAParameters structure
internal class DSACspObject {
internal byte[] P;
internal byte[] Q;
internal byte[] G;
internal byte[] Y;
internal byte[] J;
internal byte[] X;
internal byte[] Seed;
internal int Counter;
}
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DSACryptoServiceProvider : DSA, ICspAsymmetricAlgorithm {
private int _dwKeySize;
private CspParameters _parameters;
private bool _randomKeyContainer;
[System.Security.SecurityCritical] // auto-generated
private SafeProvHandle _safeProvHandle;
[System.Security.SecurityCritical] // auto-generated
private SafeKeyHandle _safeKeyHandle;
private SHA1CryptoServiceProvider _sha1;
private static volatile CspProviderFlags s_UseMachineKeyStore = 0;
//
// public constructors
//
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public DSACryptoServiceProvider()
: this(0, new CspParameters(Constants.PROV_DSS_DH, null, null, s_UseMachineKeyStore)) {
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public DSACryptoServiceProvider(int dwKeySize)
: this(dwKeySize, new CspParameters(Constants.PROV_DSS_DH, null, null, s_UseMachineKeyStore)) {
}
public DSACryptoServiceProvider(CspParameters parameters)
: this(0, parameters) {
}
[System.Security.SecuritySafeCritical] // auto-generated
public DSACryptoServiceProvider(int dwKeySize, CspParameters parameters) {
if (dwKeySize < 0)
throw new ArgumentOutOfRangeException("dwKeySize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
_parameters = Utils.SaveCspParameters(CspAlgorithmType.Dss, parameters, s_UseMachineKeyStore, ref _randomKeyContainer);
LegalKeySizesValue = new KeySizes[] { new KeySizes(512, 1024, 64) }; // per the DSS spec
_dwKeySize = dwKeySize;
_sha1 = new SHA1CryptoServiceProvider();
// If this is not a random container we generate, create it eagerly
// in the constructor so we can report any errors now.
if (!_randomKeyContainer || Environment.GetCompatibilityFlag(CompatibilityFlag.EagerlyGenerateRandomAsymmKeys))
GetKeyPair();
}
//
// private methods
//
[System.Security.SecurityCritical] // auto-generated
private void GetKeyPair () {
if (_safeKeyHandle == null) {
lock (this) {
if (_safeKeyHandle == null)
Utils.GetKeyPairHelper(CspAlgorithmType.Dss, _parameters, _randomKeyContainer, _dwKeySize, ref _safeProvHandle, ref _safeKeyHandle);
}
}
}
[System.Security.SecuritySafeCritical] // overrides public transparent member
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
_safeKeyHandle.Dispose();
if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
_safeProvHandle.Dispose();
}
//
// public properties
//
[System.Runtime.InteropServices.ComVisible(false)]
public bool PublicOnly {
[System.Security.SecuritySafeCritical] // auto-generated
get {
GetKeyPair();
byte[] publicKey = (byte[]) Utils._GetKeyParameter(_safeKeyHandle, Constants.CLR_PUBLICKEYONLY);
return (publicKey[0] == 1);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public CspKeyContainerInfo CspKeyContainerInfo {
[System.Security.SecuritySafeCritical] // auto-generated
get {
GetKeyPair();
return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
}
}
public override int KeySize {
[System.Security.SecuritySafeCritical] // auto-generated
get {
GetKeyPair();
byte[] keySize = (byte[]) Utils._GetKeyParameter(_safeKeyHandle, Constants.CLR_KEYLEN);
_dwKeySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
return _dwKeySize;
}
}
public override string KeyExchangeAlgorithm {
get { return null; }
}
public override string SignatureAlgorithm {
get { return "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; }
}
public static bool UseMachineKeyStore {
get { return (s_UseMachineKeyStore == CspProviderFlags.UseMachineKeyStore); }
set { s_UseMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0); }
}
public bool PersistKeyInCsp {
[System.Security.SecuritySafeCritical] // auto-generated
get {
if (_safeProvHandle == null) {
lock (this) {
if (_safeProvHandle == null)
_safeProvHandle = Utils.CreateProvHandle(_parameters, _randomKeyContainer);
}
}
return Utils.GetPersistKeyInCsp(_safeProvHandle);
}
[System.Security.SecuritySafeCritical] // auto-generated
set {
bool oldPersistKeyInCsp = this.PersistKeyInCsp;
if (value == oldPersistKeyInCsp)
return;
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
if (!value) {
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Delete);
kp.AccessEntries.Add(entry);
} else {
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Create);
kp.AccessEntries.Add(entry);
}
kp.Demand();
Utils.SetPersistKeyInCsp(_safeProvHandle, value);
}
}
//
// public methods
//
[System.Security.SecuritySafeCritical] // auto-generated
public override DSAParameters ExportParameters (bool includePrivateParameters) {
GetKeyPair();
if (includePrivateParameters) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Export);
kp.AccessEntries.Add(entry);
kp.Demand();
}
DSACspObject dsaCspObject = new DSACspObject();
int blobType = includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB;
// _ExportKey will check for failures and throw an exception
Utils._ExportKey(_safeKeyHandle, blobType, dsaCspObject);
return DSAObjectToStruct(dsaCspObject);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public byte[] ExportCspBlob (bool includePrivateParameters) {
GetKeyPair();
return Utils.ExportCspBlobHelper(includePrivateParameters, _parameters, _safeKeyHandle);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void ImportParameters(DSAParameters parameters) {
DSACspObject dsaCspObject = DSAStructToObject(parameters);
// Free the current key handle
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
_safeKeyHandle.Dispose();
_safeKeyHandle = SafeKeyHandle.InvalidHandle;
if (IsPublic(parameters)) {
// Use our CRYPT_VERIFYCONTEXT handle, CRYPT_EXPORTABLE is not applicable to public only keys, so pass false
Utils._ImportKey(Utils.StaticDssProvHandle, Constants.CALG_DSS_SIGN, (CspProviderFlags) 0, dsaCspObject, ref _safeKeyHandle);
} else {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Import);
kp.AccessEntries.Add(entry);
kp.Demand();
if (_safeProvHandle == null)
_safeProvHandle = Utils.CreateProvHandle(_parameters, _randomKeyContainer);
// Now, import the key into the CSP; _ImportKey will check for failures.
Utils._ImportKey(_safeProvHandle, Constants.CALG_DSS_SIGN, _parameters.Flags, dsaCspObject, ref _safeKeyHandle);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public void ImportCspBlob (byte[] keyBlob) {
Utils.ImportCspBlobHelper(CspAlgorithmType.Dss, keyBlob, IsPublic(keyBlob), ref _parameters, _randomKeyContainer, ref _safeProvHandle, ref _safeKeyHandle);
}
public byte[] SignData(Stream inputStream) {
byte[] hashVal = _sha1.ComputeHash(inputStream);
return SignHash(hashVal, null);
}
public byte[] SignData(byte[] buffer) {
byte[] hashVal = _sha1.ComputeHash(buffer);
return SignHash(hashVal, null);
}
public byte[] SignData(byte[] buffer, int offset, int count) {
byte[] hashVal = _sha1.ComputeHash(buffer, offset, count);
return SignHash(hashVal, null);
}
public bool VerifyData(byte[] rgbData, byte[] rgbSignature) {
byte[] hashVal = _sha1.ComputeHash(rgbData);
return VerifyHash(hashVal, null, rgbSignature);
}
override public byte[] CreateSignature(byte[] rgbHash) {
return SignHash(rgbHash, null);
}
override public bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) {
return VerifyHash(rgbHash, null, rgbSignature);
}
[System.Security.SecuritySafeCritical] // auto-generated
public byte[] SignHash(byte[] rgbHash, string str) {
if (rgbHash == null)
throw new ArgumentNullException("rgbHash");
Contract.EndContractBlock();
if (PublicOnly)
throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NoPrivateKey"));
int calgHash = X509Utils.NameOrOidToAlgId(str, OidGroup.HashAlgorithm);
if (rgbHash.Length != _sha1.HashSize / 8)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHashSize", "SHA1", _sha1.HashSize / 8));
GetKeyPair();
if (!CspKeyContainerInfo.RandomlyGenerated) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Sign);
kp.AccessEntries.Add(entry);
kp.Demand();
}
return Utils.SignValue(_safeKeyHandle, _parameters.KeyNumber, Constants.CALG_DSS_SIGN, calgHash, rgbHash);
}
[System.Security.SecuritySafeCritical] // auto-generated
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) {
if (rgbHash == null)
throw new ArgumentNullException("rgbHash");
if (rgbSignature == null)
throw new ArgumentNullException("rgbSignature");
Contract.EndContractBlock();
int calgHash = X509Utils.NameOrOidToAlgId(str, OidGroup.HashAlgorithm);
if (rgbHash.Length != _sha1.HashSize / 8)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHashSize", "SHA1", _sha1.HashSize / 8));
GetKeyPair();
return Utils.VerifySign(_safeKeyHandle, Constants.CALG_DSS_SIGN, calgHash, rgbHash, rgbSignature);
}
//
// private static methods
//
private static DSAParameters DSAObjectToStruct (DSACspObject dsaCspObject) {
DSAParameters dsaParams = new DSAParameters();
dsaParams.P = dsaCspObject.P;
dsaParams.Q = dsaCspObject.Q;
dsaParams.G = dsaCspObject.G;
dsaParams.Y = dsaCspObject.Y;
dsaParams.J = dsaCspObject.J;
dsaParams.X = dsaCspObject.X;
dsaParams.Seed = dsaCspObject.Seed;
dsaParams.Counter = dsaCspObject.Counter;
return dsaParams;
}
private static DSACspObject DSAStructToObject (DSAParameters dsaParams) {
DSACspObject dsaCspObject = new DSACspObject();
dsaCspObject.P = dsaParams.P;
dsaCspObject.Q = dsaParams.Q;
dsaCspObject.G = dsaParams.G;
dsaCspObject.Y = dsaParams.Y;
dsaCspObject.J = dsaParams.J;
dsaCspObject.X = dsaParams.X;
dsaCspObject.Seed = dsaParams.Seed;
dsaCspObject.Counter = dsaParams.Counter;
return dsaCspObject;
}
private static bool IsPublic (DSAParameters dsaParams) {
return (dsaParams.X == null);
}
// find whether a DSS key blob is public.
private static bool IsPublic (byte[] keyBlob) {
if (keyBlob == null)
throw new ArgumentNullException("keyBlob");
Contract.EndContractBlock();
// The CAPI DSS public key representation consists of the following sequence:
// - BLOBHEADER
// - DSSPUBKEY
// - rgbP[cbKey]
// - rgbQ[20]
// - rgbG[cbKey]
// - rgbY[cbKey]
// - DSSSEED
// The first should be PUBLICKEYBLOB and magic should be DSS_MAGIC "DSS1" or DSS_PUB_MAGIC_VER3 "DSS3"
if (keyBlob[0] != Constants.PUBLICKEYBLOB)
return false;
if ((keyBlob[11] != 0x31 && keyBlob[11] != 0x33) || keyBlob[10] != 0x53 || keyBlob[9] != 0x53 || keyBlob[8] != 0x44)
return false;
return true;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace FileBrowser.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ClassKeywordRecommenderTests : KeywordRecommenderTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEmptyStatement()
{
VerifyAbsence(AddInsideMethod(
@"$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCompilationUnit()
{
VerifyKeyword(
@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterExtern()
{
VerifyKeyword(
@"extern alias Foo;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterUsing()
{
VerifyKeyword(
@"using Foo;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNamespace()
{
VerifyKeyword(
@"namespace N {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterTypeDeclaration()
{
VerifyKeyword(
@"class C {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateDeclaration()
{
VerifyKeyword(
@"delegate void Foo();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterField()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProperty()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing()
{
VerifyAbsence(SourceCodeKind.Regular,
@"$$
using Foo;");
}
[WpfFact(Skip = "528041"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$
using Foo;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAssemblyAttribute()
{
VerifyKeyword(
@"[assembly: foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterRootAttribute()
{
VerifyKeyword(
@"[foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideInterface()
{
VerifyAbsence(@"interface I {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPartial()
{
VerifyKeyword(
@"partial $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAbstract()
{
VerifyKeyword(
@"abstract $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInternal()
{
VerifyKeyword(
@"internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStaticPublic()
{
VerifyKeyword(
@"static public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPublicStatic()
{
VerifyKeyword(
@"public static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInvalidPublic()
{
VerifyAbsence(@"virtual public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPublic()
{
VerifyKeyword(
@"public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPrivate()
{
VerifyKeyword(
@"private $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProtected()
{
VerifyKeyword(
@"protected $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterSealed()
{
VerifyKeyword(
@"sealed $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStatic()
{
VerifyKeyword(
@"static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStaticInUsingDirective()
{
VerifyAbsence(
@"using static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass()
{
VerifyAbsence(@"class $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBetweenUsings()
{
VerifyAbsence(AddInsideMethod(
@"using Foo;
$$
using Bar;"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClassTypeParameterConstraint()
{
VerifyKeyword(
@"class C<T> where T : $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClassTypeParameterConstraint2()
{
VerifyKeyword(
@"class C<T>
where T : $$
where U : U");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodTypeParameterConstraint()
{
VerifyKeyword(
@"class C {
void Foo<T>()
where T : $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodTypeParameterConstraint2()
{
VerifyKeyword(
@"class C {
void Foo<T>()
where T : $$
where U : T");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNew()
{
VerifyKeyword(
@"class C {
new $$");
}
}
}
| |
using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using log4net;
using Tailviewer.Api;
// ReSharper disable once CheckNamespace
namespace Tailviewer.Core
{
/// <summary>
/// Responsible for finding the first matching timestamp format in a stream of messages.
/// Once a format has been found, all subsequent messages are only evaluated agains the given format.
/// </summary>
public sealed class TimestampParser
: ITimestampParser
{
private const int MaxToleratedExceptions = 10;
/// <summary>
/// The maximum number of characters (from the start of the line) which tailviewer will traverse in order to find a timestamp.
/// </summary>
/// <remarks>
/// This number exists because sometimes a software (not to name names) might write utter garbage into its first line.
/// If there's enough garbage (say 158k bytes) in the first line, then tailviewer would search endlessly for a timestamp
/// (the loop not optimized so searching that much data might take hours).
/// If one were to find a better way to implement the loop, then this number might become irrelevant once more.
/// </remarks>
private const int MaxLineLength = 200;
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly ITimestampParser[] _subParsers;
private readonly int _minimumLength;
/// <summary>
/// The parser (if any) which has been successful in the past and will be used from now on.
/// </summary>
private ITimestampParser _determinedParser;
private int _numExceptions;
/// <summary>
/// Initializes this parser.
/// </summary>
public TimestampParser()
: this(
// The format I currently use at work - should be supported by default :P
new DateTimeParser("yyyy-MM-dd HH:mm:ss,fff"),
// Request by abani1986 (https://github.com/Kittyfisto/Tailviewer/issues/182)
new DateTimeParser("yyyy-MM-dd HH:mm:ss:fff"),
new DateTimeParser("yyyy-MM-dd HH:mm:ss.fff"),
new DateTimeParser("yyyy-MM-dd HH:mm:ss"),
// Request by abani1986 (https://github.com/Kittyfisto/Tailviewer/issues/182)
new DateTimeParser("dd/MM/yyyy HH:mm:ss:fff"),
// Another one used by a colleague, well its actually nanoseconds but I can't find that format string
new DateTimeParser("yyyy MMM dd HH:mm:ss.fff"),
new DateTimeParser("yyyy MMM dd HH:mm:ss"),
new DateTimeParser("yyyy-MM-dd HH-mm-ss.fff"),
new DateTimeParser("yyyy-MM-dd HH-mm-ss"),
// Various formats...
new DateTimeParser("dd/MMM/yyyy:HH:mm:ss"),
new DateTimeParser("ddd MMM dd HH:mm:ss.fff yyyy"),
// One of the most bizare formats: Time of day is apparently not interesting enough, just as are fractions of a second.
// We do, however, get the seconds (in nano seconds) since the start of the application...
new TimeOfDaySecondsSinceStartParser(),
new DateTimeParser("HH:mm:ss.fff"),
new DateTimeParser("HH:mm:ss")
)
{
}
/// <summary>
/// Initializes this parser with the given parsers.
/// </summary>
public TimestampParser(params ITimestampParser[] parsers)
{
if (parsers == null)
throw new ArgumentNullException(nameof(parsers));
_subParsers = parsers;
if (parsers.Length > 0)
{
_minimumLength = int.MaxValue;
foreach (var parser in parsers)
{
_minimumLength = Math.Min(_minimumLength, parser.MinimumLength);
}
}
else
{
_minimumLength = 0;
}
}
/// <summary>
/// The index of the character where the timestamp is expected to start.
/// </summary>
public int? DateTimeColumn { get; private set; }
/// <summary>
/// The length of the expected timestamp.
/// </summary>
public int? DateTimeLength { get; private set; }
/// <inheritdoc />
public int MinimumLength => _minimumLength;
/// <inheritdoc />
public bool TryParse(string content, out DateTime timestamp)
{
if (_numExceptions > MaxToleratedExceptions)
{
timestamp = DateTime.MinValue;
return false;
}
try
{
if (DateTimeColumn == null || DateTimeLength == null)
DetermineDateTimePart(content);
return TryParseTimestamp(content, out timestamp);
}
catch (Exception e)
{
++_numExceptions;
Log.ErrorFormat("Caught unexpected exception: {0}", e);
timestamp = DateTime.MinValue;
return false;
}
}
private bool TryParseTimestamp(string content, out DateTime timestamp)
{
if (_determinedParser != null && DateTimeColumn != null && DateTimeLength != null)
{
var start = DateTimeColumn.Value;
var length = DateTimeLength.Value;
if (content.Length >= start + length)
{
var timestampValue = content.Substring(start, length);
if (_determinedParser.TryParse(timestampValue, out timestamp))
return true;
}
}
timestamp = DateTime.MinValue;
return false;
}
private void DetermineDateTimePart(string line)
{
if (SkipLine(line))
return;
int lineLength = line.Length;
if (line.Length > MaxLineLength)
{
Log.WarnFormat("Line has a length ({1}) greater than {0} characters. A timestamp will only be looked for in the first {0} characters!", MaxLineLength, line.Length);
lineLength = MaxLineLength;
}
foreach (var parser in _subParsers)
{
for (var firstIndex = 0; firstIndex < lineLength; ++firstIndex)
for (var lastIndex = firstIndex + parser.MinimumLength; lastIndex <= lineLength; ++lastIndex)
{
var dateTimeString = line.Substring(firstIndex, lastIndex - firstIndex);
try
{
DateTime unused;
if (parser.TryParse(dateTimeString, out unused))
{
var length = lastIndex - firstIndex;
DateTimeColumn = firstIndex;
DateTimeLength = length;
_determinedParser = parser;
return;
}
}
catch (Exception e)
{
++_numExceptions;
Log.ErrorFormat("Caught unexpected exception: {0}", e);
}
}
}
}
/// <summary>
///
/// </summary>
/// <remarks>
/// This method exists because parsing timestamps is time consuming due to its sub-par implementation.
/// </remarks>
/// <param name="line"></param>
/// <returns></returns>
[Pure]
private static bool SkipLine(string line)
{
// The runtime of the DetermineDateTimePart() method is so bad that performing a simple o(n)
// check is totally worth it, when you can skip gigantic lines
if (line.Any(char.IsDigit))
return false;
return true;
}
}
}
| |
//
// PersonaAuthorizer.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Auth;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Auth
{
public class PersonaAuthorizer : Authorizer
{
public const string LoginParameterAssertion = "assertion";
private static IDictionary<IList<string>, string> assertions;
public const string AssertionFieldEmail = "email";
public const string AssertionFieldOrigin = "origin";
public const string AssertionFieldExpiration = "exp";
public const string QueryParameter = "personaAssertion";
private bool skipAssertionExpirationCheck;
private string emailAddress;
public PersonaAuthorizer(string emailAddress)
{
// set to true to skip checking whether assertions have expired (useful for testing)
this.emailAddress = emailAddress;
}
public virtual void SetSkipAssertionExpirationCheck(bool skipAssertionExpirationCheck
)
{
this.skipAssertionExpirationCheck = skipAssertionExpirationCheck;
}
public virtual bool IsSkipAssertionExpirationCheck()
{
return skipAssertionExpirationCheck;
}
public virtual string GetEmailAddress()
{
return emailAddress;
}
protected internal virtual bool IsAssertionExpired(IDictionary<string, object> parsedAssertion
)
{
if (this.IsSkipAssertionExpirationCheck() == true)
{
return false;
}
DateTime exp;
exp = (DateTime)parsedAssertion[AssertionFieldExpiration];
DateTime now = new DateTime();
if (exp.Before(now))
{
Log.W(Database.Tag, string.Format("%s assertion for %s expired: %s", this.GetType
(), this.emailAddress, exp));
return true;
}
return false;
}
public virtual string AssertionForSite(Uri site)
{
string assertion = AssertionForEmailAndSite(this.emailAddress, site);
if (assertion == null)
{
Log.W(Database.Tag, string.Format("%s %s no assertion found for: %s", this.GetType
(), this.emailAddress, site));
return null;
}
IDictionary<string, object> result = ParseAssertion(assertion);
if (IsAssertionExpired(result))
{
return null;
}
return assertion;
}
public override bool UsesCookieBasedLogin()
{
return true;
}
public override IDictionary<string, string> LoginParametersForSite(Uri site)
{
IDictionary<string, string> loginParameters = new Dictionary<string, string>();
string assertion = AssertionForSite(site);
if (assertion != null)
{
loginParameters[LoginParameterAssertion] = assertion;
return loginParameters;
}
else
{
return null;
}
}
public override string LoginPathForSite(Uri site)
{
return "/_persona";
}
public static string RegisterAssertion(string assertion)
{
lock (typeof(PersonaAuthorizer))
{
string email;
string origin;
IDictionary<string, object> result = ParseAssertion(assertion);
email = (string)result[AssertionFieldEmail];
origin = (string)result[AssertionFieldOrigin];
// Normalize the origin URL string:
try
{
Uri originURL = new Uri(origin);
if (origin == null)
{
throw new ArgumentException("Invalid assertion, origin was null");
}
origin = originURL.ToString().ToLower();
}
catch (UriFormatException e)
{
string message = "Error registering assertion: " + assertion;
Log.E(Database.Tag, message, e);
throw new ArgumentException(message, e);
}
return RegisterAssertion(assertion, email, origin);
}
}
/// <summary>
/// don't use this!! this was factored out for testing purposes, and had to be
/// made public since tests are in their own package.
/// </summary>
/// <remarks>
/// don't use this!! this was factored out for testing purposes, and had to be
/// made public since tests are in their own package.
/// </remarks>
public static string RegisterAssertion(string assertion, string email, string origin
)
{
lock (typeof(PersonaAuthorizer))
{
IList<string> key = new AList<string>();
key.AddItem(email);
key.AddItem(origin);
if (assertions == null)
{
assertions = new Dictionary<IList<string>, string>();
}
Log.D(Database.Tag, "PersonaAuthorizer registering key: " + key);
assertions[key] = assertion;
return email;
}
}
public static IDictionary<string, object> ParseAssertion(string assertion)
{
// https://github.com/mozilla/id-specs/blob/prod/browserid/index.md
// http://self-issued.info/docs/draft-jones-json-web-token-04.html
IDictionary<string, object> result = new Dictionary<string, object>();
string[] components = assertion.Split("\\.");
// split on "."
if (components.Length < 4)
{
throw new ArgumentException("Invalid assertion given, only " + components.Length
+ " found. Expected 4+");
}
string component1Decoded = Sharpen.Runtime.GetStringForBytes(Base64.Decode(components
[1], Base64.Default));
string component3Decoded = Sharpen.Runtime.GetStringForBytes(Base64.Decode(components
[3], Base64.Default));
try
{
ObjectWriter mapper = new ObjectWriter();
IDictionary<object, object> component1Json = mapper.ReadValue<IDictionary>(component1Decoded
);
IDictionary<object, object> principal = (IDictionary<object, object>)component1Json
["principal"];
result.Put(AssertionFieldEmail, principal["email"]);
IDictionary<object, object> component3Json = mapper.ReadValue<IDictionary>(component3Decoded
);
result.Put(AssertionFieldOrigin, component3Json["aud"]);
long expObject = (long)component3Json["exp"];
Log.D(Database.Tag, "PersonaAuthorizer exp: " + expObject + " class: " + expObject
.GetType());
DateTime expDate = Sharpen.Extensions.CreateDate(expObject);
result[AssertionFieldExpiration] = expDate;
}
catch (IOException e)
{
string message = "Error parsing assertion: " + assertion;
Log.E(Database.Tag, message, e);
throw new ArgumentException(message, e);
}
return result;
}
public static string AssertionForEmailAndSite(string email, Uri site)
{
IList<string> key = new AList<string>();
key.AddItem(email);
key.AddItem(site.ToString().ToLower());
Log.D(Database.Tag, "PersonaAuthorizer looking up key: " + key + " from list of assertions"
);
return assertions[key];
}
}
}
| |
/* ====================================================================
Copyright 2002-2004 Apache Software Foundation
Licensed Under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using NPOI.SS.Util;
using NPOI.Util;
using NPOI.SS.Formula.PTG;
using NPOI.SS.Formula;
/**
* Title: DATAVALIDATION Record (0x01BE)<p/>
* Description: This record stores data validation Settings and a list of cell ranges
* which contain these Settings. The data validation Settings of a sheet
* are stored in a sequential list of DV records. This list Is followed by
* DVAL record(s)
* @author Dragos Buleandra (dragos.buleandra@trade2b.ro)
* @version 2.0-pre
*/
public class DVRecord : StandardRecord, ICloneable
{
private static readonly UnicodeString NULL_TEXT_STRING = new UnicodeString("\0");
public const short sid = 0x01BE;
/** Option flags */
private int _option_flags;
/** Title of the prompt box */
private UnicodeString _promptTitle;
/** Title of the error box */
private UnicodeString _errorTitle;
/** Text of the prompt box */
private UnicodeString _promptText;
/** Text of the error box */
private UnicodeString _errorText;
/** Not used - Excel seems to always write 0x3FE0 */
private short _not_used_1 = 0x3FE0;
/** Formula data for first condition (RPN token array without size field) */
private NPOI.SS.Formula.Formula _formula1;
/** Not used - Excel seems to always write 0x0000 */
private short _not_used_2 = 0x0000;
/** Formula data for second condition (RPN token array without size field) */
private NPOI.SS.Formula.Formula _formula2;
/** Cell range address list with all affected ranges */
private CellRangeAddressList _regions;
public const int STRING_PROMPT_TITLE = 0;
public const int STRING_ERROR_TITLE = 1;
public const int STRING_PROMPT_TEXT = 2;
public const int STRING_ERROR_TEXT = 3;
/**
* Option flags field
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
private BitField opt_data_type = new BitField(0x0000000F);
private BitField opt_error_style = new BitField(0x00000070);
private BitField opt_string_list_formula = new BitField(0x00000080);
private BitField opt_empty_cell_allowed = new BitField(0x00000100);
private BitField opt_suppress_dropdown_arrow = new BitField(0x00000200);
private BitField opt_show_prompt_on_cell_selected = new BitField(0x00040000);
private BitField opt_show_error_on_invalid_value = new BitField(0x00080000);
private BitField opt_condition_operator = new BitField(0x00F00000);
public DVRecord()
{
}
public DVRecord(int validationType, int operator1, int errorStyle, bool emptyCellAllowed,
bool suppressDropDownArrow, bool isExplicitList,
bool showPromptBox, String promptTitle, String promptText,
bool showErrorBox, String errorTitle, String errorText,
Ptg[] formula1, Ptg[] formula2,
CellRangeAddressList regions)
{
int flags = 0;
flags = opt_data_type.SetValue(flags, validationType);
flags = opt_condition_operator.SetValue(flags, operator1);
flags = opt_error_style.SetValue(flags, errorStyle);
flags = opt_empty_cell_allowed.SetBoolean(flags, emptyCellAllowed);
flags = opt_suppress_dropdown_arrow.SetBoolean(flags, suppressDropDownArrow);
flags = opt_string_list_formula.SetBoolean(flags, isExplicitList);
flags = opt_show_prompt_on_cell_selected.SetBoolean(flags, showPromptBox);
flags = opt_show_error_on_invalid_value.SetBoolean(flags, showErrorBox);
_option_flags = flags;
_promptTitle = ResolveTitleText(promptTitle);
_promptText = ResolveTitleText(promptText);
_errorTitle = ResolveTitleText(errorTitle);
_errorText = ResolveTitleText(errorText);
_formula1 = NPOI.SS.Formula.Formula.Create(formula1);
_formula2 = NPOI.SS.Formula.Formula.Create(formula2);
_regions = regions;
}
/**
* Constructs a DV record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public DVRecord(RecordInputStream in1)
{
_option_flags = in1.ReadInt();
_promptTitle = ReadUnicodeString(in1);
_errorTitle = ReadUnicodeString(in1);
_promptText = ReadUnicodeString(in1);
_errorText = ReadUnicodeString(in1);
int field_size_first_formula = in1.ReadUShort();
_not_used_1 = in1.ReadShort();
//read first formula data condition
_formula1 = NPOI.SS.Formula.Formula.Read(field_size_first_formula, in1);
int field_size_sec_formula = in1.ReadUShort();
_not_used_2 = in1.ReadShort();
//read sec formula data condition
_formula2 = NPOI.SS.Formula.Formula.Read(field_size_sec_formula, in1);
//read cell range address list with all affected ranges
_regions = new CellRangeAddressList(in1);
}
/**
* When entered via the UI, Excel translates empty string into "\0"
* While it is possible to encode the title/text as empty string (Excel doesn't exactly crash),
* the resulting tool-tip text / message box looks wrong. It is best to do the same as the
* Excel UI and encode 'not present' as "\0".
*/
private static UnicodeString ResolveTitleText(String str)
{
if (str == null || str.Length < 1)
{
return NULL_TEXT_STRING;
}
return new UnicodeString(str);
}
private static String ResolveTitleString(UnicodeString us)
{
if (us == null || us.Equals(NULL_TEXT_STRING))
{
return null;
}
return us.String;
}
private static UnicodeString ReadUnicodeString(RecordInputStream in1)
{
return new UnicodeString(in1);
}
/**
* Get the condition data type
* @return the condition data type
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public int DataType
{
get
{
return this.opt_data_type.GetValue(this._option_flags);
}
set { this._option_flags = this.opt_data_type.SetValue(this._option_flags, value); }
}
/**
* Get the condition error style
* @return the condition error style
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public int ErrorStyle
{
get
{
return this.opt_error_style.GetValue(this._option_flags);
}
set { this._option_flags = this.opt_error_style.SetValue(this._option_flags, value); }
}
/**
* return true if in list validations the string list Is explicitly given in the formula, false otherwise
* @return true if in list validations the string list Is explicitly given in the formula, false otherwise
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public bool ListExplicitFormula
{
get
{
return (this.opt_string_list_formula.IsSet(this._option_flags));
}
set { this._option_flags = this.opt_string_list_formula.SetBoolean(this._option_flags, value); }
}
/**
* return true if empty values are allowed in cells, false otherwise
* @return if empty values are allowed in cells, false otherwise
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public bool EmptyCellAllowed
{
get
{
return (this.opt_empty_cell_allowed.IsSet(this._option_flags));
}
set { this._option_flags = this.opt_empty_cell_allowed.SetBoolean(this._option_flags, value); }
}
/**
* @return <code>true</code> if drop down arrow should be suppressed when list validation is
* used, <code>false</code> otherwise
*/
public bool SuppressDropdownArrow
{
get
{
return (opt_suppress_dropdown_arrow.IsSet(_option_flags));
}
}
/**
* return true if a prompt window should appear when cell Is selected, false otherwise
* @return if a prompt window should appear when cell Is selected, false otherwise
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public bool ShowPromptOnCellSelected
{
get
{
return (this.opt_show_prompt_on_cell_selected.IsSet(this._option_flags));
}
}
/**
* return true if an error window should appear when an invalid value Is entered in the cell, false otherwise
* @return if an error window should appear when an invalid value Is entered in the cell, false otherwise
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public bool ShowErrorOnInvalidValue
{
get
{
return (this.opt_show_error_on_invalid_value.IsSet(this._option_flags));
}
set { this._option_flags = this.opt_show_error_on_invalid_value.SetBoolean(this._option_flags, value); }
}
/**
* Get the condition operator
* @return the condition operator
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public int ConditionOperator
{
get
{
return this.opt_condition_operator.GetValue(this._option_flags);
}
set
{
this._option_flags = this.opt_condition_operator.SetValue(this._option_flags, value);
}
}
public String PromptTitle
{
get
{
return ResolveTitleString(_promptTitle);
}
}
public String ErrorTitle
{
get
{
return ResolveTitleString(_errorTitle);
}
}
public String PromptText
{
get
{
return ResolveTitleString(_promptText);
}
}
public String ErrorText
{
get
{
return ResolveTitleString(_errorText);
}
}
public Ptg[] Formula1
{
get
{
return Formula.GetTokens(_formula1);
}
}
public Ptg[] Formula2
{
get
{
return Formula.GetTokens(_formula2);
}
}
public CellRangeAddressList CellRangeAddress
{
get
{
return this._regions;
}
set { this._regions = value; }
}
/**
* Gets the option flags field.
* @return options - the option flags field
*/
public int OptionFlags
{
get
{
return this._option_flags;
}
}
public override String ToString()
{
/* @todo DVRecord string representation */
StringBuilder buffer = new StringBuilder();
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteInt(_option_flags);
SerializeUnicodeString(_promptTitle, out1);
SerializeUnicodeString(_errorTitle, out1);
SerializeUnicodeString(_promptText, out1);
SerializeUnicodeString(_errorText, out1);
out1.WriteShort(_formula1.EncodedTokenSize);
out1.WriteShort(_not_used_1);
_formula1.SerializeTokens(out1);
out1.WriteShort(_formula2.EncodedTokenSize);
out1.WriteShort(_not_used_2);
_formula2.SerializeTokens(out1);
_regions.Serialize(out1);
}
private static void SerializeUnicodeString(UnicodeString us, ILittleEndianOutput out1)
{
StringUtil.WriteUnicodeString(out1, us.String);
}
private static int GetUnicodeStringSize(UnicodeString us)
{
String str = us.String;
return 3 + str.Length * (StringUtil.HasMultibyte(str) ? 2 : 1);
}
protected override int DataSize
{
get
{
int size = 4 + 2 + 2 + 2 + 2;//header+options_field+first_formula_size+first_unused+sec_formula_size+sec+unused;
size += GetUnicodeStringSize(_promptTitle);
size += GetUnicodeStringSize(_errorTitle);
size += GetUnicodeStringSize(_promptText);
size += GetUnicodeStringSize(_errorText);
size += _formula1.EncodedTokenSize;
size += _formula2.EncodedTokenSize;
size += _regions.Size;
return size;
}
}
public override short Sid
{
get { return DVRecord.sid; }
}
/**
* Clones the object. Uses serialisation, as the
* contents are somewhat complex
*/
public override Object Clone()
{
return CloneViaReserialise();
}
}
}
| |
//------------------------------------------------------------------------------
// <license file="ObjToIntMap.cs">
//
// The use and distribution terms for this software are contained in the file
// named 'LICENSE', which can be found in the resources directory of this
// distribution.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// </license>
//------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
namespace EcmaScript.NET.Collections
{
/// <summary> Map to associate objects to integers.
/// The map does not synchronize any of its operation, so either use
/// it from a single thread or do own synchronization or perform all mutation
/// operations on one thread before passing the map to others
///
/// </summary>
public class ObjToIntMap
{
virtual public bool Empty
{
get
{
return keyCount == 0;
}
}
// Map implementation via hashtable,
// follows "The Art of Computer Programming" by Donald E. Knuth
// ObjToIntMap is a copy cat of ObjToIntMap with API adjusted to object keys
public class Iterator
{
virtual public object Key
{
get
{
object key = keys [cursor];
if (key == UniqueTag.NullValue) {
key = null;
}
return key;
}
}
virtual public int Value
{
get
{
return values [cursor];
}
set
{
values [cursor] = value;
}
}
internal Iterator (ObjToIntMap master)
{
this.master = master;
}
internal void Init (object [] keys, int [] values, int keyCount)
{
this.keys = keys;
this.values = values;
this.cursor = -1;
this.remaining = keyCount;
}
public virtual void start ()
{
master.initIterator (this);
next ();
}
public virtual bool done ()
{
return remaining < 0;
}
public virtual void next ()
{
if (remaining == -1)
Context.CodeBug ();
if (remaining == 0) {
remaining = -1;
cursor = -1;
}
else {
for (++cursor; ; ++cursor) {
object key = keys [cursor];
if (key != null && key != ObjToIntMap.DELETED) {
--remaining;
break;
}
}
}
}
internal ObjToIntMap master;
private int cursor;
private int remaining;
private object [] keys;
private int [] values;
}
public ObjToIntMap ()
: this (4)
{
}
public ObjToIntMap (int keyCountHint)
{
if (keyCountHint < 0)
Context.CodeBug ();
// Table grow when number of stored keys >= 3/4 of max capacity
int minimalCapacity = keyCountHint * 4 / 3;
int i;
for (i = 2; (1 << i) < minimalCapacity; ++i) {
}
power = i;
if (check && power < 2)
Context.CodeBug ();
}
public virtual int size ()
{
return keyCount;
}
public virtual bool has (object key)
{
if (key == null) {
key = UniqueTag.NullValue;
}
return 0 <= findIndex (key);
}
/// <summary> Get integer value assigned with key.</summary>
/// <returns> key integer value or defaultValue if key is absent
/// </returns>
public virtual int Get (object key, int defaultValue)
{
if (key == null) {
key = UniqueTag.NullValue;
}
int index = findIndex (key);
if (0 <= index) {
return values [index];
}
return defaultValue;
}
/// <summary> Get integer value assigned with key.</summary>
/// <returns> key integer value
/// </returns>
/// <throws> RuntimeException if key does not exist </throws>
public virtual int getExisting (object key)
{
if (key == null) {
key = UniqueTag.NullValue;
}
int index = findIndex (key);
if (0 <= index) {
return values [index];
}
// Key must exist
Context.CodeBug ();
return 0;
}
public virtual void put (object key, int value)
{
if (key == null) {
key = UniqueTag.NullValue;
}
int index = ensureIndex (key);
values [index] = value;
}
/// <summary> If table already contains a key that equals to keyArg, return that key
/// while setting its value to zero, otherwise add keyArg with 0 value to
/// the table and return it.
/// </summary>
public virtual object intern (object keyArg)
{
bool nullKey = false;
if (keyArg == null) {
nullKey = true;
keyArg = UniqueTag.NullValue;
}
int index = ensureIndex (keyArg);
values [index] = 0;
return (nullKey) ? null : keys [index];
}
public virtual void remove (object key)
{
if (key == null) {
key = UniqueTag.NullValue;
}
int index = findIndex (key);
if (0 <= index) {
keys [index] = DELETED;
--keyCount;
}
}
public virtual void clear ()
{
int i = keys.Length;
while (i != 0) {
keys [--i] = null;
}
keyCount = 0;
occupiedCount = 0;
}
public virtual Iterator newIterator ()
{
return new Iterator (this);
}
// The sole purpose of the method is to avoid accessing private fields
// from the Iterator inner class to workaround JDK 1.1 compiler bug which
// generates code triggering VerifierError on recent JVMs
internal void initIterator (Iterator i)
{
i.Init (keys, values, keyCount);
}
/// <summary>Return array of present keys </summary>
public virtual object [] getKeys ()
{
object [] array = new object [keyCount];
getKeys (array, 0);
return array;
}
public virtual void getKeys (object [] array, int offset)
{
int count = keyCount;
for (int i = 0; count != 0; ++i) {
object key = keys [i];
if (key != null && key != DELETED) {
if (key == UniqueTag.NullValue) {
key = null;
}
array [offset] = key;
++offset;
--count;
}
}
}
private static int tableLookupStep (int fraction, int mask, int power)
{
int shift = 32 - 2 * power;
if (shift >= 0) {
return ((int)(((uint)fraction >> shift)) & mask) | 1;
}
else {
return (fraction & (int)((uint)mask >> -shift)) | 1;
}
}
private int findIndex (object key)
{
if (keys != null) {
int hash = key.GetHashCode ();
int fraction = hash * A;
int index = (int)((uint)fraction >> (32 - power));
object test = keys [index];
if (test != null) {
int N = 1 << power;
if (test == key || (values [N + index] == hash && test.Equals (key))) {
return index;
}
// Search in table after first failed attempt
int mask = N - 1;
int step = tableLookupStep (fraction, mask, power);
int n = 0;
for (; ; ) {
if (check) {
if (n >= occupiedCount)
Context.CodeBug ();
++n;
}
index = (index + step) & mask;
test = keys [index];
if (test == null) {
break;
}
if (test == key || (values [N + index] == hash && test.Equals (key))) {
return index;
}
}
}
}
return -1;
}
// Insert key that is not present to table without deleted entries
// and enough free space
private int insertNewKey (object key, int hash)
{
if (check && occupiedCount != keyCount)
Context.CodeBug ();
if (check && keyCount == 1 << power)
Context.CodeBug ();
int fraction = hash * A;
int index = (int)((uint)fraction >> (32 - power));
int N = 1 << power;
if (keys [index] != null) {
int mask = N - 1;
int step = tableLookupStep (fraction, mask, power);
int firstIndex = index;
do {
if (check && keys [index] == DELETED)
Context.CodeBug ();
index = (index + step) & mask;
if (check && firstIndex == index)
Context.CodeBug ();
}
while (keys [index] != null);
}
keys [index] = key;
values [N + index] = hash;
++occupiedCount;
++keyCount;
return index;
}
private void rehashTable ()
{
if (keys == null) {
if (check && keyCount != 0)
Context.CodeBug ();
if (check && occupiedCount != 0)
Context.CodeBug ();
int N = 1 << power;
keys = new object [N];
values = new int [2 * N];
}
else {
// Check if removing deleted entries would free enough space
if (keyCount * 2 >= occupiedCount) {
// Need to grow: less then half of deleted entries
++power;
}
int N = 1 << power;
object [] oldKeys = keys;
int [] oldValues = values;
int oldN = oldKeys.Length;
keys = new object [N];
values = new int [2 * N];
int remaining = keyCount;
occupiedCount = keyCount = 0;
for (int i = 0; remaining != 0; ++i) {
object key = oldKeys [i];
if (key != null && key != DELETED) {
int keyHash = oldValues [oldN + i];
int index = insertNewKey (key, keyHash);
values [index] = oldValues [i];
--remaining;
}
}
}
}
// Ensure key index creating one if necessary
private int ensureIndex (object key)
{
int hash = key.GetHashCode ();
int index = -1;
int firstDeleted = -1;
if (keys != null) {
int fraction = hash * A;
index = (int)((uint)fraction >> (32 - power));
object test = keys [index];
if (test != null) {
int N = 1 << power;
if (test == key || (values [N + index] == hash && test.Equals (key))) {
return index;
}
if (test == DELETED) {
firstDeleted = index;
}
// Search in table after first failed attempt
int mask = N - 1;
int step = tableLookupStep (fraction, mask, power);
int n = 0;
for (; ; ) {
if (check) {
if (n >= occupiedCount)
Context.CodeBug ();
++n;
}
index = (index + step) & mask;
test = keys [index];
if (test == null) {
break;
}
if (test == key || (values [N + index] == hash && test.Equals (key))) {
return index;
}
if (test == DELETED && firstDeleted < 0) {
firstDeleted = index;
}
}
}
}
// Inserting of new key
if (check && keys != null && keys [index] != null)
Context.CodeBug ();
if (firstDeleted >= 0) {
index = firstDeleted;
}
else {
// Need to consume empty entry: check occupation level
if (keys == null || occupiedCount * 4 >= (1 << power) * 3) {
// Too litle unused entries: rehash
rehashTable ();
return insertNewKey (key, hash);
}
++occupiedCount;
}
keys [index] = key;
values [(1 << power) + index] = hash;
++keyCount;
return index;
}
// A == golden_ratio * (1 << 32) = ((sqrt(5) - 1) / 2) * (1 << 32)
// See Knuth etc.
private const int A = unchecked ((int)0x9e3779b9);
private static readonly object DELETED = new object ();
// Structure of kyes and values arrays (N == 1 << power):
// keys[0 <= i < N]: key value or null or DELETED mark
// values[0 <= i < N]: value of key at keys[i]
// values[N <= i < 2*N]: hash code of key at keys[i-N]
private object [] keys;
private int [] values;
private int power;
private int keyCount;
private int occupiedCount; // == keyCount + deleted_count
// If true, enables consitency checks
private static readonly bool check = false; // TODO: make me a preprocessor directive
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.ExperimentationModels
{
public enum AnalysisTaskState
{
Waiting,
ReadyForSubmission,
SubmittingToPipeline,
Running,
Completed,
Failed,
Canceled
}
/// <summary>
/// Given a title entity token and exclusion group details, will create a new exclusion group for the title.
/// </summary>
[Serializable]
public class CreateExclusionGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Description of the exclusion group.
/// </summary>
public string Description;
/// <summary>
/// Friendly name of the exclusion group.
/// </summary>
public string Name;
}
[Serializable]
public class CreateExclusionGroupResult : PlayFabResultCommon
{
/// <summary>
/// Identifier of the exclusion group.
/// </summary>
public string ExclusionGroupId;
}
/// <summary>
/// Given a title entity token and experiment details, will create a new experiment for the title.
/// </summary>
[Serializable]
public class CreateExperimentRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Description of the experiment.
/// </summary>
public string Description;
/// <summary>
/// When experiment should end.
/// </summary>
public DateTime? EndDate;
/// <summary>
/// Id of the exclusion group.
/// </summary>
public string ExclusionGroupId;
/// <summary>
/// Percentage of exclusion group traffic that will see this experiment.
/// </summary>
public uint? ExclusionGroupTrafficAllocation;
/// <summary>
/// Type of experiment.
/// </summary>
public ExperimentType? ExperimentType;
/// <summary>
/// Friendly name of the experiment.
/// </summary>
public string Name;
/// <summary>
/// Id of the segment to which this experiment applies. Defaults to the 'All Players' segment.
/// </summary>
public string SegmentId;
/// <summary>
/// When experiment should start.
/// </summary>
public DateTime StartDate;
/// <summary>
/// List of title player account IDs that automatically receive treatments in the experiment, but are not included when
/// calculating experiment metrics.
/// </summary>
public List<string> TitlePlayerAccountTestIds;
/// <summary>
/// List of variants for the experiment.
/// </summary>
public List<Variant> Variants;
}
[Serializable]
public class CreateExperimentResult : PlayFabResultCommon
{
/// <summary>
/// The ID of the new experiment.
/// </summary>
public string ExperimentId;
}
/// <summary>
/// Given an entity token and an exclusion group ID this API deletes the exclusion group.
/// </summary>
[Serializable]
public class DeleteExclusionGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The ID of the exclusion group to delete.
/// </summary>
public string ExclusionGroupId;
}
/// <summary>
/// Given an entity token and an experiment ID this API deletes the experiment. A running experiment must be stopped before
/// it can be deleted.
/// </summary>
[Serializable]
public class DeleteExperimentRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The ID of the experiment to delete.
/// </summary>
public string ExperimentId;
}
[Serializable]
public class EmptyResponse : PlayFabResultCommon
{
}
/// <summary>
/// Combined entity type and ID structure which uniquely identifies a single entity.
/// </summary>
[Serializable]
public class EntityKey : PlayFabBaseModel
{
/// <summary>
/// Unique ID of the entity.
/// </summary>
public string Id;
/// <summary>
/// Entity type. See https://docs.microsoft.com/gaming/playfab/features/data/entities/available-built-in-entity-types
/// </summary>
public string Type;
}
[Serializable]
public class ExclusionGroupTrafficAllocation : PlayFabBaseModel
{
/// <summary>
/// Id of the experiment.
/// </summary>
public string ExperimentId;
/// <summary>
/// Percentage of exclusion group traffic that will see this experiment.
/// </summary>
public uint TrafficAllocation;
}
[Serializable]
public class Experiment : PlayFabBaseModel
{
/// <summary>
/// Description of the experiment.
/// </summary>
public string Description;
/// <summary>
/// When experiment should end/was ended.
/// </summary>
public DateTime? EndDate;
/// <summary>
/// Id of the exclusion group for this experiment.
/// </summary>
public string ExclusionGroupId;
/// <summary>
/// Percentage of exclusion group traffic that will see this experiment.
/// </summary>
public uint? ExclusionGroupTrafficAllocation;
/// <summary>
/// Type of experiment.
/// </summary>
public ExperimentType? ExperimentType;
/// <summary>
/// Id of the experiment.
/// </summary>
public string Id;
/// <summary>
/// Friendly name of the experiment.
/// </summary>
public string Name;
/// <summary>
/// Id of the segment to which this experiment applies. Defaults to the 'All Players' segment.
/// </summary>
public string SegmentId;
/// <summary>
/// When experiment should start/was started.
/// </summary>
public DateTime StartDate;
/// <summary>
/// State experiment is currently in.
/// </summary>
public ExperimentState? State;
/// <summary>
/// List of title player account IDs that automatically receive treatments in the experiment, but are not included when
/// calculating experiment metrics.
/// </summary>
public List<string> TitlePlayerAccountTestIds;
/// <summary>
/// List of variants for the experiment.
/// </summary>
public List<Variant> Variants;
}
[Serializable]
public class ExperimentExclusionGroup : PlayFabBaseModel
{
/// <summary>
/// Description of the exclusion group.
/// </summary>
public string Description;
/// <summary>
/// Id of the exclusion group.
/// </summary>
public string ExclusionGroupId;
/// <summary>
/// Friendly name of the exclusion group.
/// </summary>
public string Name;
}
public enum ExperimentState
{
New,
Started,
Stopped,
Deleted
}
public enum ExperimentType
{
Active,
Snapshot
}
/// <summary>
/// Given a title entity token will return the list of all exclusion groups for a title.
/// </summary>
[Serializable]
public class GetExclusionGroupsRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
}
[Serializable]
public class GetExclusionGroupsResult : PlayFabResultCommon
{
/// <summary>
/// List of exclusion groups for the title.
/// </summary>
public List<ExperimentExclusionGroup> ExclusionGroups;
}
/// <summary>
/// Given a title entity token and an exclusion group ID, will return the list of traffic allocations for the exclusion
/// group.
/// </summary>
[Serializable]
public class GetExclusionGroupTrafficRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The ID of the exclusion group.
/// </summary>
public string ExclusionGroupId;
}
[Serializable]
public class GetExclusionGroupTrafficResult : PlayFabResultCommon
{
/// <summary>
/// List of traffic allocations for the exclusion group.
/// </summary>
public List<ExclusionGroupTrafficAllocation> TrafficAllocations;
}
/// <summary>
/// Given a title entity token will return the list of all experiments for a title, including scheduled, started, stopped or
/// completed experiments.
/// </summary>
[Serializable]
public class GetExperimentsRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
}
[Serializable]
public class GetExperimentsResult : PlayFabResultCommon
{
/// <summary>
/// List of experiments for the title.
/// </summary>
public List<Experiment> Experiments;
}
/// <summary>
/// Given a title entity token and experiment details, will return the latest available scorecard.
/// </summary>
[Serializable]
public class GetLatestScorecardRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The ID of the experiment.
/// </summary>
public string ExperimentId;
}
[Serializable]
public class GetLatestScorecardResult : PlayFabResultCommon
{
/// <summary>
/// Scorecard for the experiment of the title.
/// </summary>
public Scorecard Scorecard;
}
/// <summary>
/// Given a title player or a title entity token, returns the treatment variants and variables assigned to the entity across
/// all running experiments
/// </summary>
[Serializable]
public class GetTreatmentAssignmentRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
}
[Serializable]
public class GetTreatmentAssignmentResult : PlayFabResultCommon
{
/// <summary>
/// Treatment assignment for the entity.
/// </summary>
public TreatmentAssignment TreatmentAssignment;
}
[Serializable]
public class MetricData : PlayFabBaseModel
{
/// <summary>
/// The upper bound of the confidence interval for the relative delta (Delta.RelativeValue).
/// </summary>
public double ConfidenceIntervalEnd;
/// <summary>
/// The lower bound of the confidence interval for the relative delta (Delta.RelativeValue).
/// </summary>
public double ConfidenceIntervalStart;
/// <summary>
/// The absolute delta between TreatmentStats.Average and ControlStats.Average.
/// </summary>
public float DeltaAbsoluteChange;
/// <summary>
/// The relative delta ratio between TreatmentStats.Average and ControlStats.Average.
/// </summary>
public float DeltaRelativeChange;
/// <summary>
/// The machine name of the metric.
/// </summary>
public string InternalName;
/// <summary>
/// Indicates if a movement was detected on that metric.
/// </summary>
public string Movement;
/// <summary>
/// The readable name of the metric.
/// </summary>
public string Name;
/// <summary>
/// The expectation that a movement is real
/// </summary>
public float PMove;
/// <summary>
/// The p-value resulting from the statistical test run for this metric
/// </summary>
public float PValue;
/// <summary>
/// The threshold for observing sample ratio mismatch.
/// </summary>
public float PValueThreshold;
/// <summary>
/// Indicates if the movement is statistically significant.
/// </summary>
public string StatSigLevel;
/// <summary>
/// Observed standard deviation value of the metric.
/// </summary>
public float StdDev;
/// <summary>
/// Observed average value of the metric.
/// </summary>
public float Value;
}
[Serializable]
public class Scorecard : PlayFabBaseModel
{
/// <summary>
/// Represents the date the scorecard was generated.
/// </summary>
public string DateGenerated;
/// <summary>
/// Represents the duration of scorecard analysis.
/// </summary>
public string Duration;
/// <summary>
/// Represents the number of events processed for the generation of this scorecard
/// </summary>
public double EventsProcessed;
/// <summary>
/// Id of the experiment.
/// </summary>
public string ExperimentId;
/// <summary>
/// Friendly name of the experiment.
/// </summary>
public string ExperimentName;
/// <summary>
/// Represents the latest compute job status.
/// </summary>
public AnalysisTaskState? LatestJobStatus;
/// <summary>
/// Represents the presence of a sample ratio mismatch in the scorecard data.
/// </summary>
public bool SampleRatioMismatch;
/// <summary>
/// Scorecard containing list of analysis.
/// </summary>
public List<ScorecardDataRow> ScorecardDataRows;
}
[Serializable]
public class ScorecardDataRow : PlayFabBaseModel
{
/// <summary>
/// Represents whether the variant is control or not.
/// </summary>
public bool IsControl;
/// <summary>
/// Data of the analysis with the internal name of the metric as the key and an object of metric data as value.
/// </summary>
public Dictionary<string,MetricData> MetricDataRows;
/// <summary>
/// Represents the player count in the variant.
/// </summary>
public uint PlayerCount;
/// <summary>
/// Name of the variant of analysis.
/// </summary>
public string VariantName;
}
/// <summary>
/// Given a title entity token and an experiment ID, this API starts the experiment.
/// </summary>
[Serializable]
public class StartExperimentRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The ID of the experiment to start.
/// </summary>
public string ExperimentId;
}
/// <summary>
/// Given a title entity token and an experiment ID, this API stops the experiment if it is running.
/// </summary>
[Serializable]
public class StopExperimentRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The ID of the experiment to stop.
/// </summary>
public string ExperimentId;
}
[Serializable]
public class TreatmentAssignment : PlayFabBaseModel
{
/// <summary>
/// List of the experiment variables.
/// </summary>
public List<Variable> Variables;
/// <summary>
/// List of the experiment variants.
/// </summary>
public List<string> Variants;
}
/// <summary>
/// Given an entity token and exclusion group details this API updates the exclusion group.
/// </summary>
[Serializable]
public class UpdateExclusionGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Description of the exclusion group.
/// </summary>
public string Description;
/// <summary>
/// The ID of the exclusion group to update.
/// </summary>
public string ExclusionGroupId;
/// <summary>
/// Friendly name of the exclusion group.
/// </summary>
public string Name;
}
/// <summary>
/// Given a title entity token and experiment details, this API updates the experiment. If an experiment is already running,
/// only the description and duration properties can be updated.
/// </summary>
[Serializable]
public class UpdateExperimentRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Description of the experiment.
/// </summary>
public string Description;
/// <summary>
/// When experiment should end.
/// </summary>
public DateTime? EndDate;
/// <summary>
/// Id of the exclusion group.
/// </summary>
public string ExclusionGroupId;
/// <summary>
/// Percentage of exclusion group traffic that will see this experiment.
/// </summary>
public uint? ExclusionGroupTrafficAllocation;
/// <summary>
/// Type of experiment.
/// </summary>
public ExperimentType? ExperimentType;
/// <summary>
/// Id of the experiment.
/// </summary>
public string Id;
/// <summary>
/// Friendly name of the experiment.
/// </summary>
public string Name;
/// <summary>
/// Id of the segment to which this experiment applies. Defaults to the 'All Players' segment.
/// </summary>
public string SegmentId;
/// <summary>
/// When experiment should start.
/// </summary>
public DateTime StartDate;
/// <summary>
/// List of title player account IDs that automatically receive treatments in the experiment, but are not included when
/// calculating experiment metrics.
/// </summary>
public List<string> TitlePlayerAccountTestIds;
/// <summary>
/// List of variants for the experiment.
/// </summary>
public List<Variant> Variants;
}
[Serializable]
public class Variable : PlayFabBaseModel
{
/// <summary>
/// Name of the variable.
/// </summary>
public string Name;
/// <summary>
/// Value of the variable.
/// </summary>
public string Value;
}
[Serializable]
public class Variant : PlayFabBaseModel
{
/// <summary>
/// Description of the variant.
/// </summary>
public string Description;
/// <summary>
/// Id of the variant.
/// </summary>
public string Id;
/// <summary>
/// Specifies if variant is control for experiment.
/// </summary>
public bool IsControl;
/// <summary>
/// Name of the variant.
/// </summary>
public string Name;
/// <summary>
/// Id of the TitleDataOverride to use with this variant.
/// </summary>
public string TitleDataOverrideLabel;
/// <summary>
/// Percentage of target audience traffic that will see this variant.
/// </summary>
public uint TrafficPercentage;
/// <summary>
/// Variables returned by this variant.
/// </summary>
public List<Variable> Variables;
}
}
#endif
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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;
namespace Spine {
public class IkConstraint : IConstraint {
internal IkConstraintData data;
internal ExposedList<Bone> bones = new ExposedList<Bone>();
internal Bone target;
internal float mix;
internal int bendDirection;
public IkConstraintData Data { get { return data; } }
public int Order { get { return data.order; } }
public ExposedList<Bone> Bones { get { return bones; } }
public Bone Target { get { return target; } set { target = value; } }
public int BendDirection { get { return bendDirection; } set { bendDirection = value; } }
public float Mix { get { return mix; } set { mix = value; } }
public IkConstraint (IkConstraintData data, Skeleton skeleton) {
if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
this.data = data;
mix = data.mix;
bendDirection = data.bendDirection;
bones = new ExposedList<Bone>(data.bones.Count);
foreach (BoneData boneData in data.bones)
bones.Add(skeleton.FindBone(boneData.name));
target = skeleton.FindBone(data.target.name);
}
/// <summary>Applies the constraint to the constrained bones.</summary>
public void Apply () {
Update();
}
public void Update () {
Bone target = this.target;
ExposedList<Bone> bones = this.bones;
switch (bones.Count) {
case 1:
Apply(bones.Items[0], target.worldX, target.worldY, mix);
break;
case 2:
Apply(bones.Items[0], bones.Items[1], target.worldX, target.worldY, bendDirection, mix);
break;
}
}
override public string ToString () {
return data.name;
}
/// <summary>Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified
/// in the world coordinate system.</summary>
static public void Apply (Bone bone, float targetX, float targetY, float alpha) {
if (!bone.appliedValid) bone.UpdateAppliedTransform();
Bone p = bone.parent;
float id = 1 / (p.a * p.d - p.b * p.c);
float x = targetX - p.worldX, y = targetY - p.worldY;
float tx = (x * p.d - y * p.b) * id - bone.ax, ty = (y * p.a - x * p.c) * id - bone.ay;
float rotationIK = (float)Math.Atan2(ty, tx) * MathUtils.RadDeg - bone.ashearX - bone.arotation;
if (bone.ascaleX < 0) rotationIK += 180;
if (rotationIK > 180)
rotationIK -= 360;
else if (rotationIK < -180) rotationIK += 360;
bone.UpdateWorldTransform(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, bone.ascaleX, bone.ascaleY, bone.ashearX,
bone.ashearY);
}
/// <summary>Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as
/// possible. The target is specified in the world coordinate system.</summary>
/// <param name="child">A direct descendant of the parent bone.</param>
static public void Apply (Bone parent, Bone child, float targetX, float targetY, int bendDir, float alpha) {
if (alpha == 0) {
child.UpdateWorldTransform ();
return;
}
//float px = parent.x, py = parent.y, psx = parent.scaleX, psy = parent.scaleY, csx = child.scaleX;
if (!parent.appliedValid) parent.UpdateAppliedTransform();
if (!child.appliedValid) child.UpdateAppliedTransform();
float px = parent.ax, py = parent.ay, psx = parent.ascaleX, psy = parent.ascaleY, csx = child.ascaleX;
int os1, os2, s2;
if (psx < 0) {
psx = -psx;
os1 = 180;
s2 = -1;
} else {
os1 = 0;
s2 = 1;
}
if (psy < 0) {
psy = -psy;
s2 = -s2;
}
if (csx < 0) {
csx = -csx;
os2 = 180;
} else
os2 = 0;
float cx = child.ax, cy, cwx, cwy, a = parent.a, b = parent.b, c = parent.c, d = parent.d;
bool u = Math.Abs(psx - psy) <= 0.0001f;
if (!u) {
cy = 0;
cwx = a * cx + parent.worldX;
cwy = c * cx + parent.worldY;
} else {
cy = child.ay;
cwx = a * cx + b * cy + parent.worldX;
cwy = c * cx + d * cy + parent.worldY;
}
Bone pp = parent.parent;
a = pp.a;
b = pp.b;
c = pp.c;
d = pp.d;
float id = 1 / (a * d - b * c), x = targetX - pp.worldX, y = targetY - pp.worldY;
float tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py;
x = cwx - pp.worldX;
y = cwy - pp.worldY;
float dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py;
float l1 = (float)Math.Sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1, a2;
if (u) {
l2 *= psx;
float cos = (tx * tx + ty * ty - l1 * l1 - l2 * l2) / (2 * l1 * l2);
if (cos < -1)
cos = -1;
else if (cos > 1) cos = 1;
a2 = (float)Math.Acos(cos) * bendDir;
a = l1 + l2 * cos;
b = l2 * (float)Math.Sin(a2);
a1 = (float)Math.Atan2(ty * a - tx * b, tx * a + ty * b);
} else {
a = psx * l2;
b = psy * l2;
float aa = a * a, bb = b * b, dd = tx * tx + ty * ty, ta = (float)Math.Atan2(ty, tx);
c = bb * l1 * l1 + aa * dd - aa * bb;
float c1 = -2 * bb * l1, c2 = bb - aa;
d = c1 * c1 - 4 * c2 * c;
if (d >= 0) {
float q = (float)Math.Sqrt(d);
if (c1 < 0) q = -q;
q = -(c1 + q) / 2;
float r0 = q / c2, r1 = c / q;
float r = Math.Abs(r0) < Math.Abs(r1) ? r0 : r1;
if (r * r <= dd) {
y = (float)Math.Sqrt(dd - r * r) * bendDir;
a1 = ta - (float)Math.Atan2(y, r);
a2 = (float)Math.Atan2(y / psy, (r - l1) / psx);
goto outer; // break outer;
}
}
float minAngle = MathUtils.PI, minX = l1 - a, minDist = minX * minX, minY = 0;
float maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0;
c = -a * l1 / (aa - bb);
if (c >= -1 && c <= 1) {
c = (float)Math.Acos(c);
x = a * (float)Math.Cos(c) + l1;
y = b * (float)Math.Sin(c);
d = x * x + y * y;
if (d < minDist) {
minAngle = c;
minDist = d;
minX = x;
minY = y;
}
if (d > maxDist) {
maxAngle = c;
maxDist = d;
maxX = x;
maxY = y;
}
}
if (dd <= (minDist + maxDist) / 2) {
a1 = ta - (float)Math.Atan2(minY * bendDir, minX);
a2 = minAngle * bendDir;
} else {
a1 = ta - (float)Math.Atan2(maxY * bendDir, maxX);
a2 = maxAngle * bendDir;
}
}
outer:
float os = (float)Math.Atan2(cy, cx) * s2;
float rotation = parent.arotation;
a1 = (a1 - os) * MathUtils.RadDeg + os1 - rotation;
if (a1 > 180)
a1 -= 360;
else if (a1 < -180) a1 += 360;
parent.UpdateWorldTransform(px, py, rotation + a1 * alpha, parent.scaleX, parent.ascaleY, 0, 0);
rotation = child.arotation;
a2 = ((a2 + os) * MathUtils.RadDeg - child.ashearX) * s2 + os2 - rotation;
if (a2 > 180)
a2 -= 360;
else if (a2 < -180) a2 += 360;
child.UpdateWorldTransform(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
}
}
}
| |
// 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.Serialization
{
using System;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
// These classes define the abstract serialization model, e.g. the rules for WHAT is serialized.
// The answer of HOW the values are serialized is answered by a particular reflection importer
// by looking for a particular set of custom attributes specific to the serialization format
// and building an appropriate set of accessors/mappings.
internal class ModelScope
{
private readonly TypeScope _typeScope;
private readonly Dictionary<Type, TypeModel> _models = new Dictionary<Type, TypeModel>();
private readonly Dictionary<Type, TypeModel> _arrayModels = new Dictionary<Type, TypeModel>();
internal ModelScope(TypeScope typeScope)
{
_typeScope = typeScope;
}
internal TypeScope TypeScope
{
get { return _typeScope; }
}
internal TypeModel GetTypeModel(Type type)
{
return GetTypeModel(type, true);
}
internal TypeModel GetTypeModel(Type type, bool directReference)
{
TypeModel model;
if (_models.TryGetValue(type, out model))
return model;
TypeDesc typeDesc = _typeScope.GetTypeDesc(type, null, directReference);
switch (typeDesc.Kind)
{
case TypeKind.Enum:
model = new EnumModel(type, typeDesc, this);
break;
case TypeKind.Primitive:
model = new PrimitiveModel(type, typeDesc, this);
break;
case TypeKind.Array:
case TypeKind.Collection:
case TypeKind.Enumerable:
model = new ArrayModel(type, typeDesc, this);
break;
case TypeKind.Root:
case TypeKind.Class:
case TypeKind.Struct:
model = new StructModel(type, typeDesc, this);
break;
default:
if (!typeDesc.IsSpecial) throw new NotSupportedException(SR.Format(SR.XmlUnsupportedTypeKind, type.FullName));
model = new SpecialModel(type, typeDesc, this);
break;
}
_models.Add(type, model);
return model;
}
internal ArrayModel GetArrayModel(Type type)
{
TypeModel model;
if (!_arrayModels.TryGetValue(type, out model))
{
model = GetTypeModel(type);
if (!(model is ArrayModel))
{
TypeDesc typeDesc = _typeScope.GetArrayTypeDesc(type);
model = new ArrayModel(type, typeDesc, this);
}
_arrayModels.Add(type, model);
}
return (ArrayModel)model;
}
}
internal abstract class TypeModel
{
private readonly TypeDesc _typeDesc;
private readonly Type _type;
private readonly ModelScope _scope;
protected TypeModel(Type type, TypeDesc typeDesc, ModelScope scope)
{
_scope = scope;
_type = type;
_typeDesc = typeDesc;
}
internal Type Type
{
get { return _type; }
}
internal ModelScope ModelScope
{
get { return _scope; }
}
internal TypeDesc TypeDesc
{
get { return _typeDesc; }
}
}
internal class ArrayModel : TypeModel
{
internal ArrayModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal TypeModel Element
{
get { return ModelScope.GetTypeModel(TypeScope.GetArrayElementType(Type, null)); }
}
}
internal class PrimitiveModel : TypeModel
{
internal PrimitiveModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
}
internal class SpecialModel : TypeModel
{
internal SpecialModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
}
internal class StructModel : TypeModel
{
internal StructModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal MemberInfo[] GetMemberInfos()
{
// we use to return Type.GetMembers() here, the members were returned in a different order: fields first, properties last
// Current System.Reflection code returns members in opposite order: properties first, then fields.
// This code make sure that returns members in the Everett order.
MemberInfo[] members = Type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
MemberInfo[] fieldsAndProps = new MemberInfo[members.Length];
int cMember = 0;
// first copy all non-property members over
for (int i = 0; i < members.Length; i++)
{
if (!(members[i] is PropertyInfo))
{
fieldsAndProps[cMember++] = members[i];
}
}
// now copy all property members over
for (int i = 0; i < members.Length; i++)
{
if (members[i] is PropertyInfo)
{
fieldsAndProps[cMember++] = members[i];
}
}
return fieldsAndProps;
}
internal FieldModel GetFieldModel(MemberInfo memberInfo)
{
FieldModel model = null;
if (memberInfo is FieldInfo)
model = GetFieldModel((FieldInfo)memberInfo);
else if (memberInfo is PropertyInfo)
model = GetPropertyModel((PropertyInfo)memberInfo);
if (model != null)
{
if (model.ReadOnly && model.FieldTypeDesc.Kind != TypeKind.Collection && model.FieldTypeDesc.Kind != TypeKind.Enumerable)
return null;
}
return model;
}
private void CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type)
{
if (typeDesc == null)
return;
if (typeDesc.IsUnsupported)
{
if (typeDesc.Exception == null)
{
typeDesc.Exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, typeDesc.FullName));
}
throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedMember, member.DeclaringType.FullName + "." + member.Name, type.FullName), typeDesc.Exception);
}
CheckSupportedMember(typeDesc.BaseTypeDesc, member, type);
CheckSupportedMember(typeDesc.ArrayElementTypeDesc, member, type);
}
private FieldModel GetFieldModel(FieldInfo fieldInfo)
{
if (fieldInfo.IsStatic) return null;
if (fieldInfo.DeclaringType != Type) return null;
TypeDesc typeDesc = ModelScope.TypeScope.GetTypeDesc(fieldInfo.FieldType, fieldInfo, true, false);
if (fieldInfo.IsInitOnly && typeDesc.Kind != TypeKind.Collection && typeDesc.Kind != TypeKind.Enumerable)
return null;
CheckSupportedMember(typeDesc, fieldInfo, fieldInfo.FieldType);
return new FieldModel(fieldInfo, fieldInfo.FieldType, typeDesc);
}
private FieldModel GetPropertyModel(PropertyInfo propertyInfo)
{
if (propertyInfo.DeclaringType != Type) return null;
if (CheckPropertyRead(propertyInfo))
{
TypeDesc typeDesc = ModelScope.TypeScope.GetTypeDesc(propertyInfo.PropertyType, propertyInfo, true, false);
// Fix for CSDMain 100492, please contact arssrvlt if you need to change this line
if (!propertyInfo.CanWrite && typeDesc.Kind != TypeKind.Collection && typeDesc.Kind != TypeKind.Enumerable)
return null;
CheckSupportedMember(typeDesc, propertyInfo, propertyInfo.PropertyType);
return new FieldModel(propertyInfo, propertyInfo.PropertyType, typeDesc);
}
return null;
}
//CheckProperty
internal static bool CheckPropertyRead(PropertyInfo propertyInfo)
{
if (!propertyInfo.CanRead) return false;
MethodInfo getMethod = propertyInfo.GetMethod;
if (getMethod.IsStatic) return false;
ParameterInfo[] parameters = getMethod.GetParameters();
if (parameters.Length > 0) return false;
return true;
}
}
internal enum SpecifiedAccessor
{
None,
ReadOnly,
ReadWrite,
}
internal class FieldModel
{
private readonly SpecifiedAccessor _checkSpecified = SpecifiedAccessor.None;
private readonly MemberInfo _memberInfo;
private readonly MemberInfo _checkSpecifiedMemberInfo;
private readonly MethodInfo _checkShouldPersistMethodInfo;
private readonly bool _checkShouldPersist;
private readonly bool _readOnly = false;
private readonly bool _isProperty = false;
private readonly Type _fieldType;
private readonly string _name;
private readonly TypeDesc _fieldTypeDesc;
internal FieldModel(string name, Type fieldType, TypeDesc fieldTypeDesc, bool checkSpecified, bool checkShouldPersist) :
this(name, fieldType, fieldTypeDesc, checkSpecified, checkShouldPersist, false)
{
}
internal FieldModel(string name, Type fieldType, TypeDesc fieldTypeDesc, bool checkSpecified, bool checkShouldPersist, bool readOnly)
{
_fieldTypeDesc = fieldTypeDesc;
_name = name;
_fieldType = fieldType;
_checkSpecified = checkSpecified ? SpecifiedAccessor.ReadWrite : SpecifiedAccessor.None;
_checkShouldPersist = checkShouldPersist;
_readOnly = readOnly;
}
internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDesc)
{
_name = memberInfo.Name;
_fieldType = fieldType;
_fieldTypeDesc = fieldTypeDesc;
_memberInfo = memberInfo;
_checkShouldPersistMethodInfo = memberInfo.DeclaringType.GetMethod("ShouldSerialize" + memberInfo.Name, Array.Empty<Type>());
_checkShouldPersist = _checkShouldPersistMethodInfo != null;
FieldInfo specifiedField = memberInfo.DeclaringType.GetField(memberInfo.Name + "Specified");
if (specifiedField != null)
{
if (specifiedField.FieldType != typeof(bool))
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidSpecifiedType, specifiedField.Name, specifiedField.FieldType.FullName, typeof(bool).FullName));
}
_checkSpecified = specifiedField.IsInitOnly ? SpecifiedAccessor.ReadOnly : SpecifiedAccessor.ReadWrite;
_checkSpecifiedMemberInfo = specifiedField;
}
else
{
PropertyInfo specifiedProperty = memberInfo.DeclaringType.GetProperty(memberInfo.Name + "Specified");
if (specifiedProperty != null)
{
if (StructModel.CheckPropertyRead(specifiedProperty))
{
_checkSpecified = specifiedProperty.CanWrite ? SpecifiedAccessor.ReadWrite : SpecifiedAccessor.ReadOnly;
_checkSpecifiedMemberInfo = specifiedProperty;
}
if (_checkSpecified != SpecifiedAccessor.None && specifiedProperty.PropertyType != typeof(bool))
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidSpecifiedType, specifiedProperty.Name, specifiedProperty.PropertyType.FullName, typeof(bool).FullName));
}
}
}
if (memberInfo is PropertyInfo)
{
_readOnly = !((PropertyInfo)memberInfo).CanWrite;
_isProperty = true;
}
else if (memberInfo is FieldInfo)
{
_readOnly = ((FieldInfo)memberInfo).IsInitOnly;
}
}
internal string Name
{
get { return _name; }
}
internal Type FieldType
{
get { return _fieldType; }
}
internal TypeDesc FieldTypeDesc
{
get { return _fieldTypeDesc; }
}
internal bool CheckShouldPersist
{
get { return _checkShouldPersist; }
}
internal SpecifiedAccessor CheckSpecified
{
get { return _checkSpecified; }
}
internal MemberInfo MemberInfo
{
get { return _memberInfo; }
}
internal MemberInfo CheckSpecifiedMemberInfo
{
get { return _checkSpecifiedMemberInfo; }
}
internal MethodInfo CheckShouldPersistMethodInfo
{
get { return _checkShouldPersistMethodInfo; }
}
internal bool ReadOnly
{
get { return _readOnly; }
}
internal bool IsProperty
{
get { return _isProperty; }
}
}
internal class ConstantModel
{
private readonly FieldInfo _fieldInfo;
private readonly long _value;
internal ConstantModel(FieldInfo fieldInfo, long value)
{
_fieldInfo = fieldInfo;
_value = value;
}
internal string Name
{
get { return _fieldInfo.Name; }
}
internal long Value
{
get { return _value; }
}
internal FieldInfo FieldInfo
{
get { return _fieldInfo; }
}
}
internal class EnumModel : TypeModel
{
private ConstantModel[] _constants;
internal EnumModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal ConstantModel[] Constants
{
get
{
if (_constants == null)
{
var list = new List<ConstantModel>();
FieldInfo[] fields = Type.GetFields();
for (int i = 0; i < fields.Length; i++)
{
FieldInfo field = fields[i];
ConstantModel constant = GetConstantModel(field);
if (constant != null) list.Add(constant);
}
_constants = list.ToArray();
}
return _constants;
}
}
private ConstantModel GetConstantModel(FieldInfo fieldInfo)
{
if (fieldInfo.IsSpecialName) return null;
return new ConstantModel(fieldInfo, ((IConvertible)fieldInfo.GetValue(null)).ToInt64(null));
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System;
using DG.Tweening;
using UnityEngine.Events;
public class Grid : MonoBehaviour {
public delegate void SignPlaced(int[] pos, Cell.CellOcc type);
public event SignPlaced SignWasPlacedEvent;
public delegate void SignRemoved(int[] pos);
public event SignRemoved SignWasRemovedEvent;
// How many need for a win
public static int WIN_CONDITION = 5;
protected const float UPDATE_SHOWN_TIME = .3f;
protected const int SHOW_BORDER = 35; // Border around camera in cells in which we should show cells
[HideInInspector]
public string FILE_PATH; // where it should be saved
// Camera size in world units
protected int[] cameraHalfSize;
// The camera's positions: the previous frame and the current frame
// LB = LeftBottom TR = TopRight
protected int[] cameraLastPosLB = new int[2];
protected int[] cameraLastPosTR = new int[2];
protected int[] cameraCurrPosLB = new int[2];
protected int[] cameraCurrPosTR = new int[2];
public Rect CameraPos {
get {
Vector2 lb = new Vector2(cameraCurrPosLB[0] + SHOW_BORDER, cameraCurrPosLB[1] + SHOW_BORDER);
Vector2 tr = new Vector2(cameraCurrPosTR[0] - SHOW_BORDER, cameraCurrPosTR[1] - SHOW_BORDER);
return new Rect(lb, tr - lb);
}
}
// Parent of cell gameobjects
public static GameObject cellParent;
protected TTTGameLogic gameLogic;
// Used for stopping game, it stores where the last sign has been placed
protected int[] previousGridPos;
protected int[] secondToPreviousGridPos;
protected int removeCount = 0;
// Number of signs in current game
protected int numberOfSignsInGame = 0;
protected Dictionary<int[], Partion> partions = new Dictionary<int[], Partion>(new IntegerArrayComparer());
protected List<int[]> shownPartions = new List<int[]>();
// Last sign marker
private LastPlacedMarkerScript lastPlacedMarker;
protected virtual void Awake() {
FILE_PATH = Application.persistentDataPath + "/Grid.txt";
// Set camera size
cameraHalfSize = new int[2];
cameraHalfSize[1] = (int) (Camera.main.orthographicSize);
cameraHalfSize[0] = (int) ((float) Camera.main.pixelWidth / Camera.main.pixelHeight) * cameraHalfSize[1];
InvokeRepeating("ShowOnlyVisiblePartions", 0.1f, UPDATE_SHOWN_TIME);
InvokeRepeating("ShowOnlyVisibleBorders", 0.2f, UPDATE_SHOWN_TIME);
InvokeRepeating("UpdateCameraPos", 0f, 1f / 40f);
// Parent gameobject of cells
cellParent = new GameObject("Cells");
// GameLogic
gameLogic = FindObjectOfType<TTTGameLogic>();
// Marker
lastPlacedMarker = FindObjectOfType<LastPlacedMarkerScript>();
}
/// <summary>
/// How many lines of data one coroutine should process
/// </summary>
private int dataProcessCount = 500;
/// <summary>
/// Load borders and signs from file
/// </summary>
public virtual void LoadFromFile() {
try {
string[] lines = System.IO.File.ReadAllLines(FILE_PATH);
if (lines.Length == 0) return;
int count = int.Parse(lines[0]);
int coroutineCount = Mathf.CeilToInt(count / (float) dataProcessCount);
for (int i = 0; i < coroutineCount; i++) {
int arrayLength = i == coroutineCount - 1 ? lines.Length - 1 - (coroutineCount - 1) * dataProcessCount : dataProcessCount;
string[] lineTemp = new string[arrayLength];
Array.Copy(lines, 1 + i * dataProcessCount, lineTemp, 0, arrayLength);
StartCoroutine("ProcessLoadedData", lineTemp);
}
} catch (Exception e) {
Debug.LogError(e.Message + " " + e.Source + " " + e.StackTrace);
}
}
/// <summary>
/// Processes lines of loaded data and the places the signs.
/// It is called ad a coroutine from LoadFromFile().
/// </summary>
private void ProcessLoadedData(string[] lines) {
string[] line;
int[] pos = new int[2];
for (int i = 0; i < lines.Length; i++) {
line = lines[i].Split(' ');
pos[0] = int.Parse(line[0]); pos[1] = int.Parse(line[1]);
PlaceSign(pos, (Cell.CellOcc) Enum.Parse(typeof(Cell.CellOcc), line[2]), true);
}
cameraLastPosLB[0] = int.MaxValue;
}
/// <summary>
/// Write borders and signs to file
/// </summary>
public virtual void WriteToFile() {
List<string> allLines = new List<string>();
int count = 0;
foreach (Partion partion in partions.Values) {
foreach (CellHolder holder in partion.GetAllCellsWhichHaveSigns()) {
if (holder.IsDisabled) { // Only write sign which are in game
allLines.Add(holder.WorldPos[0] + " " + holder.WorldPos[1] + " " + holder.CurrentTemplate.cellOcc.ToString());
count++;
}
}
}
// add how many signs there are
allLines.Insert(0, count.ToString());
try {
System.IO.File.WriteAllLines(FILE_PATH, allLines.ToArray());
} catch (Exception e) {
Debug.LogError(e.StackTrace);
}
}
/// <summary>
/// Updates the stored camera position
/// Updates quite frequently
/// </summary>
protected void UpdateCameraPos() {
// Store camera's curr pos to last pos pos
cameraLastPosLB[0] = cameraCurrPosLB[0];
cameraLastPosLB[1] = cameraCurrPosLB[1];
cameraLastPosTR[0] = cameraCurrPosTR[0];
cameraLastPosTR[1] = cameraCurrPosTR[1];
// Get camera's new pos and set curr pos to it
GetCameraCoords(out cameraCurrPosLB, out cameraCurrPosTR);
}
/// <summary>
/// Is the given gridpos in the camera's sight
/// </summary>
public bool IsInCameraSight(int[] gridPos) {
return gridPos[0] >= cameraCurrPosLB[0] + SHOW_BORDER && gridPos[0] <= cameraCurrPosTR[0] - SHOW_BORDER &&
gridPos[1] >= cameraCurrPosLB[1] + SHOW_BORDER && gridPos[1] <= cameraCurrPosTR[1] - SHOW_BORDER;
}
/// <summary>
/// This is called from the ui
/// </summary>
public void RemoveLastSignUI() {
RemoveLastSign();
}
/// <summary>
/// Removes the sign we last placed
/// </summary>
public virtual bool RemoveLastSign() {
if (numberOfSignsInGame < 1 || removeCount > 0) return false; // Only remove if we placed two signs already
// Remove sign
CellHolder cellHolder = GetCellHolderAtGridPos(previousGridPos);
if (!cellHolder.IsFull()) return false; // Return if we don't have a sign there
// At this point we surely are going to remove the sign
if (SignWasRemovedEvent != null)
SignWasRemovedEvent(previousGridPos);
cellHolder.RemoveCurrentCellWithoutStoring();
// move marker, do this before changin turns because we want the color to be the exact opposite of the sign at secondToPrevious pos
if (lastPlacedMarker != null)
lastPlacedMarker.MoveMarkerTo(new Vector2(secondToPreviousGridPos[0], secondToPreviousGridPos[1]), SignResourceStorage.Instance.GetColorRelatedTo(gameLogic.WhoseTurn));
// Revert back to previous turn in gamelogic
gameLogic.SetPreviousTurn();
// The order of these are very crucial
// We just strated a game so we want to restart it
if (numberOfSignsInGame == 1) {
gameLogic.RestartCurrentGame();
previousGridPos = null;
} else {
previousGridPos[0] = secondToPreviousGridPos[0]; previousGridPos[1] = secondToPreviousGridPos[1];
}
numberOfSignsInGame--;
removeCount++;
return true;
}
/// <summary>
/// Brings back camera to last placed sign
/// </summary>
public virtual void SetCameraToPreviousSign() {
if (previousGridPos != null)
Camera.main.transform.DOMove(new Vector3(previousGridPos[0], previousGridPos[1], Camera.main.transform.position.z), 1f, false);
}
/// <summary>
/// Used for deterimining whether to check the borders (which to show).
/// </summary>
private int[] borderLastExamineCamPos = new int[2];
/// <summary>
/// which borders should be visible
/// Updates quite frequently
/// </summary>
void ShowOnlyVisibleBorders() {
if (!HasCameraMovedSince(borderLastExamineCamPos)) return;
borderLastExamineCamPos[0] = cameraCurrPosLB[0];
borderLastExamineCamPos[1] = cameraCurrPosLB[1];
Border.UpdateBordersShown(cameraCurrPosLB, cameraCurrPosTR);
}
/// <summary>
/// Used for deterimining whether to check the partion (which to show).
/// </summary>
private int[] partionLastExamineCamPos = new int[2];
/// <summary>
/// Calculates which partions should not be shown
/// Updates quite frequently
/// </summary>
void ShowOnlyVisiblePartions() {
if (!HasCameraMovedSince(partionLastExamineCamPos)) return;
partionLastExamineCamPos[0] = cameraCurrPosLB[0];
partionLastExamineCamPos[1] = cameraCurrPosLB[1];
int[] leftBottomPart = Partion.GetPartionPosOfCell(cameraCurrPosLB);
int[] topRightPart = Partion.GetPartionPosOfCell(cameraCurrPosTR);
// Hide partions we can't see anymore
for (int i = shownPartions.Count - 1; i >= 0; i--) {
int[] at = shownPartions[i];
// Out of visibility range
if ((at[0] < leftBottomPart[0] || at[0] > topRightPart[0]) ||
(at[1] < leftBottomPart[1] || at[1] > topRightPart[1])) {
Partion p;
partions.TryGetValue(at, out p);
if (p != null) {
p.HidePartion();
shownPartions.RemoveAt(i);
}
}
}
// Show partions which are visible
for (int i = leftBottomPart[0]; i <= topRightPart[0]; i++) {
for (int k = leftBottomPart[1]; k <= topRightPart[1]; k++) {
int[] temp = new int[] { i, k };
Partion p;
partions.TryGetValue(temp, out p);
if (p != null && !p.IsShown) {
p.ShowPartion();
shownPartions.Add(temp);
}
}
}
}
/// <summary>
/// Returns the position of camera's viewport's lefbottom and topright position
/// </summary>
/// <param name="leftBottomPart"></param>
/// <param name="topRightPart"></param>
protected void GetCameraCoords(out int[] leftBottomPart, out int[] topRightPart) {
Vector2 cameraPos = Camera.main.transform.position;
int[] leftBottomPartL = new int[] {
(int) (cameraPos.x - (cameraHalfSize[0])),
(int) (cameraPos.y - (cameraHalfSize[1]))
};
int[] topRightPartL = new int[] {
(int) (cameraPos.x + (cameraHalfSize[0])),
(int) (cameraPos.y + (cameraHalfSize[1]))
};
leftBottomPartL[0] -= SHOW_BORDER; leftBottomPartL[1] -= SHOW_BORDER;
topRightPartL[0] += SHOW_BORDER; topRightPartL[1] += SHOW_BORDER;
leftBottomPart = leftBottomPartL;
topRightPart = topRightPartL;
}
/// <summary>
/// Returns whether the camera has moved compared to lastLBPos
/// </summary>
protected bool HasCameraMovedSince(int[] lastLBPos) {
return cameraCurrPosLB[0] != lastLBPos[0] || cameraCurrPosLB[1] != lastLBPos[1];
}
/// <summary>
/// Places sign at gridpos pos of type cellType
/// </summary>
/// <param name="gridPos">Grid pos of click</param>
/// <param name="cellType"></param>
/// <returns> whether the sign could be placed or not></returns>
public virtual bool PlaceSign(int[] gridPos, Cell.CellOcc cellType, bool disabled = false) {
// The partion's pos
int[] partionPos = Partion.GetPartionPosOfCell(gridPos);
// The cell's partion
Partion currP;
// We don't have a partion yet for this pos
if (!partions.ContainsKey(partionPos)) {
currP = new Partion(partionPos);
partions.Add(partionPos, currP);
} else { // we already store the partion in the dictionary
partions.TryGetValue(partionPos, out currP);
}
// At this point we should surely have the partion in p
// We need to convert the click's world pos to partion local pos
int[] localPos = Partion.GetLocalPosOfCell(gridPos);
// We need to place the sign in the partion
bool couldBePlaced = currP.PlaceSign(localPos, cellType, disabled);
if (couldBePlaced && !disabled) { // If we could place the sign store it's gridPos
if (previousGridPos != null) secondToPreviousGridPos = new int[] { previousGridPos[0], previousGridPos[1] };
previousGridPos = new int[] { gridPos[0], gridPos[1] };
// Increase amount of cells in game
numberOfSignsInGame++;
removeCount = 0; // Reset removecount to be able to remove sign again
// move marker
if (lastPlacedMarker != null)
lastPlacedMarker.MoveMarkerTo(new Vector2(gridPos[0], gridPos[1]), SignResourceStorage.Instance.GetColorRelatedTo(gameLogic.WhoseTurn == Cell.CellOcc.X ? Cell.CellOcc.O : Cell.CellOcc.X));
if (SignWasPlacedEvent != null)
SignWasPlacedEvent(gridPos, cellType);
}
return couldBePlaced;
}
/// <param name="gridPos">Where the placing is examined in gridpos</param>
/// <returns>Whether the user can place at gridPos</returns>
public bool CanPlaceAt(int[] gridPos) {
// Game has not started, explained in GameLogic
CellHolder ch = GetCellHolderAtGridPos(gridPos);
if (!gameLogic.GameSarted) {
return ch == null || !ch.IsDisabled;
}
if (ch != null && ch.IsDisabled) return false;
CellHolder[] holders = GetAllNeighbourCellHolders(gridPos);
foreach (CellHolder holder in holders) {
if (holder != null && !holder.IsDisabled && holder.IsFull()) {
return true;
}
}
return false;
}
/// <summary>
/// It disables all of the sign which belong to this game
/// </summary>
/// <param name="wonData">More data like cellgrid of current game pass in a wonData</param>
public TTTGameLogic.GameWonData StopCurrentGame(TTTGameLogic.GameWonData wonData) {
// We need to start a bejaras from the last placed sign's pos, which we happen to store in previousGridPos
// Then set all of the found sign's cellholder to disabled
// Disable marker
if (lastPlacedMarker != null)
lastPlacedMarker.Disable();
// Ended game so reset the amount of cells in game
numberOfSignsInGame = 0;
// Store all of the cellholders which have signs in game
List<CellHolder> listOfCells = new List<CellHolder>();
listOfCells.Add(GetCellHolderAtGridPos(previousGridPos));
Queue<CellHolder> queue = new Queue<CellHolder>();
queue.Enqueue(listOfCells[0]);
// Stores the min and max values of x and y (essentially bottomleft and topright corner points)
int[] min = new int[] { int.MaxValue, int.MaxValue };
int[] max = new int[] { int.MinValue, int.MinValue };
// Go through cells in this game
while (queue.Count > 0) {
CellHolder currCH = queue.Dequeue();
if (currCH.IsDisabled) break;
// Store the min and max of x and y we examine
if (currCH.WorldPos[0] < min[0]) min[0] = currCH.WorldPos[0];
if (currCH.WorldPos[0] > max[0]) max[0] = currCH.WorldPos[0];
if (currCH.WorldPos[1] < min[1]) min[1] = currCH.WorldPos[1];
if (currCH.WorldPos[1] > max[1]) max[1] = currCH.WorldPos[1];
// Disable cell
currCH.Disable();
// Get all af nthe neighbours af current cell
CellHolder[] neighbours = GetAllNeighbourCellHolders(currCH.WorldPos);
foreach (CellHolder ch in neighbours) {
if (ch != null && !ch.IsDisabled && ch.IsFull()) { // Found a cell which belongs to this game
if (!queue.Contains(ch) && !listOfCells.Contains(ch)) {
queue.Enqueue(ch);
listOfCells.Add(ch);
}
}
}
}
wonData.table = new bool[Mathf.Abs(max[0] - min[0] + 1), Mathf.Abs(max[1] - min[1] + 1)];
// Fill the thingy with true where there is a cell. Thingy defined in WonData class
foreach (CellHolder ch in listOfCells) {
wonData.table[ch.WorldPos[0] - min[0], ch.WorldPos[1] - min[1]] = true;
}
wonData.startPos = min;
// Now we can fill the holes
List<int[]> holes = wonData.GetFillableHoles();
foreach (int[] pos in holes) {
// Get the partion the cell is in (we surely have this one, because holes are between signs
int[] partionPos = Partion.GetPartionPosOfCell(pos);
Partion p;
// We don't have a partion yet for this pos
if (!partions.ContainsKey(partionPos)) {
p = new Partion(partionPos);
partions.Add(partionPos, p);
} else { // we already store the partion in the dictionary
partions.TryGetValue(partionPos, out p);
}
// Place new BLOCKED cell in partion at pos
p.PlaceSign(Partion.GetLocalPosOfCell(pos), Cell.CellOcc.BLOCKED, true);
}
return wonData;
}
/// <summary>
/// Returns whether someone has won the game based on the placement of a sign
/// So it should be called after a sign has been placed
/// </summary>
/// <param name="gridPos">Where the sign has been placed</param>
/// <returns>Returns BLOCKED when no one won yet</returns>
public TTTGameLogic.GameWonData DidWinGame(int[] gridPos) {
CellHolder currCellHolder = GetCellHolderAtGridPos(gridPos);
Cell.CellOcc currCellType = currCellHolder.CurrentTemplate.cellOcc;
// Used for return data
TTTGameLogic.GameWonData gameWonData = new TTTGameLogic.GameWonData();
CellHolder[] winCells = new CellHolder[WIN_CONDITION];
winCells[0] = currCellHolder;
// Go through directions
for (int i = 0; i <= 1; i++) {
for (int k = -1; k <= 1; k++) {
if (!(k == 0 && i == 0) && !(i == 0 && k == 1)) { // Dont want 0 0 direction or up dir
int count = 1; // Used to determine whether someone has won: if after the loop it is WIN_CONDITION someone has won
// Go till we found end in this direction or founf out that someone has won
for (int j = 1; j < WIN_CONDITION && count < WIN_CONDITION; j++) {
CellHolder ch = GetCellHolderRelativeTo(gridPos, i * j, k * j);
// ch is null
// OR ch is not full
// OR ch is disabled
// OR cell type is not the one we have in this cell
if (!(ch != null && ch.IsFull() && !ch.IsDisabled && ch.CurrentTemplate.cellOcc == currCellType)) {
break;
}
winCells[count] = ch;
count++;
}
// We need to go in the other direction as well
for (int j = 1; j < WIN_CONDITION && count < WIN_CONDITION; j++) {
CellHolder ch = GetCellHolderRelativeTo(gridPos, -i * j, -k * j);
// ch is null
// OR ch is not full
// OR ch is disabled
// OR cell type is not the one we have in this cell
if (!(ch != null && ch.IsFull() && !ch.IsDisabled && ch.CurrentTemplate.cellOcc == currCellType)) {
break;
}
winCells[count] = ch;
count++;
}
if (count >= WIN_CONDITION) {
gameWonData.gameWon = true;
gameWonData.winType = currCellType;
gameWonData.HoldersWithWon = winCells;
return gameWonData;
}
}
}
}
gameWonData.gameWon = false;
return gameWonData;
}
/// <summary>
/// Converts worldclickpos of cell to grid pos
/// </summary>
/// <param name="wordClickPos"></param>
/// <returns></returns>
public static int[] GetCellInGridPos(Vector2 wordClickPos) {
int[] gridPos = new int[2];
gridPos[0] = Mathf.CeilToInt(wordClickPos[0]);
gridPos[1] = Mathf.CeilToInt(wordClickPos[1]);
return gridPos;
}
/// <summary>
/// Return cellHolder at gridPos
/// </summary>
/// <param name="gridPos">Position of cell in grid</param>
/// <returns>May return null</returns>
public CellHolder GetCellHolderAtGridPos(int[] gridPos) {
int[] partionPos = Partion.GetPartionPosOfCell(gridPos);
int[] partionLocalPos = Partion.GetLocalPosOfCell(gridPos);
Partion p;
partions.TryGetValue(partionPos, out p);
if (p != null) {
return p.GetCellHolderAt(partionLocalPos);
}
return null;
}
/// <summary>
/// The neighbours start from bottomleft and go first right then up in rows
/// </summary>
/// <param name="gridPos">The gridpos of the cell of which we want the neighbours</param>
/// <returns>An array with a length of 8 in the order seen above</returns>
public CellHolder[] GetAllNeighbourCellHolders(int[] gridPos) {
CellHolder[] neighbours = new CellHolder[8];
int at = 0;
for (int i = -1; i <= 1; i++) {
for (int k = -1; k <= 1; k++) {
if (!(k == 0 && i == 0)) { // We don't want to return the cell itself
neighbours[at] = GetCellHolderRelativeTo(gridPos, i, k);
at++;
}
}
}
return neighbours;
}
/// <summary>
/// The neighbours are in this order: Top Right Bottom Left
/// </summary>
/// <param name="gridPos">The gridpos of the cell of which we want the neighbours</param>
/// <returns>An array with a length of 4 in the order seen above</returns>
public CellHolder[] GetNeighbourCellHolders(int[] gridPos) {
CellHolder[] holders = new CellHolder[4];
holders[0] = GetUpwardCellHolder(gridPos);
holders[1] = GetRightCellHolder(gridPos);
holders[2] = GetDownwardCellHolder(gridPos);
holders[3] = GetLeftCellHolder(gridPos);
return holders;
}
/// <summary>
/// Gets the right cellholder of the given gridpos cell
/// </summary>
/// <param name="gridPos"></param>
/// <returns>Returns null if the cellholder does not exists</returns>
public CellHolder GetRightCellHolder(int[] gridPos) {
return GetCellHolderRelativeTo(gridPos, 1, 0);
}
/// <summary>
/// Gets the left cellholder of the given gridpos cell
/// </summary>
/// <param name="gridPos"></param>
/// <returns>Returns null if the cellholder does not exists</returns>
public CellHolder GetLeftCellHolder(int[] gridPos) {
return GetCellHolderRelativeTo(gridPos, -1, 0);
}
/// <summary>
/// Gets the upward cellholder of the given gridpos cell
/// </summary>
/// <param name="gridPos"></param>
/// <returns>Returns null if the cellholder does not exists</returns>
public CellHolder GetUpwardCellHolder(int[] gridPos) {
return GetCellHolderRelativeTo(gridPos, 0, 1);
}
/// <summary>
/// Gets the downward cellholder of the given gridpos cell
/// </summary>
/// <param name="gridPos"></param>
/// <returns>Returns null if the cellholder does not exists</returns>
public CellHolder GetDownwardCellHolder(int[] gridPos) {
return GetCellHolderRelativeTo(gridPos, 0, -1);
}
/// <summary>
/// Gets the cellholder of the cell relative to gridpos with the eltolas of x and y on those axis
/// Currently only using it for right, left, up and down
/// In other cases may crash so be aware
/// </summary>
/// <param name="gridPos">Grid pos of cell</param>
/// <param name="x">X axis relative</param>
/// <param name="y">Y axis relative</param>
/// <returns>Returns null if can't find cellholder</returns>
public CellHolder GetCellHolderRelativeTo(int[] gridPos, int x, int y) {
int[] relativePos = new int[] {
gridPos[0] + x,
gridPos[1] + y
};
// gets partion and local pos of relative cell
int[] partionPos = Partion.GetPartionPosOfCell(relativePos);
int[] partionLocalPos = Partion.GetLocalPosOfCell(relativePos);
Partion p;
partions.TryGetValue(partionPos, out p);
// There is no partion at this coord yet
if (p == null) return null;
return p.GetCellHolderAt(partionLocalPos);
}
/// <summary>
/// Used for array if partions
/// </summary>
public class IntegerArrayComparer : IEqualityComparer<int[]> {
public bool Equals(int[] x, int[] y) {
if (x.Length != y.Length) {
return false;
}
for (int i = 0; i < x.Length; i++) {
if (x[i] != y[i]) {
return false;
}
}
return true;
}
public int GetHashCode(int[] obj) {
int result = 17;
for (int i = 0; i < obj.Length; i++) {
unchecked {
result = result * 23 + obj[i];
}
}
return result;
}
}
public struct SignStoreInFile {
public int x;
public int y;
public string type;
public SignStoreInFile(int x, int y, string type) {
this.x = x;
this.y = y;
this.type = type;
}
}
}
| |
namespace Nancy.Tests.Unit
{
using System;
using System.Linq;
using System.Threading.Tasks;
using Nancy.Tests.Fakes;
using Xunit;
public class NancyModuleFixture
{
private readonly NancyModule module;
public NancyModuleFixture()
{
this.module = new FakeNancyModuleNoRoutes();
}
[Fact]
public void Adds_route_when_get_indexer_used()
{
// Given, When
this.module.Get<object>("/test", (_, __) => null);
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Adds_route_when_put_indexer_used()
{
// Given, When
this.module.Put<object>("/test", (_, __) => null);
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Adds_route_when_post_indexer_used()
{
// Given, When
this.module.Post<object>("/test", (_, __) => null);
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Adds_route_when_delete_indexer_used()
{
// Given, When
this.module.Delete<object>("/test", (_, __) => null);
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Adds_route_when_options_indexer_userd()
{
// Given, When
this.module.Options<object>("/test", (_, __) => null);
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Should_store_route_with_specified_path_when_route_indexer_is_invoked_with_a_path_but_no_condition()
{
// Given, When
this.module.Get<object>("/test", (_, __) => null);
// Then
module.Routes.First().Description.Path.ShouldEqual("/test");
}
[Fact]
public void Should_store_route_with_specified_path_when_route_indexer_is_invoked_with_a_path_and_condition()
{
// Given
Func<NancyContext, bool> condition = r => true;
// When
this.module.Get<object>("/test",
condition: condition,
action: (_, __) => null);
// Then
module.Routes.First().Description.Path.ShouldEqual("/test");
}
[Fact]
public void Should_store_route_with_null_condition_when_route_indexer_is_invoked_without_a_condition()
{
// Given, When
this.module.Get<object>("/test", (_, __) => null);
// Then
module.Routes.First().Description.Condition.ShouldBeNull();
}
[Fact]
public void Should_store_route_with_condition_when_route_indexer_is_invoked_with_a_condition()
{
// Given
Func<NancyContext, bool> condition = r => true;
// When
this.module.Get<object>("/test",
condition: condition,
action: (_, __) => null);
// Then
module.Routes.First().Description.Condition.ShouldBeSameAs(condition);
}
[Fact]
public void Should_add_route_with_get_method_when_added_using_get_indexer()
{
// Given, When
this.module.Get<object>("/test", (_, __) => null);
// Then
module.Routes.First().Description.Method.ShouldEqual("GET");
}
[Fact]
public void Should_add_route_with_put_method_when_added_using_get_indexer()
{
// Given, When
this.module.Put<object>("/test", (_, __) => null);
// Then
module.Routes.First().Description.Method.ShouldEqual("PUT");
}
[Fact]
public void Should_add_route_with_post_method_when_added_using_get_indexer()
{
// Given, When
this.module.Post<object>("/test", (_, __) => null);
// Then
module.Routes.First().Description.Method.ShouldEqual("POST");
}
[Fact]
public void Should_add_route_with_delete_method_when_added_using_get_indexer()
{
// Given, When
this.module.Delete<object>("/test", (_, __) => null);
// Then
module.Routes.First().Description.Method.ShouldEqual("DELETE");
}
[Fact]
public void Should_store_route_combine_with_base_path_if_one_specified()
{
// Given
var moduleWithBasePath = new FakeNancyModuleWithBasePath();
// When
moduleWithBasePath.Get("/NewRoute", args => Task.FromResult<object>(null));
// Then
moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual("/fake/NewRoute");
}
[Fact]
public void Should_add_leading_slash_to_route_if_missing()
{
// Given
var moduleWithBasePath = new FakeNancyModuleWithBasePath();
// When
moduleWithBasePath.Get<object>("/test", (_, __) => null);
// Then
moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual("/fake/test");
}
[Fact]
public void Should_store_single_route_when_calling_non_overridden_post_from_sub_module()
{
// Given
var moduleWithBasePath = new CustomNancyModule();
// When
moduleWithBasePath.Post<object>("/Test1", (_, __) => null);
// Then
moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual("/Test1");
}
[Fact]
public void Should_not_throw_when_null_passed_as_modulepath()
{
// Given
var moduleWithNullPath = new CustomModulePathModule(null);
// When
moduleWithNullPath.Post<object>("/Test1", (_, __) => null);
// Then
moduleWithNullPath.Routes.Count().ShouldBeGreaterThan(0);
}
[Fact]
public void Adds_named_route_when_named_indexer_used()
{
// Given, When
this.module.Get<object>("/test",
name: "Foo",
action: (_, __) => null);
// Then
this.module.Routes.Count().ShouldEqual(1);
this.module.Routes.First().Description.Name.ShouldEqual("Foo");
}
private class CustomModulePathModule : NancyModule
{
public CustomModulePathModule(string modulePath)
: base(modulePath)
{
}
}
private class CustomNancyModule : NancyModule
{
}
}
}
| |
using System;
using System.Globalization;
using System.Threading;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using EIDSS.Web;
using bv.common.Core;
using eidss.model.Core;
using eidss.model.Core.Security;
using eidss.model.Enums;
namespace Eidss.Web
{
/// <summary>
/// Summary description for OpenArchitecture
/// </summary>
[WebService(Namespace = "http://bv.com/eidss")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class EidssService : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public HumanCaseListInfo[] GetHumanCaseList(HumanCaseListInfo filter)
{
Check(PermissionHelper.SelectPermission(EIDSSPermissionObject.HumanCase));
return HumanCaseListInfo.GetAll(filter);
}
[WebMethod(EnableSession = true)]
public VetCaseListInfo[] GetVetCaseList(VetCaseListInfo filter)
{
Check(PermissionHelper.SelectPermission(EIDSSPermissionObject.VetCase));
return VetCaseListInfo.GetAll(filter);
}
[WebMethod(EnableSession = true)]
public DiagnosisLookupItem[] GetDiagnosisList(int code)
{
Check(null);
return DiagnosisLookupItem.GetDiagnosisList(code);
}
[WebMethod(EnableSession = true)]
public RayonLookupItem[] GetRayonList(long region)
{
Check(null);
return RayonLookupItem.GetListByRegionId(region);
}
[WebMethod(EnableSession = true)]
public RegionLookupItem[] GetRegionList()
{
Check(null);
return RegionLookupItem.GetAll();
}
[WebMethod(EnableSession = true)]
public BaseReferenceItem[] GetBaseReferenceList(long type)
{
Check(null);
return BaseReferenceItem.GetList(type);
}
[WebMethod(EnableSession = true)]
public HumanCaseInfo GetHumanCase(string id)
{
Check(PermissionHelper.SelectPermission(EIDSSPermissionObject.HumanCase));
return HumanCaseInfo.GetById(id);
}
[WebMethod(EnableSession = true)]
public VetCaseInfo GetVetCase(string id)
{
Check(PermissionHelper.SelectPermission(EIDSSPermissionObject.VetCase));
return VetCaseInfo.GetById(id);
}
[WebMethod(EnableSession = true)]
public string CreateHumanCase(HumanCaseInfo hc)
{
Check(PermissionHelper.InsertPermission(EIDSSPermissionObject.HumanCase));
hc.Save(true);
return hc.Id.ToString();
}
[WebMethod(EnableSession = true)]
public void EditHumanCase(HumanCaseInfo hc)
{
Check(PermissionHelper.UpdatePermission(EIDSSPermissionObject.HumanCase));
hc.Save(true);
}
[WebMethod(EnableSession = true)]
public SampleInfo[] GetSampleList(SampleInfo filter)
{
Check(PermissionHelper.SelectPermission(EIDSSPermissionObject.Sample));
return SampleInfo.GetAll(filter);
}
[WebMethod(EnableSession = true)]
public TestInfo[] GetTestList(TestInfo filter)
{
Check(PermissionHelper.SelectPermission(EIDSSPermissionObject.Test));
return TestInfo.GetAll(filter);
}
/*
[WebMethod(EnableSession = true)]
public AnimalInfo[] GetAnimalList()
{
Check(PermissionHelper.SelectPermission (EIDSSPermissionObject.VetCase));
return ((List<AnimalInfo>)AnimalInfo.GetAll()).ToArray();
}
*/
protected void Check(string permission)
{
if (EidssUserContext.User == null || EidssUserContext.User.ID == null)
throw new SoapException("Login required", SoapException.ClientFaultCode);
if (permission != null && EidssUserContext.User.HasPermission(permission) == false)
throw new SoapException("Access denied", SoapException.ClientFaultCode);
}
[WebMethod(EnableSession = true)]
public void Login(string Organization, string User, string Password, string Language)
{
if (!Localizer.SupportedLanguages.ContainsKey(Language))
{
throw new SoapException("Language is not supported", SoapException.ClientFaultCode);
}
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Localizer.SupportedLanguages[Language]);
var security = new EidssSecurityManager();
var result = security.LogIn(Organization, User, Password);
if (result == 0) //authorized
{
//set current language
EidssUserContext.CurrentLanguage = Language;
}
else
{
throw new SoapException(SecurityMessages.GetLoginErrorMessage(result), SoapException.ClientFaultCode);
}
}
[WebMethod(EnableSession = true)]
public bool SaveHumanCases(string Organization, string User, string Password, string Language,
HumanCaseInfo[] hc_in, out HumanCaseInfo[] hc_out)
{
hc_out = null;
var security = new EidssSecurityManager();
var result = security.LogIn(Organization, User, Password);
if (result == 0) //authorized
{
EidssUserContext.CurrentLanguage = Language;
Thread.CurrentThread.CurrentCulture = new CultureInfo(Language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Language);
Check(PermissionHelper.InsertPermission(EIDSSPermissionObject.HumanCase));
Check(PermissionHelper.UpdatePermission(EIDSSPermissionObject.HumanCase));
var list = new List<HumanCaseInfo>();
hc_in.ToList().ForEach(c =>
{
if (c.Id == 0)
{
c.NotificationDate = DateTime.Today;
c.NotificationSentBy.Id = EidssSiteContext.Instance.OrganizationID;
c.NotificationSentBy.Name = EidssSiteContext.Instance.OrganizationName;
c.NotificationSentByPerson.Id = (long) EidssUserContext.User.ID;
c.NotificationSentByPerson.Name = EidssUserContext.User.FullName;
}
c.Save(c.Id == 0);
list.Add(c);
});
hc_out = list.ToArray();
return true;
}
return false;
}
[WebMethod(EnableSession = true)]
public bool LoadReferences(string Organization, string User, string Password,
long[] types, string[] langs,
out BaseReferenceRaw[] refs, out BaseReferenceTranslationRaw[] refs_trans,
out GisBaseReferenceRaw[] gis_refs, out GisBaseReferenceTranslationRaw[] gis_refs_trans)
{
refs = null;
refs_trans = null;
gis_refs = null;
gis_refs_trans = null;
var security = new EidssSecurityManager();
var result = security.LogIn(Organization, User, Password);
if (result == 0) //authorized
{
refs = BaseReferenceRaw.GetList(types);
refs_trans = BaseReferenceTranslationRaw.GetList(types, langs);
gis_refs = GisBaseReferenceRaw.GetAll();
gis_refs_trans = GisBaseReferenceTranslationRaw.GetAll(langs);
return true;
}
return false;
}
[WebMethod(EnableSession = true)]
public HumanCaseInfo[] SaveHumanCases2(string Organization, string User, string Password, string Language, HumanCaseInfo[] hc_in)
{
//HttpContext.Current.Request.SaveAs(@"C:\Work\temporary\test.txt", true);
var security = new EidssSecurityManager();
var result = security.LogIn(Organization, User, Password);
if (result == 0) //authorized
{
EidssUserContext.CurrentLanguage = Language;
Thread.CurrentThread.CurrentCulture = new CultureInfo(Language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Language);
Check(PermissionHelper.InsertPermission(EIDSSPermissionObject.HumanCase));
Check(PermissionHelper.UpdatePermission(EIDSSPermissionObject.HumanCase));
var list = new List<HumanCaseInfo>();
hc_in.ToList().ForEach(c =>
{
if (c.Id == 0)
{
c.NotificationDate = DateTime.Today;
c.NotificationSentBy.Id = EidssSiteContext.Instance.OrganizationID;
c.NotificationSentBy.Name = EidssSiteContext.Instance.OrganizationName;
c.NotificationSentByPerson.Id = (long)EidssUserContext.User.ID;
c.NotificationSentByPerson.Name = EidssUserContext.User.FullName;
}
try
{
c.Save(c.Id == 0);
}
catch(SoapException)
{
}
list.Add(c);
});
return list.ToArray();
}
return null;
}
[WebMethod(EnableSession = true)]
public BaseReferenceRaw[] LoadReference(string Organization, string User, string Password, long type)
{
var security = new EidssSecurityManager();
var result = security.LogIn(Organization, User, Password);
if (result == 0) //authorized
{
return BaseReferenceRaw.GetList(new[] { type });
}
return null;
}
[WebMethod(EnableSession = true)]
public BaseReferenceTranslationRaw[] LoadReferenceTranslation(string Organization, string User, string Password, long type, string lang)
{
var security = new EidssSecurityManager();
var result = security.LogIn(Organization, User, Password);
if (result == 0) //authorized
{
return BaseReferenceTranslationRaw.GetList(new[]{type}, new[]{lang});
}
return null;
}
[WebMethod(EnableSession = true)]
public GisBaseReferenceRaw[] LoadGisReference(string Organization, string User, string Password)
{
var security = new EidssSecurityManager();
var result = security.LogIn(Organization, User, Password);
if (result == 0) //authorized
{
return GisBaseReferenceRaw.GetAll();
}
return null;
}
[WebMethod(EnableSession = true)]
public GisBaseReferenceTranslationRaw[] LoadGisReferenceTranslation(string Organization, string User, string Password, string lang)
{
var security = new EidssSecurityManager();
var result = security.LogIn(Organization, User, Password);
if (result == 0) //authorized
{
return GisBaseReferenceTranslationRaw.GetAll(new []{lang});
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Net;
using System.Threading.Tasks;
using TddEbook.TddToolkit.Generators;
using TddEbook.TddToolkit.Subgenerators;
using Type = System.Type;
namespace TddEbook.TddToolkit
{
public partial class Any
{
private static readonly AllGenerator Generate = AllGeneratorFactory.Create();
public static IPAddress IpAddress()
{
return Generate.IpAddress();
}
public static T ValueOtherThan<T>(params T[] omittedValues)
{
return Generate.ValueOtherThan(omittedValues);
}
public static T From<T>(params T[] possibleValues)
{
return Generate.From(possibleValues);
}
public static DateTime DateTime()
{
return Generate.DateTime();
}
public static TimeSpan TimeSpan()
{
return Generate.TimeSpan();
}
public static T ValueOf<T>()
{
return Generate.ValueOf<T>();
}
public static IEnumerable<T> EmptyEnumerableOf<T>()
{
return Generate.EmptyEnumerableOf<T>();
}
public static string LegalXmlTagName()
{
return Generate.LegalXmlTagName();
}
public static bool Boolean()
{
return Generate.Boolean();
}
public static object Object()
{
return Generate.Object();
}
public static T Exploding<T>() where T : class
{
return Generate.Exploding<T>();
}
public static MethodInfo Method()
{
return Generate.Method();
}
public static Type Type()
{
return Generate.Type();
}
public static T InstanceOf<T>()
{
return Generate.InstanceOf<T>();
}
public static T Instance<T>()
{
return Generate.Instance<T>();
}
public static T Dummy<T>()
{
return Generate.Dummy<T>();
}
#pragma warning disable CC0068 // Unused Method
#pragma warning disable S1144 // Unused private types or members should be removed
[SuppressMessage("ReSharper", "UnusedMember.Local")]
private static T InstanceOtherThanObjects<T>(params object[] omittedValues)
{
return Generate.InstanceOtherThanObjects<T>(omittedValues);
}
#pragma warning restore S1144 // Unused private types or members should be removed
#pragma warning restore CC0068 // Unused Method
public static T SubstituteOf<T>() where T : class
{
return Generate.SubstituteOf<T>();
}
public static T OtherThan<T>(params T[] omittedValues)
{
return Generate.OtherThan(omittedValues);
}
public static Uri Uri()
{
return Generate.Uri();
}
public static Guid Guid()
{
return Generate.Guid();
}
public static string UrlString()
{
return Generate.UrlString();
}
public static Exception Exception()
{
return Generate.Exception();
}
public static int Port()
{
return Generate.Port();
}
public static string Ip()
{
return Generate.Ip();
}
public static object Instance(Type type)
{
return Generate.Instance(type);
}
public static IEnumerable<T> EnumerableWith<T>(IEnumerable<T> included)
{
return Generate.EnumerableWith(included);
}
public static Task NotStartedTask()
{
return Generate.NotStartedTask();
}
public static Task<T> NotStartedTask<T>()
{
return Generate.NotStartedTask<T>();
}
public static Task StartedTask()
{
return Generate.StartedTask();
}
public static Task<T> StartedTask<T>()
{
return Generate.StartedTask<T>();
}
public static Func<T> Func<T>()
{
return Generate.Func<T>();
}
public static Func<T1, T2> Func<T1, T2>()
{
return Generate.Func<T1, T2>();
}
public static Func<T1, T2, T3> Func<T1, T2, T3>()
{
return Generate.Func<T1, T2, T3>();
}
public static Func<T1, T2, T3, T4> Func<T1, T2, T3, T4>()
{
return Generate.Func<T1, T2, T3, T4>();
}
public static Func<T1, T2, T3, T4, T5> Func<T1, T2, T3, T4, T5>()
{
return Generate.Func<T1, T2, T3, T4, T5>();
}
public static Func<T1, T2, T3, T4, T5, T6> Func<T1, T2, T3, T4, T5, T6>()
{
return Generate.Func<T1, T2, T3, T4, T5, T6>();
}
public static Action Action()
{
return Generate.Action();
}
public static Action<T> Action<T>()
{
return Generate.Action<T>();
}
public static Action<T1, T2> Action<T1, T2>()
{
return Generate.Action<T1, T2>();
}
public static Action<T1, T2, T3> Action<T1, T2, T3>()
{
return Generate.Action<T1, T2, T3>();
}
public static Action<T1, T2, T3, T4> Action<T1, T2, T3, T4>()
{
return Generate.Action<T1, T2, T3, T4>();
}
public static Action<T1, T2, T3, T4, T5> Action<T1, T2, T3, T4, T5>()
{
return Generate.Action<T1, T2, T3, T4, T5>();
}
public static Action<T1, T2, T3, T4, T5, T6> Action<T1, T2, T3, T4, T5, T6>()
{
return Generate.Action<T1, T2, T3, T4, T5, T6>();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.